Compare commits

...

185 Commits

Author SHA1 Message Date
Andy 7649a607e6 Merge pull request #69 from AndyMik90/v2.6.0
Version 2.6.0
2025-12-20 14:36:09 +01:00
AndyMik90 f89e4e6c56 fix: create coroutine inside worker thread for asyncio.run
The coroutine was being created on the main thread before being passed
to ThreadPoolExecutor. This is incorrect as coroutines should be created
and run in the same thread. Use a lambda to defer coroutine creation
until execution inside the worker thread.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 14:31:18 +01:00
AndyMik90 b9797cbe21 fix: improve UX for phase configuration in task creation
Add visual affordances to make it clear that the Phase Configuration
section is clickable and editable:

- Add pencil icon and "Click to customize" text in collapsed state
- Improve hover state on the header
- Add labels for Model and Thinking columns in expanded state
- Better visual separation between collapsed and expanded states

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 13:40:56 +01:00
AndyMik90 cc38a0619c fix: address CodeRabbit PR #69 feedback
Security fixes:
- Fix Windows command injection vulnerability in terminal-handlers.ts
  by adding escapeShellArgWindows() for proper cmd.exe escaping
- Fix OAuth race condition in device code extraction using mutex pattern

Bug fixes:
- Fix settings migration to preserve existing user profile selections
  instead of unconditionally overwriting them
- Fix asyncio.run() to handle existing event loops by using ThreadPoolExecutor
- Add error logging for migration persistence failures

UX improvements:
- Add cleanup for copy feedback timeouts in GitHubOAuthFlow to prevent
  setState on unmounted component warnings
- Add error handling for failed agent profile saves

Type safety:
- Add _migratedAgentProfileToAuto to AppSettings interface
- Fix GraphitiStep type to use Partial<Pick<AppSettings, ...>>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 13:38:50 +01:00
AndyMik90 aee0ba4cc5 feat: add customizable phase configuration in app settings
Allow users to customize the model and thinking level for each phase
(Spec Creation, Planning, Coding, QA Review) when using the Auto profile.
These settings are persisted in app settings and used as defaults when
creating new tasks.

Changes:
- Add customPhaseModels and customPhaseThinking to AppSettings type
- Update AgentProfileSettings to show editable phase configuration
  when Auto profile is selected
- Update TaskCreationWizard to initialize from custom settings
- Phase config can still be overridden per-task in task creation wizard

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 13:38:38 +01:00
AndyMik90 9981ee4469 fix: sort imports in workspace.py to pass ruff I001 check 2025-12-20 13:38:11 +01:00
AndyMik90 297d380f4c fix(ui): auto-close task modal when marking task as done
Previously, clicking "Mark as Done" or "Delete Worktree & Mark Done"
  would update the task status but leave the modal open, requiring an
  extra click on "Close". Now the modal automatically closes after
  successfully marking a task as done for better UX.
2025-12-20 13:30:08 +01:00
AndyMik90 05062562f0 fix: resolve Python lint errors in workspace.py
- Consolidate split import blocks for core.workspace.display and core.workspace.git_utils
- Remove duplicate module-level `import re` (already imported in function scope)
- Sort import block alphabetically (asyncio, logging, os)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 13:25:53 +01:00
AndyMik90 438f6e2237 Merge branch 'auto-claude/050-github-connection-will-not-open-browser-on-macos' into v2.6.0 2025-12-20 13:22:07 +01:00
AndyMik90 458d4bb97a feat: implement parallel AI merge functionality
Add the ability to perform parallel merges using AI for conflict resolution. This includes the implementation of the `_run_parallel_merges` function, which processes multiple merge tasks concurrently, and the `_merge_file_with_ai_async` function for handling individual file merges.

Key changes:
- Introduced AI-based merging logic with a system prompt for 3-way merges.
- Added helper functions for inferring file types and building merge prompts.
- Updated tests to cover various scenarios for the new merging functionality.

This enhancement allows for more efficient handling of merge conflicts, leveraging AI to ensure accurate and context-aware resolutions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2025-12-20 13:19:57 +01:00
AndyMik90 10949905f7 refactor: move Agent Profiles from dashboard to Settings
Move the Agent Profiles configuration from a separate dashboard tab
to the Settings page under "Agent Settings". This provides a more
intuitive location for users to configure their default agent profile.

Changes:
- Create AgentProfileSettings component for settings page
- Add agent profiles to GeneralSettings 'agent' section
- Remove 'agent-profiles' from sidebar navigation
- Remove AgentProfiles view from App.tsx routing
- Update SidebarView type

The agent profiles are now accessible via Settings > Agent Settings,
alongside other agent-related configuration options.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 12:37:47 +01:00
AndyMik90 9ab5a4f2cc fix(planning): ensure planner agent writes implementation_plan.json
- Add explicit Write tool instructions to planner.md prompt
- Clarify that agent must use Write tool, not just describe file contents
- Fix PROMPTS_DIR path in prompts.py to correctly reference prompts/ directory
- Add checkpoint reminder in Phase 4 to verify Write tool was used
- Add critical instructions for all file creation phases (init.sh, build-progress.txt)

Fixes #38

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 12:37:00 +01:00
AndyMik90 f0a6a0a0af fix(windows): add platform detection for terminal profile commands
- Use cmd.exe syntax (set/%) on Windows
- Use bash syntax (export/$) on Unix/macOS

Fixes #51

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 12:34:45 +01:00
AndyMik90 cdda3ff277 Suggested commit message 2025-12-20 12:20:02 +01:00
AndyMik90 08aa2ff02b fix: default agent profile to 'Auto (Optimized)' for all users
Add one-time migration to reset selectedAgentProfile to 'auto' for
existing users. This ensures the optimized per-phase model selection
is the default experience for everyone.

The migration:
- Runs once on settings load (tracked by _migratedAgentProfileToAuto flag)
- Sets selectedAgentProfile to 'auto'
- Persists the change to settings.json
- Users can still change their preference afterward

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 12:18:39 +01:00
AndyMik90 37ace0a39a fix: update default selected agent profile to 'auto'
Changed the default value for the selected agent profile from 'balanced' to 'auto' in the AgentProfiles component to improve user experience and align with expected behavior.
2025-12-20 12:10:05 +01:00
AndyMik90 7f0eeba366 chore: bump version to 2.6.0
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 12:08:45 +01:00
AndyMik90 f82bd5b871 linting 2025-12-20 12:02:30 +01:00
AndyMik90 f117bccbbc Merge branch 'auto-claude/056-add-design-system-themes-to-electron-app' into v2.6.0 2025-12-20 11:58:43 +01:00
AndyMik90 8b59375404 fix: extract human-readable title from spec.md when feature field is spec ID
When the implementation_plan.json feature field contains the spec directory
name (e.g., "054-version-2-5-5-displays-version-2-5-0-in-updater") instead
of a human-readable title, the task card and modal showed the ugly spec ID.

Now detects when the feature field looks like a spec ID (starts with 3 digits
and a dash) and extracts the actual title from spec.md's first heading,
handling prefixes like "Quick Spec:" and "Specification:".

Example: "054-version..." → "Fix Version 2.5.5 Display in Updater"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 11:44:21 +01:00
AndyMik90 91a1e3df6c fix: resolve multiple platform and UI issues
Authentication:
- Add macOS Keychain token retrieval support to auth.py
- Fix UsageMonitor to decrypt tokens before API calls

Task Status:
- Fix JSON cache not updating on successful parse
- Replace one-time stuck detection with periodic re-checking
- Add visibility change handler for focus re-validation

Windows:
- Use temp file for insights history to avoid ENAMETOOLONG

Linux/Ubuntu:
- Handle non-UTF-8 file encoding with errors='replace'
- Add tomli fallback for Python 3.10 compatibility

UI:
- Fix ROADMAP_SAVE handler parameter type mismatch

Fixes #21, #43, #15, #45, #61, #42, #62, #58, #48, #49, #46

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 11:38:05 +01:00
AndyMik90 7f12ef0355 fix: task descriptions not showing for specs with compact markdown
Tasks like spec 053 were missing descriptions in the kanban board and
task modal because the regex for extracting the overview from spec.md
required two newlines after "## Overview" (a blank line).

Specs generated with compact markdown (no blank line after headers)
were not matched, resulting in empty descriptions.

Changes:
- Fix regex to accept one or more newlines: /## Overview\s*\n+/
- Add fallback to read from requirements.json task_description field
- Extract meaningful content from GitHub issue descriptions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 11:37:16 +01:00
AndyMik90 30921550df style: enhance WorkspaceStatus component UI
Updated the styling of the "Stage only" option in the WorkspaceStatus component for improved user experience. Changes include a more visually appealing label with rounded corners and hover effects, as well as dynamic text color based on the checkbox state. This enhances the overall design consistency and interactivity of the UI.
2025-12-20 11:29:34 +01:00
AndyMik90 2b96160ab0 fix: display correct merge target branch in worktree UI
The UI was showing "→ main" for all worktree merges because it checked
origin/HEAD (the remote's default branch) instead of the user's current
local branch.

This caused confusion since the actual merge logic in Python correctly
merges into the user's current branch (e.g., v2.6.0), but the UI
displayed "→ main".

Changed baseBranch detection from origin/HEAD to the current local
branch (git rev-parse --abbrev-ref HEAD) in three handlers:
- TASK_WORKTREE_STATUS
- TASK_WORKTREE_DIFF
- TASK_LIST_WORKTREES

Now the UI accurately reflects where changes will be merged.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 11:24:31 +01:00
AndyMik90 7171589002 Cleanup UI design for build review process 2025-12-20 11:14:15 +01:00
AndyMik90 2a96f855ae Improvement/refactor task sidebar to task modal 2025-12-20 11:08:44 +01:00
Andy 3ac3f067cc Merge pull request #33 from adryserage/feature/graphiti-multi-provider-support
feat(graphiti): add Google AI as LLM and embedding provider
2025-12-20 10:09:03 +01:00
Andy 535d58c80f Merge branch 'main' into feature/graphiti-multi-provider-support 2025-12-20 10:08:49 +01:00
AndyMik90 2ef90b980f auto-claude: 5.2 - Add validation for invalid colorTheme fallback
Verify theme settings persist after app restart:
- Settings stored in settings.json via Electron IPC
- colorTheme included in DEFAULT_APP_SETTINGS

Add invalid colorTheme fallback to 'default':
- Added validation against COLOR_THEMES array
- Invalid stored values now fallback to 'default'

Verify system mode preference detection:
- Uses matchMedia API with event listener
- Correctly handles 'system' mode preference

Ensure no CSS flash on load:
- Default theme uses :root CSS (no data-theme attribute)
- Settings initialize with colorTheme: 'default'
- IPC loads fast (local process, not network)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 02:01:44 +01:00
AndyMik90 e6654b96c5 auto-claude: 4.2 - Remove the Sun/Moon toggle button from the Sidebar
Removed theme toggle functionality from sidebar header:
- Removed Sun/Moon toggle button from header section
- Removed toggleTheme function and isDark calculation
- Removed unused Moon, Sun icons from lucide-react imports
- Removed unused saveSettings import

Theme selection is now exclusively in Settings > Appearance via
the ThemeSelector component which provides full 7-theme support
with light/dark/system mode toggle.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 01:49:17 +01:00
AndyMik90 5db28fd8e8 auto-claude: 4.1 - Modify the theme application useEffect in App.tsx
Updated the theme application useEffect to set/remove the data-theme
attribute on document.documentElement based on settings.colorTheme.
- Default theme removes the data-theme attribute
- Other themes set data-theme="themeName"
- Added settings.colorTheme to useEffect dependency array
- Falls back to 'default' if colorTheme is undefined

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 01:46:57 +01:00
AndyMik90 c1207ef7fc auto-claude: 3.2 - Replace simple mode toggle with ThemeSelector component
- Updated ThemeSettings.tsx to use the new ThemeSelector component
- Removed old 3-button mode toggle in favor of full theme selector grid
- ThemeSelector provides both color theme selection (7 themes) and mode toggle
- Simplified ThemeSettings to act as a wrapper with consistent section layout

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 01:45:24 +01:00
AndyMik90 70072e4281 auto-claude: 3.1 - Create ThemeSelector component with theme grid and mode toggle
- Create ThemeSelector.tsx component in settings folder
- Display a grid of theme cards showing name, description, and preview color swatches
- Preview swatches show bg/accent colors based on current light/dark mode
- Include a 3-option mode toggle (Light/Dark/System)
- Handle selection via props callbacks (onSettingsChange pattern)
- Export component from settings barrel file

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 01:43:32 +01:00
AndyMik90 ba776a3fb8 auto-claude: 2.6 - Add forest theme CSS with natural green palette
Add [data-theme="forest"] and [data-theme="forest"].dark CSS blocks with
natural green palette mapped to app variables:

Light mode:
- Background: #DCFCE7 (soft mint green)
- Foreground: #14532D (dark forest green)
- Primary accent: #16A34A (natural green)
- Borders: #86EFAC (light green)

Dark mode:
- Background: #052E16 (deep forest)
- Foreground: #F0FDF4 (near white with green tint)
- Primary accent: #4ADE80 (bright green)
- Card surfaces: #166534 (medium forest green)

Follows existing theme patterns for dusk, lime, ocean, retro, neo.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 01:40:51 +01:00
AndyMik90 e2b24e2e25 auto-claude: 2.5 - Add [data-theme="neo"] and [data-theme="neo"].dark
Add Neo theme CSS blocks with cyberpunk pink/purple palette:
- Light mode: soft lavender background (#FDF4FF), fuchsia accent (#D946EF)
- Dark mode: deep purple background (#0F0720), bright pink accent (#F0ABFC)
- Dark mode includes unique neon glow shadows for cyberpunk aesthetic
- All color variables mapped to app's existing variable naming convention

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 01:39:07 +01:00
AndyMik90 7589046bbe auto-claude: 2.4 - Add Retro theme CSS variables (light and dark)
Add [data-theme="retro"] and [data-theme="retro"].dark CSS blocks with
warm amber/orange palette mapped to app variables:

Light mode:
- Background: #FEF3C7 (warm cream/amber)
- Primary accent: #D97706 (amber/orange)
- Text: #78350F (warm brown)

Dark mode:
- Background: #1C1917 (warm stone/charcoal)
- Primary accent: #FBBF24 (bright gold/amber)
- Text: #FEFCE8 (cream/off-white)

All color variables mapped to the app's variable naming convention,
following the same pattern as existing Dusk, Lime, and Ocean themes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 01:37:09 +01:00
AndyMik90 e248256649 auto-claude: 2.3 - Add [data-theme="ocean"] and [data-theme="ocean"].dark CSS blocks
Added Ocean theme CSS variables for both light and dark modes:
- Light mode: sky blue background (#E0F2FE) with blue accent (#0284C7)
- Dark mode: deep ocean (#082F49) with bright sky blue (#38BDF8)
- All color variables mapped to app's variable naming convention
- Includes semantic colors, shadows, and focus states
2025-12-20 01:35:03 +01:00
AndyMik90 76c1bd7578 auto-claude: 2.2 - Add [data-theme="lime"] CSS theme blocks
Add lime theme CSS variables for both light and dark modes:
- Light: Fresh lime background (#E8F5A3) with purple accent (#7C3AED)
- Dark: Deep purple undertones (#0F0F1A) with bright purple (#8B5CF6)
- Maps design system color variables to app's variable naming convention

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 01:33:00 +01:00
AndyMik90 bcbced24e5 auto-claude: 2.1 - Add Dusk theme CSS variables (light and dark)
Copy [data-theme="dusk"] and [data-theme="dusk"].dark CSS blocks from
.design-system/src/styles.css. Map design system variables to app's
existing variable structure (--background, --foreground, --primary, etc.).

Dusk Light: Warm, muted palette with olive/yellow accents (#B8B978)
Dusk Dark: Fey-inspired dark theme with pale yellow accents (#E6E7A3)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 01:31:22 +01:00
AndyMik90 a75c0a9965 auto-claude: 1.3 - Add colorTheme: 'default' to DEFAULT_APP_SETTINGS
Added colorTheme: 'default' as const to DEFAULT_APP_SETTINGS in config.ts
to ensure new users start with the default theme.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 01:29:31 +01:00
AndyMik90 c505d6e32c auto-claude: 1.2 - Create themes.ts file in constants directory
Add COLOR_THEMES constant array with all 7 theme definitions:
- Default: Oscura-inspired with pale yellow accent
- Dusk: Warmer variant with slightly lighter dark mode
- Lime: Fresh, energetic lime with purple accents
- Ocean: Calm, professional blue tones
- Retro: Warm, nostalgic amber vibes
- Neo: Modern cyberpunk pink/magenta
- Forest: Natural, earthy green tones

Each theme includes preview colors for light/dark mode variants.
Export added to constants/index.ts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 01:28:07 +01:00
Andy 7d053313b5 Merge pull request #54 from AndyMik90/v2.5.6
chore: update version number to 2.5.6 in package.json
2025-12-20 01:27:32 +01:00
AndyMik90 e9535c8dc4 chore: update version number to 2.5.6 in package.json
This commit increments the version of the auto-claude-ui package to 2.5.6, reflecting the latest changes and improvements made in the project.
2025-12-20 01:27:15 +01:00
Andy 1642719445 Merge pull request #53 from AndyMik90/v2.5.6
V2.5.6
2025-12-20 01:26:35 +01:00
AndyMik90 3efab867c5 refactor: improve drag-and-drop handling and cleanup in FileTreeItem and ClaudeOAuthFlow components
- Added useEffect in FileTreeItem to clean up custom drag image on component unmount, preventing memory leaks.
- Enhanced drag image creation using safe DOM manipulation instead of innerHTML.
- Updated ClaudeOAuthFlow to manage auto-advance timeout with cleanup on unmount, ensuring onSuccess is not called after component unmount.

These changes enhance the reliability and performance of drag-and-drop functionality and OAuth flow handling.
2025-12-20 01:26:23 +01:00
AndyMik90 2ca89ce7c9 auto-claude: 1.1 - Add ColorTheme type and ColorThemeDefinition interface
Add multi-theme type definitions to settings.ts:
- ColorTheme union type with 7 theme options
- ThemePreviewColors interface for theme preview UI
- ColorThemeDefinition interface for theme metadata
- Optional colorTheme property in AppSettings interface

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 01:25:36 +01:00
AndyMik90 52e12d8d2a refactor: enhance terminal command handling and security
- Introduced shell escape utilities to prevent command injection in terminal commands.
- Updated terminal handlers to use safe command construction for profile switching and OAuth token initialization.
- Removed unnecessary console warnings, replacing them with debug logs for cleaner output.
- Implemented a wait mechanism to monitor terminal output for Claude exit, improving profile switching reliability.

This update improves the security and reliability of terminal command execution, ensuring user inputs are safely handled.
2025-12-20 01:24:40 +01:00
AndyMik90 c5b72451af fix: improve drag-and-drop functionality in FileTreeItem component
- Added useRef to manage custom drag image for better cleanup
- Updated drag image positioning to prevent display issues
- Enhanced cleanup process for drag image element on drag end

This update refines the drag-and-drop experience within the file tree, ensuring that custom drag images are handled more effectively.
2025-12-20 01:18:10 +01:00
AndyMik90 ffd8b153a5 Merge PR #52: fix: save Claude OAuth token to active profile during GitHub setup flow 2025-12-20 01:12:01 +01:00
AndyMik90 ee168d317f feat: enhance Git integration and drag-and-drop functionality
- Implement default branch selection in GitHub integration settings
- Fetch and display available branches based on the project path
- Update TaskCreationWizard to support file reference drops in the description
- Improve drag-and-drop handling for file references and images
- Add console logging for agent process when DEBUG is enabled
- Refactor FileTreeItem to manage drag state and custom drag images

This update enhances user experience with Git operations and improves the task creation workflow by allowing users to easily reference files.
2025-12-20 01:09:46 +01:00
AndyMik90 a335925eae feat: add Git Options section to task creation wizard
- Add collapsible Git Options section with base branch selector
- Allow per-task override of the worktree base branch
- Fetch and display available branches from the project repository
- Show project default branch in placeholder when available
- Use special placeholder value for Radix UI Select compatibility
- Move DndContext inside DialogContent for proper portal behavior
- Add drag-and-drop debugging logs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 00:49:07 +01:00
AndyMik90 cf1ba6b57b fix: auto-restart Claude sessions when switching profiles
When switching Claude profiles via the UI, existing terminal sessions
now automatically restart with the new profile's OAuth token. This
fixes the issue where users had to manually restart Claude after
switching profiles.

Changes:
- Profile switch handler now iterates active terminals and restarts
  Claude sessions that are in Claude mode
- Added clear terminal before profile switch to hide temp file command
- Fixed OAuth token regex to match 'default' profile ID (not just
  profile-\d+)
- Hide "Authenticate" button when profile is already authenticated
- Add re-authenticate button (refresh icon) for authenticated profiles
- Added debug logging for profile switching (enabled with DEBUG=true)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 00:23:45 +01:00
AndyMik90 ce7c95cae7 fix: resolve GitHub update system issues and version tracking
- Fix HTTP 415 error when downloading updates from GitHub API
  - Use 'application/vnd.github+json' Accept header for API URLs
  - Use 'application/octet-stream' only for CDN/direct download URLs

- Add getEffectiveVersion() to track installed source version
  - Reads from .update-metadata.json written during updates
  - Works in both dev mode and packaged app
  - Falls back to app.getVersion() if no metadata found

- Update version display to persist after app reload
  - APP_VERSION IPC now returns effective version
  - Update checker uses effective version for comparison
  - UI updates displayVersion from check result

- Add comprehensive DEBUG logging for update process
  - Logs update stages: download, extract, apply
  - Logs version resolution and metadata paths
  - Shows clear success/failure banners

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-20 00:23:39 +01:00
Andrew Chepurny 4b6a59826e fix: add null check for active profile during OAuth token save
Added defensive null check when saving OAuth tokens to active profile during
non-profile terminal flows (e.g., GitHub setup). Previously, if no active
profile existed, the code would crash when trying to access activeProfile.id.

Changes:
- Added null check for activeProfile before attempting to save token
- Send failure event to UI when no active profile is found
- Include profileId in failure event for consistency
- Added docstrings to fall
2025-12-19 18:06:18 -05:00
Andrew Chepurny e6058168f0 fix: save Claude OAuth token to active profile during GitHub setup flow
When users authenticate with Claude during the GitHub setup modal, the
OAuth token is now automatically saved to the active Claude profile
instead of being ignored.

Changes:
- Modified handleOAuthToken() to save tokens to active profile when not
  in a profile-specific terminal (e.g., during GitHub OAuth flow)
- Added Claude authentication step to GitHub setup modal flow
- Renamed setup steps for clarity: 'auth' → 'github-auth',
2025-12-19 17:42:57 -05:00
Andy c7dde1f979 Merge pull request #37 from adryserage/fix/windows-python-and-init-popup
Fix Windows Python detection and initialization popup issues
2025-12-19 20:17:58 +01:00
adryserage 15a7585f6e fix(python): correctly handle 'py -3' command on Windows
Critical bug fix: The Python detector was returning 'py' instead of 'py -3'
on Windows, which could cause Python 2 to be invoked instead of Python 3.

Changes:
- Removed special case in findPythonCommand() that stripped the '-3' flag
- Added parsePythonCommand() helper to split space-separated commands
- Updated all 9 spawn() call sites to properly handle command parsing:
  * agent-process.ts
  * agent-queue.ts (2 locations)
  * title-generator.ts
  * terminal-name-generator.ts
  * changelog/generator.ts
  * changelog/version-suggester.ts
  * ipc-handlers/task/worktree-handlers.ts (2 locations)

This ensures Windows systems using 'py -3' launcher correctly invoke
Python 3 instead of potentially defaulting to Python 2.

Fixes issue identified in PR review comment.
2025-12-19 14:08:58 -05:00
Andy c486e5ba84 Merge pull request #44 from mojaray2k/fix/ui-improvements-post-merge
Fix file explorer to show hidden directories
2025-12-19 19:24:22 +01:00
Amen-Ra Mendel d94833a678 Fix file explorer to show hidden directories
## Problem
Users couldn't access hidden directories like `.claude`, `.auto-claude`,
`.github`, `.vscode`, etc. when creating tasks or adding file references.

## Root Cause
File explorer filtered out ALL files/directories starting with `.` except `.env`,
making important configuration directories invisible.

## Solution

### 1. Allow hidden directories to be visible
- Changed filter to only hide hidden FILES, not directories
- Hidden directories like `.claude`, `.github`, `.vscode`, `.idea` now visible

### 2. Keep useful hidden files visible
- `.env`, `.gitignore`, `.env.example`, `.env.local` still shown
- Other random hidden files (`.DS_Store`, etc.) still filtered

### 3. Updated IGNORED_DIRS
- Removed `.auto-claude` (contains user specs/data)
- Removed `.vscode` and `.idea` (users may need IDE config)
- Kept truly problematic dirs: `.git`, `node_modules`, `.cache`, `.worktrees`

## User Impact
Users can now drag and reference files from `.claude`, `.auto-claude`,
`.github`, and other configuration directories when creating tasks.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-19 11:17:09 -05:00
Andy 376e950bd4 Merge pull request #41 from flokosti96/master
fix: human feedback not processed when QA already approved
2025-12-19 16:36:32 +01:00
AndyMik90 0959e790df fix: use model parameter for human feedback fixer
The fixer client for human feedback was hardcoding "sonnet" as the
fallback model instead of using the model parameter passed to
run_qa_validation_loop. This now correctly passes the user's chosen
model to get_phase_model.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 16:31:30 +01:00
AndyMik90 e134c4cba9 auto-claude: subtask-3-1 - Write unit tests for device code parsing and shell
Add comprehensive unit tests for GitHub OAuth handlers:
- Device code parsing from gh CLI stdout/stderr output
- shell.openExternal success and failure handling
- Fallback URL provision when browser launch fails
- Error handling for gh CLI process errors and non-zero exit codes
- gh CLI check and auth status handlers
- Repository format validation for command injection prevention

21 new tests covering all critical OAuth flow paths.

Also updates vitest.config.ts to include *.spec.ts files.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 16:26:54 +01:00
AndyMik90 81e1536801 auto-claude: subtask-2-3 - Add authentication timeout handling (5 minutes)
- Add 5-minute authentication timeout using useCallback and useRef for cleanup
- Implement clearAuthTimeout helper to manage timeout lifecycle
- Start timeout when auth begins, clear on success/failure/unmount
- Add isTimeout state to track timeout vs other errors
- Display timeout-specific UI with Clock icon and warning colors
- Show clear error message with retry option on timeout
- Timeout set to 5 minutes (GitHub device codes expire after 15 minutes)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 16:22:42 +01:00
AndyMik90 1a7cf409eb auto-claude: subtask-2-2 - Implement fallback URL display when browser launch fails
- Added fallback URL card in error state when authUrl is available
- Shows "Complete Authentication Manually" instructions when browser fails to open
- Added copyable URL display with Copy button that tracks copy state separately
- Added "Open URL in Browser" button to attempt manual browser launch
- Shows device code reminder in fallback card if available
- Changed Retry button in error state to call handleStartAuth instead of
  handleRetry for fresh auth attempt
- Added urlCopied state variable to track URL copy status independently
  from device code copy status

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 16:19:50 +01:00
AndyMik90 5f26d3964d auto-claude: subtask-2-1 - Add device code display state and UI component
- Add device code, auth URL, and browser opened state variables to GitHubOAuthFlow
- Display prominent device code card during authentication with copy button
- Show manual auth URL link when browser fails to open
- Update IPC types to include deviceCode, authUrl, browserOpened, and fallbackUrl
- Add visual feedback for code copy (checkmark icon when copied)
- Instructions adapt based on whether browser opened successfully
2025-12-19 16:17:02 +01:00
AndyMik90 4a4ad6b1df auto-claude: subtask-1-4 - Add error handling and fallback URL return for browser launch failures
- Added fallbackUrl field to GitHubAuthStartResult interface
- Updated success case to include fallbackUrl when browser fails to open
- Updated failure case to always provide fallbackUrl for manual recovery
- Updated gh process error handler to include fallbackUrl
- Updated catch block to include fallbackUrl for exception cases

This ensures users always have a way to manually navigate to the auth URL
when automatic browser opening fails (e.g., due to macOS security restrictions).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 16:13:29 +01:00
AndyMik90 5702692940 fix: resolve lint errors in PR #41
- Format Python code in qa/loop.py per ruff standards
- Add missing success property to WorktreeMergeResult data object

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 16:10:29 +01:00
AndyMik90 6a4c1b452b auto-claude: subtask-1-2 - Implement device code extraction from gh CLI stdout
Modify registerStartGhAuth to:
- Extract device code from gh CLI stdout/stderr as data streams in
- Use parseDeviceFlowOutput to get device code and auth URL
- Open browser via shell.openExternal (bypasses macOS restrictions)
- Return device code, auth URL, and browserOpened status in response
- Handle browser open failures gracefully (allows manual fallback)

Added GitHubAuthStartResult interface with deviceCode, authUrl,
and browserOpened fields for rich response data.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 16:09:28 +01:00
AndyMik90 b75a09c88c auto-claude: subtask-1-1 - Add shell import and device code parsing logic to oauth-handlers.ts
- Import `shell` from Electron for browser launching capability
- Add DEVICE_CODE_PATTERN regex to parse device code (format: XXXX-XXXX) from gh CLI output
- Add DEVICE_URL_PATTERN regex and GITHUB_DEVICE_URL constant for device flow URL
- Add parseDeviceCode() helper to extract device code from output
- Add parseDeviceUrl() helper to extract or default to GitHub device flow URL
- Add DeviceFlowInfo interface for structured device flow output
- Add parseDeviceFlowOutput() helper to parse both stdout and stderr for device flow info

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 16:05:56 +01:00
Andy 0601520e9b Merge pull request #35 from adryserage/fix/version-automation-issue-27
fix: implement automated version management to prevent version mismatches (#27)
2025-12-19 16:00:55 +01:00
Flokosti 412ed0be3c fix: human feedback not processed when QA already approved
Bug: Clicking "Request Changes" in Human Review caused the task to
immediately return to human_review without applying any fixes.

Root causes:
- QA_FIX_REQUEST.md was written to main project instead of worktree
- QA process ran against main project path (missing implementation_plan.json)
- Early return in qa_commands.py and loop.py if QA already approved,
  ignoring pending human feedback

Fixes:
- Write QA_FIX_REQUEST.md to worktree spec directory
- Run QA process with worktree path where build files exist
- Check for human feedback before "already approved" early return
- Process human feedback by running QA fixer first
- Reset staged changes in main when going back to QA
- Add check for already-staged changes to prevent duplicate work

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 15:52:27 +01:00
adryserage 586aa9f8c3 fix(ui): Fix initialization popup not closing automatically on success
**Issue:**
The initialization popup would not close automatically after successful
initialization due to a race condition in the Dialog's onOpenChange handler.
The handler couldn't distinguish between user-initiated close and
programmatic close after success.

**Root Cause:**
When we programmatically closed the dialog after successful init, React's
state batching meant the onOpenChange handler couldn't reliably check if
pendingProject was null yet, causing it to trigger the "skip" logic instead
of completing successfully.

**Fixes:**
1. Added initSuccess state flag to track successful initialization
2. Updated handleInitialize to set flag before closing dialog
3. Modified onOpenChange condition to check !initSuccess before calling skip
4. Added error state and UI display for failed initializations
5. Added comprehensive debug logging throughout initialization flow

**Files Modified:**
- auto-claude-ui/src/renderer/App.tsx
- auto-claude-ui/src/renderer/stores/project-store.ts

**Behavior:**
- On success: Closes automatically and opens GitHub setup modal
- On failure: Stays open with clear error message for user to retry
- On skip: Closes and remembers skip preference
- Debug logs show exactly what's happening at each step

Fixes initialization popup staying open after successful project setup.
2025-12-19 08:35:43 -05:00
adryserage bc6470f5c3 fix(ui): Add cross-platform Python detection and fix dependency installation
This commit fixes Python-related issues on Windows and other platforms:

**Python Detection Issues:**
- Fixed "spawn python3 ENOENT" errors on Windows
- All services were hardcoded to use 'python3' which doesn't exist on Windows
- Created python-detector.ts utility with intelligent detection:
  - Windows: tries 'py -3', 'python', 'python3', 'py' (in order)
  - Unix/Mac: tries 'python3', 'python' (in order)
  - Verifies each candidate is actually Python 3.x
  - Falls back to platform-specific default if none found

**Dependency Installation Issues:**
- Fixed PythonEnvManager failing to install dependencies
- Newer Python versions (3.13+) create pip3.exe instead of pip.exe
- Changed to use 'python -m pip' for universal compatibility
- Added automatic pip bootstrapping using 'python -m ensurepip'
- Works across all Python versions and platforms

**Files Modified:**
- Created: auto-claude-ui/src/main/python-detector.ts
- Updated: agent-process.ts, title-generator.ts, terminal-name-generator.ts,
  changelog-service.ts, insights/config.ts, worktree-handlers.ts,
  python-env-manager.ts

Fixes issues where Windows users couldn't run tasks, generate titles,
or install Python dependencies.
2025-12-19 08:35:20 -05:00
adryserage a107ed03a3 fix(graphiti): address additional CodeRabbit review comments
- Fix FalkorDB default port from 6379 to 6380
- Update provider list comment to include Google AI
- Fix requirements.txt comment to mention both LLM and embeddings
- Add logging and warning for unimplemented tool calling in GoogleLLMClient
- Fix overly broad exception handling (catch only JSONDecodeError)
- Add Azure deployment name validation (LLM and embedding deployments)
2025-12-19 08:01:09 -05:00
adryserage 679b8cd948 fix(graphiti): address CodeRabbit review comments
- Apply ruff formatting to Python files
- Fix ENV_GET handler to populate graphitiProviderConfig from .env
- Add Google AI to get_available_providers() function
- Fix type assertions to include google/groq/huggingface providers
- Fix asyncio deprecation: use get_running_loop() instead of get_event_loop()
2025-12-19 07:56:40 -05:00
adryserage cece172df6 fix: implement automated version management to prevent version mismatches
Fixes #27

## Problem
Version 2.5.5 was displaying as 2.5.0 in the updater because package.json
wasn't updated when the git tag was created.

## Solution
This PR implements a comprehensive automated version management system:

### 1. Version Bump Script (scripts/bump-version.js)
- Automates version updates in package.json
- Creates git commits and tags automatically
- Prevents human error in version management
- Supports semver bumps (major/minor/patch) or specific versions

### 2. Version Validation Workflow (.github/workflows/validate-version.yml)
- Runs automatically on every git tag push
- Validates package.json version matches the git tag
- Fails CI if versions mismatch with clear error messages
- Prevents releases with incorrect versions

### 3. Documentation (RELEASE.md)
- Complete release process guide
- Troubleshooting for version issues
- Release checklist

### 4. Updated package.json
- Fixed current version from 2.5.0 to 2.5.5

## Impact
-  Prevents version mismatch issues from happening again
-  Automates release process
-  CI validation catches manual errors
-  Clear documentation for maintainers
2025-12-19 07:52:06 -05:00
adryserage 1a38a06e6e fix(lint): sort imports in Google provider files
Move relative imports before TYPE_CHECKING block to satisfy ruff I001.
2025-12-19 07:48:13 -05:00
adryserage fe691066dd feat(graphiti): add Google AI as LLM and embedding provider
Add full Google AI (Gemini) support for Graphiti memory system:

Backend:
- Add google-generativeai dependency to requirements.txt
- Create GoogleEmbedder class with text-embedding-004 default model
- Create GoogleLLMClient class with gemini-2.0-flash default model
- Add GOOGLE to LLMProvider and EmbedderProvider enums
- Add google_api_key, google_llm_model, google_embedding_model config
- Update factory to create Google LLM client and embedder
- Add validation for Google provider configuration

Frontend:
- Add 'google' to GraphitiLLMProvider and GraphitiEmbeddingProvider types
- Add Google AI option to LLM provider dropdown in Setup Wizard
- Add Google AI option to embedding provider dropdown
- Add Google API key input field with link to Google AI Studio
- Update MemoryBackendSection and SecuritySettings components
- Update env-handlers to save GOOGLE_API_KEY, GOOGLE_LLM_MODEL,
  and GOOGLE_EMBEDDING_MODEL to .env files

This allows users to use Google's Gemini models for both LLM operations
(graph extraction, search, reasoning) and embeddings in Graphiti memory.
2025-12-19 07:45:54 -05:00
Andy 0f47961a8c Merge pull request #24 from mojaray2k/fix/github-org-repo-support
Fix GitHub organization repository support
2025-12-19 13:05:17 +01:00
Andy 9299ee107a Merge pull request #31 from adryserage/feature/graphiti-provider-selection
feat(ui): add LLM provider selection to Graphiti onboarding
2025-12-19 13:04:47 +01:00
adryserage 6680ed49f6 fix(types): add missing AppSettings properties for Graphiti providers
- Add globalAnthropicApiKey, globalGoogleApiKey, globalGroqApiKey to AppSettings
- Add graphitiLlmProvider and ollamaBaseUrl to AppSettings
- Use proper typed access instead of Record<string, unknown> casts
- Import AppSettings type in GraphitiStep component
2025-12-19 06:58:23 -05:00
adryserage a3eee9285e feat(ui): add Ollama as LLM provider option for Graphiti
- Add 'ollama' to GraphitiProviderType and GraphitiEmbeddingProvider
- Add Ollama-specific config fields (baseUrl, llmModel, embeddingModel, embeddingDim)
- Update GraphitiStep UI to show Base URL field instead of API key for Ollama
- Handle Ollama differently in validation, save, and load logic
- Ollama runs locally and doesn't require an API key
2025-12-19 06:52:11 -05:00
Andy 01a4eb6bbf Merge pull request #32 from adryserage/fix/node-pty-imports
fix(deps): update imports to use @lydell/node-pty directly
2025-12-19 12:51:18 +01:00
adryserage b8a419af5a fix(ui): address PR review feedback for Graphiti provider selection
- Fix initial API key loading to use saved provider preference
- Update local settings store for all providers (not just OpenAI)
- Load saved API keys when switching between providers
- Add note for non-OpenAI providers about validation limitations
2025-12-19 06:45:21 -05:00
adryserage 2b61ebbfad fix(deps): update imports to use @lydell/node-pty directly
The previous commit (e1aee6a) updated package.json to use @lydell/node-pty
but the source files still imported from 'node-pty'. This caused the app
to fail on startup with "Cannot find module 'node-pty'" error.

This commit updates all imports and the vite external config to reference
@lydell/node-pty directly, completing the migration.

Files changed:
- src/main/terminal/pty-manager.ts
- src/main/terminal/pty-daemon.ts
- src/main/terminal/types.ts
- electron.vite.config.ts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 06:32:26 -05:00
adryserage 4750869526 feat(ui): add LLM provider selection to Graphiti onboarding
Add provider dropdown to the Memory & Context onboarding step allowing
users to choose between OpenAI, Anthropic (Claude), Google (Gemini),
and Groq (Llama) for Graphiti memory operations.

Changes:
- Add provider selection dropdown with 4 LLM options
- Dynamic API key field that updates label, placeholder, and link
  based on selected provider
- Update validation and save logic to handle multiple providers
- Fix node-pty imports to use @lydell/node-pty directly

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 06:30:11 -05:00
Amen-Ra Mendel c9745b6669 Add UI clarity for per-project GitHub configuration
## Summary
- Add visual indicator showing GitHub config is per-project, not global
- Users were confused thinking settings applied to all projects

## Changes Made

### 1. Added info box to GitHub Integration section
- Displays project name in configuration context
- Explains that each project can have its own repository
- Only shown when GitHub Integration is enabled

### 2. Component updates
- GitHubIntegrationSection: Added projectName prop and info box
- ProjectSettings: Pass project.name to GitHubIntegrationSection

## User Impact
Eliminates confusion about configuration scope - users now clearly understand
that GitHub repository settings are project-specific.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-19 06:17:38 -05:00
adryserage 08b65f315a Update dependencies in pnpm-lock.yaml
Upgraded various dependencies including node-pty (now using @lydell/node-pty@^1.1.0), @types/node, @eslint/js, @standard-schema/spec, @typescript-eslint, and several others. Also updated esbuild and rollup platform-specific packages to newer versions.
2025-12-19 06:14:30 -05:00
adryserage e1aee6a44f fix(deps): replace node-pty with @lydell/node-pty for prebuilt binaries
node-pty@1.1.0-beta9 fails to compile on Windows with node-gyp due to
MSBuild errors during native module compilation. This blocks installation
for Windows users without full Visual Studio Build Tools configured.

Solution:
- Replace node-pty with @lydell/node-pty which provides prebuilt binaries
- Add pnpm override to alias 'node-pty' imports to the new package
- Update extraResources path for electron-builder
- Remove node-pty from onlyBuiltDependencies (no compilation needed)

@lydell/node-pty@1.1.0 provides prebuilt binaries for:
- Windows x64 and ARM64
- macOS x64 (Intel) and ARM64 (Apple Silicon)
- Linux x64 and ARM64

This eliminates the need for node-gyp compilation and ensures
cross-platform compatibility without build tool dependencies.
2025-12-19 06:10:52 -05:00
Amen-Ra Mendel b3636a5bce Add defensive array validation for GitHub issues API response
- Ensures API response is an array before filtering
- Prevents 'filter is not a function' error
- Improves error handling for unexpected responses
2025-12-19 05:58:57 -05:00
Andy 908eebfb16 Merge pull request #25 from AndyMik90/version/2.5.5
chore: update CHANGELOG for version 2.5.5
2025-12-19 11:30:08 +01:00
AndyMik90 0e6b652dd7 chore: update CHANGELOG for version 2.5.5
- Added new features including GitHub setup flow, atomic log saving, and multi-auth token support.
- Improved agent behavior with a new default profile and enhanced issue tracking.
- Fixed multiple CI test failures and improved merge preview reliability.
- Implemented security measures to prevent command injection and enforced Python version requirements.
- Conducted code cleanup and removed redundant directory structures.

This release focuses on enhancing agent reliability and streamlining the build workflow.
2025-12-19 11:29:37 +01:00
Andy 0acdba6f01 Merge pull request #22 from AndyMik90/version/2.5.5
Version/2.5.5
2025-12-19 11:25:23 +01:00
AndyMik90 de2eccd209 fix: resolve CI test failures and improve merge preview
Test fix:
- Mock getClaudeProfileManager in subprocess spawn tests to bypass
  authentication checks that fail in CI (no auth token configured)

Merge preview improvements:
- Add _detect_default_branch() to properly detect main/master branch
- Add debug logging for git diff failures to aid troubleshooting
- Use detected default branch instead of hardcoded 'main'

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 11:22:55 +01:00
Amen-Ra Mendel 873cafa46f Fix GitHub organization repository support
## Summary
- Add support for organization repositories by including org members in repo list API
- Add repository reference normalization to handle full GitHub URLs, SSH URLs, and owner/repo format
- Apply normalization to all GitHub API calls to ensure consistent behavior

## Changes Made

### 1. Enhanced repo listing (repository-handlers.ts)
- Updated `/user/repos` endpoint to include affiliation parameter
- Now fetches: owner, collaborator, and organization_member repos
- Fixes #20: Organization repos now appear in repository list

### 2. Added URL normalization utility (utils.ts)
- New `normalizeRepoReference()` function handles:
  - owner/repo format (already normalized)
  - https://github.com/owner/repo URLs
  - https://github.com/owner/repo.git URLs
  - git@github.com:owner/repo.git SSH URLs
- Prevents 404 errors from malformed repository references

### 3. Applied normalization consistently
- Updated repository-handlers.ts to normalize repo refs before API calls
- Updated issue-handlers.ts to normalize repo refs before API calls
- All GitHub API calls now use normalized repository format

## Testing
- Verified with organization repository: imaginationeverywhere/ppsv-charities
- Tested with various URL formats
- GitHub CLI authentication continues to work seamlessly

## Related Issues
Fixes #20: Auto Claude doesn't work with GitHub Organization repositories
2025-12-19 05:22:41 -05:00
AndyMik90 948db57763 chore: code cleanup and test fixture updates
- Apply ruff formatting to workspace_commands.py
- Remove unnecessary f-string in workspace.py
- Remove unused import get_phase_config from spec_runner.py
- Add phase_name parameter to mock_run_agent_fn fixture

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 11:13:35 +01:00
AndyMik90 f98a13eaa0 refactor: change default agent profile from 'balanced' to 'auto'
Update TaskCreationWizard to use 'auto' as the default agent profile
when no profile is explicitly selected.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 11:13:25 +01:00
AndyMik90 24ff491d3c security: prevent command injection in GitHub API calls
- Use execFileSync instead of execSync to avoid shell interpretation
- Add regex validation for repo format (owner/repo pattern)
- Reject requests with invalid characters that could enable injection

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 11:13:16 +01:00
AndyMik90 a8f2d0b110 fix: resolve CI failures (lint, format, test)
- Fix import sorting issues caught by ruff (I001)
- Apply ruff formatting to auto-claude modules
- Update test to match default model (sonnet-4-5 not opus-4-5)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 11:11:36 +01:00
AndyMik90 46d2536600 fix: use git diff count for totalFiles in merge preview
The merge preview was showing incorrect file counts because it only
counted files tracked by the semantic evolution tracker. Many files
(test files, config files, etc.) weren't being tracked, leading to
misleading "Files to merge: 0" displays when there were actually
multiple files changed.

Changes:
- Add _get_changed_files_from_git() helper to get actual changed files
- Use git diff count as authoritative totalFiles instead of tracker count
- Use git diff file list for the files array in preview response
- Always compare against 'main' branch (worktrees are created from main)

This ensures the UI shows the correct number of files that will be
merged, matching the git diff stats shown elsewhere in the UI.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 11:01:34 +01:00
AndyMik90 71535581c2 feat: enhance stage-only merge handling with verification checks
This commit improves the handling of stage-only merges by adding verification to ensure that actual changes are staged before proceeding. Key changes include:
- Implementation of checks to determine if there are staged changes or if the merge has already been committed.
- Updated status handling based on the verification results, allowing for more accurate task status updates.
- Enhanced debug logging for better traceability of merge outcomes.

These enhancements provide a more robust user experience by preventing false positives in stage-only scenarios and ensuring accurate task management.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2025-12-19 10:50:09 +01:00
AndyMik90 26725286d5 feat: introduce phase configuration module and enhance agent profiles
This commit adds a new phase configuration module that manages model and thinking level settings for different execution phases. It reads configurations from `task_metadata.json` and provides resolved model IDs for various phases, including spec creation, planning, coding, and QA.

Key changes include:
- New `phase_config.py` file to handle model ID mappings and thinking budgets.
- Updates to agent files (`coder.py`, `planner.py`, `loop.py`) to utilize phase-specific models and thinking levels.
- Modifications to the CLI and UI components to support per-phase configuration, enhancing the user experience for task creation and editing.

The new structure allows for optimized model selection and thinking depth based on the phase, improving overall task execution efficiency.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2025-12-19 10:24:44 +01:00
AndyMik90 569e921759 fix: preserve roadmap generation state when switching projects
Previously, roadmap generation would stop or appear stopped when users
navigated between projects. This fix ensures generation continues in
the background and the UI properly reflects the generation state.

Changes:
- Add ROADMAP_GET_STATUS IPC endpoint to query if generation is running
- Update loadRoadmap() to query backend status when switching projects
- Restore generation UI state when returning to a project with active gen
- Remove aggressive stopRoadmap() call that killed generation on switch

The fix allows users to start roadmap generation, navigate to other
projects, and return to see the correct progress/completion state.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 10:16:30 +01:00
AndyMik90 03ccce5cc1 feat: add required GitHub setup flow after Auto Claude initialization
This ensures users properly configure GitHub before using Auto Claude,
which is necessary for the branch-based workflow to function correctly.

Changes:
- Add GitHubSetupModal component with 3-step flow:
  1. GitHub OAuth authentication (via gh CLI)
  2. Auto-detect repository from git remote
  3. Select base branch for task worktrees (with recommended default)
- Add IPC handlers for detectGitHubRepo and getGitHubBranches
- Integrate modal into App.tsx to show after Auto Claude init
- Update ElectronAPI types and browser mocks

The flow now is:
1. User adds project
2. Git must be initialized (GitSetupModal if not)
3. Auto Claude initialized (creates .auto-claude folder)
4. GitHub setup required (new GitHubSetupModal)
5. Project ready for task creation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 08:00:17 +01:00
AndyMik90 64d5170c94 chore: remove redundant auto-claude/specs directory
Specs are stored in .auto-claude/specs/ (per-project, gitignored).
The auto-claude/specs/ folder was legacy and no longer used.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 01:30:27 +01:00
AndyMik90 0710c13964 chore: untrack .auto-claude directory (should be gitignored)
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 01:29:28 +01:00
AndyMik90 56cedec2ae fix: prevent dialog skip during project initialization
- Added checks to ensure the initialization dialog does not trigger skip logic while a project is being initialized.
- Refactored project ID handling in the initialization process for consistency across components.
- Improved user experience by preventing unintended dialog closures during initialization.

This change enhances the reliability of the project initialization workflow in the application.
2025-12-19 01:23:56 +01:00
AndyMik90 c0c8067bc5 feat: enhance merge workflow by detecting current branch
- Added functionality to detect the current Git branch before merging spec changes.
- Prevent merging into the same branch by providing user guidance to switch branches.
- Updated WorktreeManager initialization to use the detected branch as the merge target.

This improves the user experience by ensuring that merges are performed correctly and reduces the risk of accidental merges into the spec branch.
2025-12-19 01:02:12 +01:00
AndyMik90 db3a034d75 Merge auto-claude/040: Add auth failure detection to prevent premature human_review status 2025-12-19 00:58:38 +01:00
AndyMik90 059315d6ab fix: update model IDs for Sonnet and Haiku
Updated the model IDs in the MODEL_ID_MAP to reflect the latest versions for Sonnet and Haiku. This change ensures that the application uses the correct identifiers for these models moving forward.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2025-12-19 00:43:29 +01:00
AndyMik90 8df7ba4f16 qa: Sign off - all verification passed
- Unit tests: 365/365 passing
- Auth-specific tests: 48/48 passing
- TypeScript type-check: passed
- Security review: passed (no vulnerabilities)
- Pattern compliance: passed
- No regressions found

All acceptance criteria verified:
- Pre-flight auth checks implemented
- Auth failure detection patterns comprehensive
- Clear error messages directing users to Settings > Claude Profiles
- Status transition validation prevents premature human_review
- Code follows established patterns

🤖 QA Agent Session 1

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 00:26:34 +01:00
Andy 2bffea842b Fix discord link 2025-12-19 00:15:24 +01:00
AndyMik90 99cf21e61b feat: add comprehensive DEBUG logging and fix lint errors
DEBUG logging additions:
- agents/session.py: SDK invocation logging with tool calls/results
- qa/loop.py: QA iteration tracking and verdict logging
- qa/reviewer.py: Review session lifecycle logging
- qa/fixer.py: Fix session lifecycle logging
- runners/spec_runner.py: Spec creation orchestrator logging

Python lint fixes:
- Remove f-string without placeholders (qa/loop.py)
- Add noqa: UP036 for intentional version checks (run.py, spec_runner.py)
- Format 5 files with ruff

TypeScript fixes:
- Add InsightsAPI to ElectronAPI interface composition
- Fix sendInsightsMessage signature to include modelConfig param
- Add updateInsightsModelConfig method to ipc.ts types
- Add updateInsightsModelConfig to browser mock

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-19 00:07:55 +01:00
AndyMik90 da5e26b923 feat: implement atomic log saving to prevent corruption
Enhance log storage functionality by saving logs to a temporary file first, followed by an atomic rename to the final log file. This change mitigates the risk of log corruption during concurrent reads, particularly when the UI accesses the log file mid-write. Additionally, update the log loading mechanism to return cached logs if the file is detected as corrupted.

Files updated:
- auto-claude/task_logger/storage.py: Implement atomic log saving
- auto-claude-ui/src/main/task-log-service.ts: Handle potential log file corruption by returning cached logs

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2025-12-18 23:56:20 +01:00
AndyMik90 c957eaa3a1 Add better github issue tracking and UX 2025-12-18 23:56:08 +01:00
AndyMik90 73d01c0103 feat: add comprehensive DEBUG logging to Claude SDK invocation points
Add detailed debug logging throughout the spec creation and QA validation
pipeline to help diagnose issues during autonomous builds.

Files updated:
- agents/session.py: Log session start, SDK queries, message types,
  tool calls (with inputs), tool results (success/error/blocked),
  and session completion status
- spec/pipeline/agent_runner.py: Log agent run lifecycle, prompt loading,
  message processing, and tool execution
- qa/loop.py: Log iteration progress, reviewer/fixer session status,
  QA verdicts, recurring issues detection, and final summary
- qa/reviewer.py: Log QA reviewer session lifecycle and verdicts
- qa/fixer.py: Log QA fixer session lifecycle and fix status
- runners/spec_runner.py: Log orchestrator creation, run status,
  build approval, and command execution

Usage: Set DEBUG=true and optionally DEBUG_LEVEL=1|2|3 for verbosity:
  DEBUG=true DEBUG_LEVEL=2 python auto-claude/run.py --spec 001

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 23:54:35 +01:00
AndyMik90 41a507fe8b feat: auto-download prebuilt node-pty binaries for Windows
Eliminates the need for Visual Studio Build Tools on Windows by:

1. GitHub Actions workflow (.github/workflows/build-prebuilds.yml)
   - Builds node-pty for Windows x64 with correct Electron ABI
   - Uploads prebuilt binaries as release assets
   - Triggered on releases and manual dispatch

2. Smart postinstall script (auto-claude-ui/scripts/postinstall.js)
   - On Windows: tries to download prebuilts first
   - Falls back to electron-rebuild if prebuilts unavailable
   - Shows clear instructions if compilation fails

3. Download helper (auto-claude-ui/scripts/download-prebuilds.js)
   - Fetches prebuilt binaries from GitHub releases
   - Extracts and installs to node_modules/node-pty

Windows users can now run `npm install` without installing Visual Studio
Build Tools, as long as prebuilt binaries exist for their Electron version.

Fixes #8

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 23:53:06 +01:00
AndyMik90 e02aa597f2 feat(insights): add per-session model and thinking level selection
- Add model selector dropdown in Insights chat header with agent profiles:
  - Complex (Opus + ultrathink)
  - Balanced (Sonnet + medium) - new default
  - Quick (Haiku + low)
  - Custom option for direct model + thinking level selection
- Change default from slow Opus to Sonnet for faster responses
- Persist model configuration per-session
- Fix missing event forwarding from insightsService to renderer
  (was causing responses to not appear without hard refresh)
- Fix insights_runner.py path (was looking in auto-claude/ instead of
  auto-claude/runners/)
- Add --model and --thinking-level CLI args to insights_runner.py

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 23:37:09 +01:00
AndyMik90 909305c82b auto-claude: subtask-5-1 - Add unit tests for auth failure detection patterns
Added comprehensive unit tests for the rate-limit-detector module covering:
- Rate limit detection with reset times and secondary indicators
- Auth failure detection for all 13 patterns (authentication required, not
  authenticated, login required, oauth token invalid/expired/missing,
  unauthorized, invalid credentials, session expired, access denied, etc.)
- Failure type classification (missing, invalid, expired, unknown)
- Profile ID handling and user-friendly message generation
- Edge cases: multiline output, case-insensitivity, JSON errors, stack traces
- Mutual exclusivity between rate limit and auth failure detection

All 48 tests pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 23:31:27 +01:00
AndyMik90 121b2b294f auto-claude: subtask-4-1 - Add status transition validation to prevent premature human_review status
Adds validation in TASK_UPDATE_STATUS handler to prevent tasks from being
moved to human_review status prematurely when execution fails.

Changes:
- Check if spec.md exists and has meaningful content (at least 100 chars)
  before allowing transition to human_review status
- Return error with actionable message if spec is missing or empty
- Log warning for debugging when blocked

This prevents the issue where tasks incorrectly appear in human_review
when spec creation fails silently (e.g., due to auth issues).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 23:23:08 +01:00
AndyMik90 c2fe3322a7 auto-claude: subtask-3-1 - Add auth failure detection to agent-process.ts exit handler
Added authentication failure detection to the process exit handler in agent-process.ts:
- Import detectAuthFailure from rate-limit-detector
- In exit handler, when process fails (code !== 0) and is not rate limited,
  check for authentication failures using detectAuthFailure(allOutput)
- If auth failure detected, emit 'auth-failure' event with taskId and
  detection details (profileId, failureType, message, originalError)

This enables proper detection and reporting of authentication issues that
occur during spec creation or task execution.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 23:21:03 +01:00
AndyMik90 aac6b106aa auto-claude: subtask-2-2 - Add auth validation in execution-handlers.ts with proper error messaging
Added pre-flight authentication checks before task execution:
- Import getClaudeProfileManager for auth validation
- Check hasValidAuth() in TASK_START handler before calling agentManager
- Check hasValidAuth() in TASK_UPDATE_STATUS handler before auto-starting tasks
- Check hasValidAuth() in TASK_RECOVER_STUCK handler before auto-restarting tasks
- Emit TASK_ERROR with actionable message when auth is missing
- Return early without changing task status when auth fails

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 23:19:07 +01:00
AndyMik90 7f6beba3ad auto-claude: subtask-2-1 - Add pre-flight auth check in agent-manager.ts
Added pre-flight authentication validation before spawning processes:
- Import getClaudeProfileManager from claude-profile-manager
- In startSpecCreation(): Check hasValidAuth() before spawning spec_runner.py
- In startTaskExecution(): Check hasValidAuth() before spawning run.py
- Emit clear error message if auth is missing, preventing task from starting

This ensures tasks cannot start without valid Claude authentication,
addressing GitHub Issue #11 where tasks would skip to human_review
when spec creation fails silently due to missing authentication.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 23:16:35 +01:00
AndyMik90 4b354e7b9f auto-claude: subtask-1-2 - Add hasValidAuth method to ClaudeProfileManager
Add hasValidAuth(profileId?: string): boolean method to check if a profile
has valid authentication for starting tasks. A profile is considered
authenticated if it has a valid OAuth token (not expired) OR has an
authenticated configDir with credential files.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 23:13:54 +01:00
AndyMik90 eed5297e9d auto-claude: subtask-1-1 - Add authentication failure detection patterns
Add AUTH_FAILURE_PATTERNS array with regex patterns to detect various
authentication error messages from Claude CLI/SDK output, including:
- Authentication required messages
- Invalid/expired token errors
- Unauthorized/access denied errors
- Login required messages

Also add:
- AuthFailureDetectionResult interface for structured detection results
- detectAuthFailure() function to detect auth failures in process output
- isAuthFailureError() helper for simple boolean checks
- classifyAuthFailureType() to categorize failures (missing/invalid/expired)
- getAuthFailureMessage() for user-friendly error messages

This enables detecting when tasks fail silently due to authentication
issues, allowing proper error feedback to users instead of incorrectly
skipping to human review status.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 23:12:03 +01:00
AndyMik90 9a5ca8c78f fix: require Python 3.10+ and add version check
The codebase uses Python 3.10+ type hint syntax (e.g., `str | list[str]`)
which causes TypeError on Python 3.9 and earlier.

Changes:
- Update README.md to document Python 3.10+ requirement
- Add runtime version check in run.py and spec_runner.py
- Provides clear error message with upgrade instructions

Fixes #5

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 23:00:42 +01:00
AndyMik90 63a1d3c138 fix: detect branch namespace conflict blocking worktree creation
Add detection for when a branch named 'auto-claude' exists, which blocks
creating branches in the 'auto-claude/*' namespace due to Git's file-based
ref storage system.

Now provides a clear error message explaining the issue and how to fix it
by renaming the conflicting branch.

Fixes #3

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 22:58:12 +01:00
Andy 3caf9cf18e Merge pull request #7 from wignerStan/feature/multi-auth-token-support
feat: Add multi-auth token support and ANTHROPIC_BASE_URL passthrough (CLI only)
2025-12-18 21:50:09 +01:00
Jacob 7d351e3422 fix: Remove duplicate LINEAR_API_KEY check and consolidate imports
Addresses CodeRabbit review comment:
- Consolidated split imports from core.auth
- Removed unreachable duplicate LINEAR_API_KEY validation
2025-12-18 21:40:04 +01:00
Jacob 9dea155505 feat: Add multi-auth token support and ANTHROPIC_BASE_URL passthrough
Implements support for multiple authentication environment variables:
- CLAUDE_CODE_OAUTH_TOKEN (original, highest priority)
- ANTHROPIC_AUTH_TOKEN (for proxies like CCR)
- ANTHROPIC_API_KEY (direct Anthropic API)

Also adds ANTHROPIC_BASE_URL and related env vars passthrough to SDK.

Changes:
- New core/auth.py with centralized auth logic
- Updated core/client.py to use auth helpers
- Updated cli/utils.py to show auth source and base URL
- Updated all modules using auth tokens
- Updated .env.example with documentation
2025-12-18 21:40:04 +01:00
Andy d3cdd3a1c7 Merge pull request #13 from AndyMik90/release/version2.5
chore: update CHANGELOG for version 2.5.0 with new features, improvem…
2025-12-18 21:36:14 +01:00
AndyMik90 a9d1ddb84f chore: update CHANGELOG for version 2.5.0 with new features, improvements, and bug fixes 2025-12-18 21:34:54 +01:00
Andy 6985934825 Merge pull request #10 from AndyMik90/feature/recent-updates
Recent updates: roadmap enhancements, bug fixes, and drag-and-drop support
2025-12-18 20:53:05 +01:00
AndyMik90 4f1766b501 fix: correct CompetitorAnalysisViewer to match type definitions
Fix TypeScript errors by using correct property names from types:
- Replace userQuotes with source and frequency fields
- Change opportunityScore to opportunity
- Replace summary with insightsSummary structure
- Display top pain points, differentiator opportunities, and market trends

All properties now match the CompetitorPainPoint and CompetitorAnalysis
type definitions in roadmap.ts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 20:49:46 +01:00
AndyMik90 7ff326d898 feat: add interactive competitor analysis viewer for roadmap
Add comprehensive competitor analysis viewing capabilities:

- Create CompetitorAnalysisViewer component with detailed insights display
  * Shows competitor names, descriptions, and market positions
  * Displays pain points with severity badges (high/medium/low)
  * Includes user quotes from reviews/forums
  * Shows opportunity scores for prioritization
  * Provides visit links to competitor products

- Make Competitor Analysis badge interactive
  * Click to open detailed viewer modal
  * Tooltip shows summary (competitor count, pain points)
  * Visual feedback with hover state

- Enhance persona visibility in roadmap header
  * Make "+N more personas" clickable with dotted underline
  * Show all secondary personas in tooltip on hover

- Fix modal scrolling in CompetitorAnalysisViewer
  * Add flex layout constraints for proper scrolling
  * Set max-height with calculation for header space
  * Add bottom padding to prevent content cutoff

This enables users to view detailed competitive insights generated
during roadmap creation, including specific pain points identified
in competitor products and opportunities to address market gaps.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 20:46:31 +01:00
AndyMik90 48f7c3cc61 fix: address multiple CodeRabbit review feedback items
Changes included:

1. **InvestigationDialog.tsx** - Prevent state updates after unmount:
   - Add isMounted flag to prevent state updates after component unmounts
   - Add fetchCommentsError state to surface API errors to the user
   - Display error state in UI with styled error message
   - Ensure cleanup function properly sets isMounted = false

2. **EnvConfigModal.tsx** - Improve type safety:
   - Replace `any` type with proper `ClaudeProfile` type in filter callback

3. **GenerationProgressScreen.tsx** & **RoadmapGenerationProgress.tsx**:
   - Add double-click prevention for stop button
   - Add isStopping state with proper error handling
2025-12-18 20:41:30 +01:00
AndyMik90 892e01d608 fix: use stable React keys instead of array indices in RoadmapHeader
Replace array index keys with content-based stable keys in two mapped lists:

- Competitor analysis: use `comp.id` instead of index, and simplify
  type annotation by relying on TypeScript inference
- Secondary personas: use `persona` string value instead of index

Using stable keys improves React's reconciliation efficiency and prevents
potential rendering issues when list items are reordered or modified.

Addresses CodeRabbit review feedback.
2025-12-18 20:40:50 +01:00
AndyMik90 54501cbd73 fix: additional fixes for http error handling and path resolution
- http-client.ts: Limit error response data collection to 10KB and add error handlers
- RoadmapGenerationProgress.tsx, GenerationProgressScreen.tsx: Allow onStop to return Promise<void>
- insights_runner.py: Fix path resolution and load .env from auto-claude directory

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 20:30:17 +01:00
AndyMik90 f1d578fd18 fix: update worktree test to match intended branch detection behavior
The WorktreeManager is designed to prefer main/master branches over the
current branch when detecting the base branch. Updated the test to
reflect this intended behavior:

- Renamed test_init_detects_current_branch to test_init_prefers_main_over_current_branch
- Added new test_init_falls_back_to_current_branch to verify fallback when main/master don't exist

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 20:23:45 +01:00
AndyMik90 2e3a5d9de5 fix: resolve CI lint and TypeScript errors
- Fix Python formatting (ruff) in workspace.py, display.py, menu.py
- Fix TypeScript errors:
  - Add missing CompetitorAnalysis import in types.ts
  - Add type annotations to RoadmapHeader.tsx map callback
  - Add cn import and fix EnvConfigModal OAuth token handling
  - Add type annotations to InvestigationDialog.tsx
  - Add missing stopRoadmap and onRoadmapStopped to browser-mock
  - Add getIssueComments to ElectronAPI type and mocks
  - Update investigateGitHubIssue to accept optional selectedCommentIds
  - Fix CLAUDE_CODE_OAUTH_TOKEN access in agent-queue.ts
- Include pending bug fixes:
  - Add .trim() to git status parsing in worktree-handlers.ts
  - Change Accept header to application/octet-stream in http-client.ts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 20:22:55 +01:00
AndyMik90 a6dad428e9 feat: enhance roadmap generation with stop functionality and debug logging
- Added stop functionality for roadmap generation, allowing users to halt the process.
- Implemented debug logging throughout the roadmap generation process for better traceability.
- Updated IPC channels to support stopping roadmap generation and added corresponding handlers.
- Enhanced UI components to include stop buttons and feedback for the stop action.

This update improves user control over the roadmap generation process and aids in debugging.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2025-12-18 20:09:44 +01:00
AndyMik90 3d24f8f59e fix: correct path resolution in runners for module imports and .env loading
The runners in auto-claude/runners/ were using incorrect relative paths
that only went up one directory level instead of two, causing:
- ModuleNotFoundError for 'debug' module
- Missing .env file (CLAUDE_CODE_OAUTH_TOKEN not found)
- Script not found errors for analyzer.py
- Prompt files not found for agent execution

Fixed paths in:
- roadmap_runner.py: sys.path and .env now resolve to auto-claude/
- ideation_runner.py: sys.path and .env now resolve to auto-claude/
- roadmap/executor.py: scripts_base_dir and prompts_dir now resolve
  correctly from the nested roadmap/ subdirectory

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 20:03:46 +01:00
AndyMik90 9106038a17 fix: resolve React key warning in PhaseProgressIndicator
- Add explicit key to overflow count span that shows "+N" when more
  than 10 subtasks exist (sibling to mapped elements needed a key)
- Add fallback key using index for subtask indicators in case
  subtask.id is undefined

Fixes console warning: "Each child in a list should have a unique
'key' prop"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 19:31:34 +01:00
AndyMik90 895ed9f605 fix: enable stuck task detection for ai_review status
Previously, stuck detection only checked tasks with status='in_progress',
causing tasks stuck in 'ai_review' status to never show the recovery option.

When a task enters QA review phase, its status changes to 'ai_review'. If
the process crashes during this phase, the status remains 'ai_review' with
no active process, but the stuck detection was skipped because isRunning
only checked for 'in_progress' status.

This fix extends the isRunning check to include both 'in_progress' and
'ai_review' statuses, ensuring stuck tasks in AI Review can be detected
and recovered.

Fixes: Task #838 stuck in AI Review with no recovery option

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 18:59:28 +01:00
AndyMik90 cbe14fda9b feat: map GitHub issue labels to task categories
## Changes
- Automatically categorize tasks based on GitHub issue labels
- Added label-to-category mapping function with comprehensive coverage

## Category Mapping
- **bug_fix**: Issues labeled with bug, defect, error, fix
- **security**: Issues labeled with security, vulnerability, cve
- **performance**: Issues labeled with performance, optimization, speed
- **ui_ux**: Issues labeled with ui, ux, design, styling
- **infrastructure**: Issues labeled with infrastructure, devops, deployment, ci, cd
- **testing**: Issues labeled with test, testing, qa
- **refactoring**: Issues labeled with refactor, cleanup, maintenance, chore, tech-debt
- **documentation**: Issues labeled with documentation, docs
- **feature**: Default for enhancement, feature, improvement, or unlabeled issues

## Implementation
- Updated `determineCategoryFromLabels()` to return proper TaskCategory types
- Modified `createSpecForIssue()` to accept labels array parameter
- Updated both investigation and import handlers to pass labels
- Tasks now display with correct category badge in Kanban board

## Example
- GitHub issue with "bug" label → Task category: "bug_fix"
- GitHub issue with "enhancement" label → Task category: "feature"
- GitHub issue with no labels → Task category: "feature" (default)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 18:31:12 +01:00
AndyMik90 4c1dd89840 feat: add GitHub issue comment selection and fix auto-start bug
## Features
- Add comment selection UI when creating tasks from GitHub issues
  - Fetch and display all comments with author, timestamp, and preview
  - Allow users to select/deselect individual comments via checkboxes
  - Include "Select All" / "Deselect All" toggle functionality
  - Show selected comment count (e.g., "3/5 comments selected")
  - Only selected comments are included in the task description

- Fix auto-start bug where GitHub issues were immediately executed
  - Tasks now stay in "backlog" status after creation
  - Users must manually start tasks from the Kanban board

## Implementation Details

### Backend
- Added `getIssueComments` IPC handler to fetch comments separately
- Modified `investigateGitHubIssue` to accept selectedCommentIds parameter
- Updated comment filtering logic in buildIssueContext
- Removed automatic startSpecCreation call to prevent auto-execution

### Frontend
- Enhanced InvestigationDialog with scrollable comment list UI
- Updated GitHubAPI interface with getIssueComments method
- Modified hooks and stores to pass selected comment IDs through the chain
- Added projectId prop to InvestigationDialog for comment fetching

### Files Changed
- Backend handlers: investigation-handlers.ts, issue-handlers.ts, types.ts
- API layer: github-api.ts
- UI components: InvestigationDialog.tsx, GitHubIssues.tsx
- State management: github-store.ts, useGitHubInvestigation.ts
- Type definitions: types/index.ts, ipc.ts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-18 18:27:01 +01:00
AndyMik90 d93eefe806 feat: enhance TaskCreationWizard with drag-and-drop support for file references and inline @mentions
- Added a drop zone for file references and a separate drop zone for inline @mentions in the description textarea.
- Updated drag-and-drop handling to allow inserting @mentions directly into the description or adding files to the referenced files list.
- Implemented parsing of @mentions from the description to create ReferencedFile entries, avoiding duplicates.
- Improved visual feedback for drag-and-drop interactions, including indicators for maximum file capacity and drop zones.
2025-12-18 17:45:23 +01:00
AndyMik90 e11f5fcd50 v2.4.0 changelogs 2025-12-18 17:41:32 +01:00
AndyMik90 8e891dfcfe cleanup docs 2025-12-18 16:42:00 +01:00
AndyMik90 c721dc23b6 fix: correct git status parsing in merge preview
Fixed parsing bug where .trim() on entire output removed leading space
from git status --porcelain format, causing filenames to be truncated.

- Removed .trim() from git status output (line 536)
- Check for empty status using gitStatus.trim() in condition
- Correctly parse XY<space>filename format without truncation
- Removed diagnostic logging

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-18 16:37:41 +01:00
AndyMik90 1a2b7a1bbb Update TaskReview component to refine conditional rendering for staged tasks, ensuring proper display when staging is unsuccessful. 2025-12-18 16:29:01 +01:00
AndyMik90 b194c0e11f Merge branch 'auto-claude/033-add-drag-and-drop-file-upload' 2025-12-18 16:27:20 +01:00
AndyMik90 a20b8cf12a Enhance task status handling to allow 'done' status in limbo state. Added worktree existence check to enforce merge workflow unless no worktree is found, enabling direct status updates in specific scenarios. 2025-12-18 16:24:40 +01:00
AndyMik90 0ed6afb805 Improvement/Worktree needs to be manually deleted for early access safety (not delete work that has introduced spend) 2025-12-18 16:18:05 +01:00
AndyMik90 914a09d0da feat/claude account oauth implementation on onboarding instead of manual token 2025-12-18 16:06:43 +01:00
AndyMik90 e44202a066 Better handling of lock files from worktress upon merging 2025-12-18 16:00:30 +01:00
AndyMik90 42496446bc new oauth github integration upon onboarding. 2025-12-18 16:00:17 +01:00
AndyMik90 b0fc497583 lock update 2025-12-18 15:57:32 +01:00
AndyMik90 462edcdd93 improved readme and build process 2025-12-18 15:07:25 +01:00
AndyMik90 affbc48cbe fix ESLint warnings and failing tests 2025-12-18 14:49:07 +01:00
AndyMik90 d7fd1a24da Big upgrade to windows and linux compability, also introduced a auto upgrading functionality to work cross platform with also the posiblity for Git init on app startup and checking when adding new projects. 2025-12-18 13:41:57 +01:00
AndyMik90 96dd04d411 feat: Add debug logging to app updater
Improved logging for app updates to help diagnose update issues:

- Added DEBUG_UPDATER env var for verbose electron-updater logging

- Better console output showing update check status

- Clear message when running in dev mode (updates disabled)

- Option to force updater init in dev mode for testing logs
2025-12-18 11:21:13 +01:00
AndyMik90 1d0566fce7 feat: Auto-open settings to updates section when app update is ready
When an app update is downloaded and ready to install, automatically opens the Settings dialog to the Updates section so users can easily install the update.

Changes:

- App.tsx: Listen for onAppUpdateDownloaded event and open settings

- AdvancedSettings.tsx: Add Electron app update UI with download/install buttons

- ipc.ts: Add app update methods to ElectronAPI interface

- settings-mock.ts: Add browser mocks for app update methods
2025-12-18 10:59:25 +01:00
AndyMik90 7f3cd5969d feat: Add integrated release workflow with AI version suggestion
Adds a streamlined release workflow that uses AI (Claude Haiku) to analyze git commits and suggest semantic version bumps (major/minor/patch). Automatically updates package.json, commits, and pushes using a safe git workflow that preserves user's current work.

New features:

- RELEASE_SUGGEST_VERSION IPC for AI-powered version suggestions

- bumpVersion() with safe git workflow (stash/checkout/commit/restore)

- VersionSuggestion type with bumpType and reasoning

- Updated ReleaseProgress to include bumping_version stage

Also replaces VERSION file detection with requirements.txt across the codebase.
2025-12-18 10:32:55 +01:00
AndyMik90 0ef0e1588b fix for fixing windows/linux python handling 2025-12-18 10:18:34 +01:00
AndyMik90 efc112a313 Implement Electron app auto-updater (Phase 1 & 2)
Phase 1: Update Notifications & Download
- Install electron-updater dependency
- Add GitHub publish configuration to package.json

Phase 2: Auto-Download & Install
- Backend: Main process auto-updater with electron-updater
- Frontend: AppUpdateNotification UI component
- IPC: Full update workflow (check/download/install/events)

Backend Implementation:
- Created app-updater.ts with autoUpdater configuration
- Auto-download enabled, checks every 4 hours
- Events: update-available, update-downloaded, download-progress
- Created app-update-handlers.ts with IPC handlers
- Integrated into main/index.ts (production only)

Frontend Implementation:
- Created AppUpdateNotification.tsx with modal dialog
- Shows version, release notes, download progress
- Download workflow: Available → Downloading → Downloaded → Install
- Created app-update-api.ts preload bindings
- Integrated into App.tsx root level

Configuration:
- Added 8 IPC channels: APP_UPDATE_* operations & events
- Created AppUpdateInfo, AppUpdateProgress, AppUpdate*Event types
- GitHub release publishing: provider=github, repo=Auto-Claude

Features:
 Automatic update checking (3s after launch, every 4 hours)
 Auto-download updates in background with progress bar
 User notification with version & release notes
 One-click install and restart
 Dismissible with "Remind Me Later"
 Error handling & visual feedback
 Production-only (disabled in dev mode)

Non-technical users can now update the Electron app with one click!

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-18 09:38:20 +01:00
AndyMik90 d33a0aaff6 Fix Windows/Linux source path detection
- Enhanced detectAutoBuildSourcePath() to work across all platforms
- Separated dev vs production mode path resolution
- Added comprehensive path checking for Windows/Linux packaged apps
- Added debug logging (enable with AUTO_CLAUDE_DEBUG=1)
- Updated both settings-handlers.ts and project-handlers.ts
- Fixes 'Source path not configured' error on Windows/Linux

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-18 09:24:44 +01:00
AndyMik90 6cff4420c9 auto-claude: subtask-2-3 - Refine visual drop zone feedback to be more subtle
- Simplified main content area feedback to subtle background tint only
- Added dashed border hint when dragging but not over drop zone
- Made drop zone indicator more compact with smaller text/icons
- Added smooth transitions (150ms ease-out) for polish
- Reduced overlay opacity for less intrusive visual feedback
- Removed heavy ring effects that interfered with modal interactions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-17 23:19:27 +01:00
AndyMik90 12bf69def6 auto-claude: subtask-2-1 - Remove showFiles auto-expand on draft restore
Since the Referenced Files section is now always visible, remove the
conditional setShowFiles(true) in the useEffect that loads drafts.

Changes:
- Remove unused showFiles state variable
- Remove conditional that auto-expanded files section when restoring drafts
- Remove auto-expand call in handleDragEnd (section is always visible)
- Remove showFiles reset in resetForm

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-17 23:16:30 +01:00
AndyMik90 3818b4641f auto-claude: subtask-1-3 - Create an always-visible referenced files section
- Made referenced files section always visible in Create Task modal
- Added header with FolderTree icon and "Referenced Files" label
- Added count badge showing current/max files when files are present
- Added empty state hint: "Drag files from the file explorer to add references"
- Removed conditional showFiles rendering wrapper
- Section now shows before the Review Requirement Toggle

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-17 23:13:43 +01:00
AndyMik90 219b66dcc6 auto-claude: subtask-1-2 - Add drop zone wrapper around main modal content area
- Applied useDroppable ref to main form content div for drag-and-drop
- Added visual feedback (ring highlight, background change) when dragging files over the modal
- Visual states: blue ring when dragging over (can add), yellow ring when at max capacity
- Subtle ring indication when dragging but not over the drop zone
- Updated Referenced Files section to show visual feedback only during active drag
- Removed the compact collapsed drop zone (now redundant with main wrapper drop zone)
2025-12-17 23:11:23 +01:00
AndyMik90 4e63e8559d auto-claude: subtask-1-1 - Remove Reference Files toggle button
Remove the 'Reference Files (optional)' toggle button that controlled
the showFiles state for the collapsible section. The FolderTree icon
toggle with chevron is now removed from TaskCreationWizard.tsx.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-17 23:08:53 +01:00
AndyMik90 2fa3c51659 Update README.md to include git repository initialization and folder structure explanations
- Added instructions for initializing a git repository as a prerequisite for using Auto Claude.
- Included a section detailing the purpose of various folders created during the Auto Claude process, enhancing user understanding of the framework's structure.
2025-12-17 22:47:09 +01:00
AndyMik90 59b091a79f V 2.3.2 2025-12-17 22:37:52 +01:00
AndyMik90 a0c775f690 Merge branch 'auto-claude/028-fix-kanban-view-task-display-styling' 2025-12-17 22:19:09 +01:00
AndyMik90 9babdc23c1 fix to spec runner paths 2025-12-17 22:18:11 +01:00
AndyMik90 dc886dce44 auto-claude: subtask-1-1 - Restructure SortableFeatureCard badge layout
- Reorganize layout for better visual hierarchy: title first, then description, then metadata
- Make badges more compact with smaller text (text-[10px]) and reduced padding (px-1.5 py-0)
- Separate priority badge in header from complexity/impact badges in footer
- Replace competitor insight text with icon-only badge (with tooltip)
- Reduce card padding from p-4 to p-3
- Change title from truncate to line-clamp-2 for better readability
- Move complexity and impact badges to dedicated metadata row at bottom
- Remove " impact" text suffix for cleaner look
- Shorten "Go to Task" button text to "Task"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-17 22:04:47 +01:00
AndyMik90 32760348ae Fix to linux path issue 2025-12-17 21:42:53 +01:00
AndyMik90 395ba60098 Improvement/Terminal session persistence over app restart 2025-12-17 18:23:47 +01:00
AndyMik90 d85a1b4f63 V2.3.0 release for terminals 2025-12-17 17:28:02 +01:00
AndyMik90 43a593c1e1 Bug fix: dont let tasks slip by human review if the task was set as done. 2025-12-17 17:21:55 +01:00
AndyMik90 5078191d74 Added a release title for the github format - changelog functionality 2025-12-17 17:15:28 +01:00
AndyMik90 99850512e6 Implement PTY Daemon and Buffer Management
- Introduced a new PTY Daemon to handle terminal processes, ensuring session continuity and efficient resource management.
- Added session persistence for terminal states, allowing recovery across app restarts.
- Implemented buffer management to optimize terminal output handling, reducing React re-renders.
- Enhanced flow control and scroll management for better user experience during high-velocity terminal output.
- Refactored terminal store to utilize the new buffer manager, improving performance and memory management.
- Added WebGL context management for enhanced rendering capabilities in terminals.

This update significantly improves terminal performance and reliability, especially during intensive operations.
2025-12-17 17:05:37 +01:00
AndyMik90 f92fcfa075 Version 2.2.0 2025-12-17 16:23:00 +01:00
AndyMik90 f201f7e3a8 hotfix/spec-runner path location 2025-12-17 16:19:49 +01:00
314 changed files with 24359 additions and 3388 deletions
+132
View File
@@ -0,0 +1,132 @@
name: Build Native Module Prebuilds
on:
# Build on releases
release:
types: [published]
# Manual trigger for testing
workflow_dispatch:
inputs:
electron_version:
description: 'Electron version to build for'
required: false
default: '39.2.6'
env:
# Default Electron version - update when upgrading Electron in package.json
ELECTRON_VERSION: ${{ github.event.inputs.electron_version || '39.2.6' }}
jobs:
build-windows:
runs-on: windows-latest
strategy:
matrix:
arch: [x64]
# Add arm64 when GitHub Actions supports Windows ARM runners
# arch: [x64, arm64]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Install Visual Studio Build Tools
uses: microsoft/setup-msbuild@v2
- name: Install node-pty and rebuild for Electron
working-directory: auto-claude-ui
shell: pwsh
run: |
# Install only node-pty
pnpm add node-pty@1.1.0-beta42
# Get Electron ABI version
$electronAbi = (npx electron-abi $env:ELECTRON_VERSION)
Write-Host "Building for Electron $env:ELECTRON_VERSION (ABI: $electronAbi)"
# Rebuild node-pty for Electron
npx @electron/rebuild --version $env:ELECTRON_VERSION --module-dir node_modules/node-pty --arch ${{ matrix.arch }}
- name: Package prebuilt binaries
working-directory: auto-claude-ui
shell: pwsh
run: |
$electronAbi = (npx electron-abi $env:ELECTRON_VERSION)
$prebuildDir = "prebuilds/win32-${{ matrix.arch }}-electron-$electronAbi"
New-Item -ItemType Directory -Force -Path $prebuildDir
# Copy all built native files
$buildDir = "node_modules/node-pty/build/Release"
if (Test-Path $buildDir) {
Copy-Item "$buildDir/*.node" $prebuildDir/ -Force
Copy-Item "$buildDir/*.dll" $prebuildDir/ -Force -ErrorAction SilentlyContinue
Copy-Item "$buildDir/*.exe" $prebuildDir/ -Force -ErrorAction SilentlyContinue
# Also copy conpty files if they exist in subdirectory
if (Test-Path "$buildDir/conpty") {
Copy-Item "$buildDir/conpty/*" $prebuildDir/ -Force
}
}
# List what we packaged
Write-Host "Packaged prebuilds:"
Get-ChildItem $prebuildDir
- name: Create archive
working-directory: auto-claude-ui
shell: pwsh
run: |
$electronAbi = (npx electron-abi $env:ELECTRON_VERSION)
$archiveName = "node-pty-win32-${{ matrix.arch }}-electron-$electronAbi.zip"
Compress-Archive -Path "prebuilds/*" -DestinationPath $archiveName
Write-Host "Created archive: $archiveName"
Get-ChildItem $archiveName
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: node-pty-win32-${{ matrix.arch }}
path: auto-claude-ui/node-pty-*.zip
retention-days: 90
- name: Upload to release
if: github.event_name == 'release'
uses: softprops/action-gh-release@v1
with:
files: auto-claude-ui/node-pty-*.zip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Create a combined prebuilds package
package-prebuilds:
needs: build-windows
runs-on: ubuntu-latest
steps:
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
- name: List artifacts
run: |
echo "Downloaded artifacts:"
find artifacts -type f -name "*.zip"
- name: Upload combined artifact
uses: actions/upload-artifact@v4
with:
name: node-pty-prebuilds-all
path: artifacts/**/*.zip
retention-days: 90
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
uses: SethCohen/github-releases-to-discord@v1.19.0
with:
webhook_url: ${{ secrets.DISCORD_WEBHOOK_URL }}
color: "5865F2"
color: "5793266"
username: "Auto Claude Releases"
avatar_url: "https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png"
footer_title: "Auto Claude Changelog"
+71
View File
@@ -0,0 +1,71 @@
name: Validate Version
on:
push:
tags:
- 'v*'
jobs:
validate-version:
name: Validate package.json version matches tag
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Extract version from tag
id: tag_version
run: |
# Extract version from tag (e.g., v2.5.5 -> 2.5.5)
TAG_VERSION=${GITHUB_REF#refs/tags/v}
echo "version=$TAG_VERSION" >> $GITHUB_OUTPUT
echo "Tag version: $TAG_VERSION"
- name: Extract version from package.json
id: package_version
run: |
# Read version from package.json
PACKAGE_VERSION=$(node -p "require('./auto-claude-ui/package.json').version")
echo "version=$PACKAGE_VERSION" >> $GITHUB_OUTPUT
echo "Package.json version: $PACKAGE_VERSION"
- name: Compare versions
run: |
TAG_VERSION="${{ steps.tag_version.outputs.version }}"
PACKAGE_VERSION="${{ steps.package_version.outputs.version }}"
echo "=========================================="
echo "Version Validation"
echo "=========================================="
echo "Git tag version: v$TAG_VERSION"
echo "package.json version: $PACKAGE_VERSION"
echo "=========================================="
if [ "$TAG_VERSION" != "$PACKAGE_VERSION" ]; then
echo ""
echo "❌ ERROR: Version mismatch detected!"
echo ""
echo "The version in package.json ($PACKAGE_VERSION) does not match"
echo "the git tag version ($TAG_VERSION)."
echo ""
echo "To fix this:"
echo " 1. Delete this tag: git tag -d v$TAG_VERSION"
echo " 2. Update package.json version to $TAG_VERSION"
echo " 3. Commit the change"
echo " 4. Recreate the tag: git tag -a v$TAG_VERSION -m 'Release v$TAG_VERSION'"
echo ""
echo "Or use the automated script:"
echo " node scripts/bump-version.js $TAG_VERSION"
echo ""
exit 1
fi
echo ""
echo "✅ SUCCESS: Versions match!"
echo ""
- name: Version validation result
if: success()
run: |
echo "::notice::Version validation passed - package.json version matches tag v${{ steps.tag_version.outputs.version }}"
+1
View File
@@ -74,6 +74,7 @@ dmypy.json
.auto-claude-security.json
.auto-claude-status
.claude_settings.json
.update-metadata.json
# Development of Auto Build with Auto Build
dev/
+408
View File
@@ -1,3 +1,411 @@
## 2.6.0 - Multi-Provider Graphiti Support & Platform Fixes
### ✨ New Features
- **Google AI Provider for Graphiti**: Full Google AI (Gemini) support for both LLM and embeddings in the Memory Layer
- Add GoogleLLMClient with gemini-2.0-flash default model
- Add GoogleEmbedder with text-embedding-004 default model
- UI integration for Google API key configuration with link to Google AI Studio
- **Ollama LLM Provider in UI**: Add Ollama as an LLM provider option in Graphiti onboarding wizard
- Ollama runs locally and doesn't require an API key
- Configure Base URL instead of API key for local inference
- **LLM Provider Selection UI**: Add provider selection dropdown to Graphiti setup wizard for flexible backend configuration
- **Per-Project GitHub Configuration**: UI clarity improvements for per-project GitHub org/repo settings
### 🛠️ Improvements
- Enhanced Graphiti provider factory to support Google AI alongside existing providers
- Updated env-handlers to properly populate graphitiProviderConfig from .env files
- Improved type definitions with proper Graphiti provider config properties in AppSettings
- Better API key loading when switching between providers in settings
### 🐛 Bug Fixes
- **node-pty Migration**: Replaced node-pty with @lydell/node-pty for prebuilt Windows binaries
- Updated all imports to use @lydell/node-pty directly
- Fixed "Cannot find module 'node-pty'" startup error
- **GitHub Organization Support**: Fixed repository support for GitHub organization accounts
- Add defensive array validation for GitHub issues API response
- **Asyncio Deprecation**: Fixed asyncio deprecation warning by using get_running_loop() instead of get_event_loop()
- Applied ruff formatting and fixed import sorting (I001) in Google provider files
### 🔧 Other Changes
- Added google-generativeai dependency to requirements.txt
- Updated provider validation to include Google/Groq/HuggingFace type assertions
---
## What's Changed
- fix(graphiti): address CodeRabbit review comments by @adryserage in 679b8cd
- fix(lint): sort imports in Google provider files by @adryserage in 1a38a06
- feat(graphiti): add Google AI as LLM and embedding provider by @adryserage in fe69106
- fix: GitHub organization repository support by @mojaray2k in 873cafa
- feat(ui): add LLM provider selection to Graphiti onboarding by @adryserage in 4750869
- fix(types): add missing AppSettings properties for Graphiti providers by @adryserage in 6680ed4
- feat(ui): add Ollama as LLM provider option for Graphiti by @adryserage in a3eee92
- fix(ui): address PR review feedback for Graphiti provider selection by @adryserage in b8a419a
- fix(deps): update imports to use @lydell/node-pty directly by @adryserage in 2b61ebb
- fix(deps): replace node-pty with @lydell/node-pty for prebuilt binaries by @adryserage in e1aee6a
- fix: add UI clarity for per-project GitHub configuration by @mojaray2k in c9745b6
- fix: add defensive array validation for GitHub issues API response by @mojaray2k in b3636a5
---
## 2.5.5 - Enhanced Agent Reliability & Build Workflow
### ✨ New Features
- Required GitHub setup flow after Auto Claude initialization to ensure proper configuration
- Atomic log saving mechanism to prevent log file corruption during concurrent operations
- Per-session model and thinking level selection in insights management
- Multi-auth token support and ANTHROPIC_BASE_URL passthrough for flexible authentication
- Comprehensive DEBUG logging at Claude SDK invocation points for improved troubleshooting
- Auto-download of prebuilt node-pty binaries for Windows environments
- Enhanced merge workflow with current branch detection for accurate change previews
- Phase configuration module and enhanced agent profiles for improved flexibility
- Stage-only merge handling with comprehensive verification checks
- Authentication failure detection system with patterns and validation checks across agent pipeline
### 🛠️ Improvements
- Changed default agent profile from 'balanced' to 'auto' for more adaptive behavior
- Better GitHub issue tracking and improved user experience in issue management
- Improved merge preview accuracy using git diff counts for file statistics
- Preserved roadmap generation state when switching between projects
- Enhanced agent profiles with phase configuration support
### 🐛 Bug Fixes
- Resolved CI test failures and improved merge preview reliability
- Fixed CI failures related to linting, formatting, and tests
- Prevented dialog skip during project initialization flow
- Updated model IDs for Sonnet and Haiku to match current Claude versions
- Fixed branch namespace conflict detection to prevent worktree creation failures
- Removed duplicate LINEAR_API_KEY checks and consolidated imports
- Python 3.10+ version requirement enforced with proper version checking
- Prevented command injection vulnerabilities in GitHub API calls
### 🔧 Other Changes
- Code cleanup and test fixture updates
- Removed redundant auto-claude/specs directory structure
- Untracked .auto-claude directory to respect gitignore rules
---
## What's Changed
- fix: resolve CI test failures and improve merge preview by @AndyMik90 in de2eccd
- chore: code cleanup and test fixture updates by @AndyMik90 in 948db57
- refactor: change default agent profile from 'balanced' to 'auto' by @AndyMik90 in f98a13e
- security: prevent command injection in GitHub API calls by @AndyMik90 in 24ff491
- fix: resolve CI failures (lint, format, test) by @AndyMik90 in a8f2d0b
- fix: use git diff count for totalFiles in merge preview by @AndyMik90 in 46d2536
- feat: enhance stage-only merge handling with verification checks by @AndyMik90 in 7153558
- feat: introduce phase configuration module and enhance agent profiles by @AndyMik90 in 2672528
- fix: preserve roadmap generation state when switching projects by @AndyMik90 in 569e921
- feat: add required GitHub setup flow after Auto Claude initialization by @AndyMik90 in 03ccce5
- chore: remove redundant auto-claude/specs directory by @AndyMik90 in 64d5170
- chore: untrack .auto-claude directory (should be gitignored) by @AndyMik90 in 0710c13
- fix: prevent dialog skip during project initialization by @AndyMik90 in 56cedec
- feat: enhance merge workflow by detecting current branch by @AndyMik90 in c0c8067
- fix: update model IDs for Sonnet and Haiku by @AndyMik90 in 059315d
- feat: add comprehensive DEBUG logging and fix lint errors by @AndyMik90 in 99cf21e
- feat: implement atomic log saving to prevent corruption by @AndyMik90 in da5e26b
- feat: add better github issue tracking and UX by @AndyMik90 in c957eaa
- feat: add comprehensive DEBUG logging to Claude SDK invocation points by @AndyMik90 in 73d01c0
- feat: auto-download prebuilt node-pty binaries for Windows by @AndyMik90 in 41a507f
- feat(insights): add per-session model and thinking level selection by @AndyMik90 in e02aa59
- fix: require Python 3.10+ and add version check by @AndyMik90 in 9a5ca8c
- fix: detect branch namespace conflict blocking worktree creation by @AndyMik90 in 63a1d3c
- fix: remove duplicate LINEAR_API_KEY check and consolidate imports by @Jacob in 7d351e3
- feat: add multi-auth token support and ANTHROPIC_BASE_URL passthrough by @Jacob in 9dea155
## 2.5.0 - Roadmap Intelligence & Workflow Refinements
### ✨ New Features
- Interactive competitor analysis viewer for roadmap planning with real-time data visualization
- GitHub issue label mapping to task categories for improved organization and tracking
- GitHub issue comment selection in task creation workflow for better context integration
- TaskCreationWizard enhanced with drag-and-drop support for file references and inline @mentions
- Roadmap generation now includes stop functionality and comprehensive debug logging
### 🛠️ Improvements
- Refined visual drop zone feedback in file reference system for more subtle user guidance
- Remove auto-expand behavior for referenced files on draft restore to improve UX
- Always-visible referenced files section in TaskCreationWizard for better discoverability
- Drop zone wrapper added around main modal content area for improved drag-and-drop ergonomics
- Stuck task detection now enabled for ai_review status to better track blocked work
- Enhanced React component stability with proper key usage in RoadmapHeader and PhaseProgressIndicator
### 🐛 Bug Fixes
- Corrected CompetitorAnalysisViewer type definitions for proper TypeScript compliance
- Fixed multiple CodeRabbit review feedback items for improved code quality
- Resolved React key warnings in PhaseProgressIndicator component
- Fixed git status parsing in merge preview for accurate worktree state detection
- Corrected path resolution in runners for proper module imports and .env loading
- Resolved CI lint and TypeScript errors across codebase
- Fixed HTTP error handling and path resolution issues in core modules
- Corrected worktree test to match intended branch detection behavior
- Refined TaskReview component conditional rendering for proper staged task display
---
## What's Changed
- feat: add interactive competitor analysis viewer for roadmap by @AndyMik90 in 7ff326d
- fix: correct CompetitorAnalysisViewer to match type definitions by @AndyMik90 in 4f1766b
- fix: address multiple CodeRabbit review feedback items by @AndyMik90 in 48f7c3c
- fix: use stable React keys instead of array indices in RoadmapHeader by @AndyMik90 in 892e01d
- fix: additional fixes for http error handling and path resolution by @AndyMik90 in 54501cb
- fix: update worktree test to match intended branch detection behavior by @AndyMik90 in f1d578f
- fix: resolve CI lint and TypeScript errors by @AndyMik90 in 2e3a5d9
- feat: enhance roadmap generation with stop functionality and debug logging by @AndyMik90 in a6dad42
- fix: correct path resolution in runners for module imports and .env loading by @AndyMik90 in 3d24f8f
- fix: resolve React key warning in PhaseProgressIndicator by @AndyMik90 in 9106038
- fix: enable stuck task detection for ai_review status by @AndyMik90 in 895ed9f
- feat: map GitHub issue labels to task categories by @AndyMik90 in cbe14fd
- feat: add GitHub issue comment selection and fix auto-start bug by @AndyMik90 in 4c1dd89
- feat: enhance TaskCreationWizard with drag-and-drop support for file references and inline @mentions by @AndyMik90 in d93eefe
- cleanup docs by @AndyMik90 in 8e891df
- fix: correct git status parsing in merge preview by @AndyMik90 in c721dc2
- Update TaskReview component to refine conditional rendering for staged tasks, ensuring proper display when staging is unsuccessful by @AndyMik90 in 1a2b7a1
- auto-claude: subtask-2-3 - Refine visual drop zone feedback to be more subtle by @AndyMik90 in 6cff442
- auto-claude: subtask-2-1 - Remove showFiles auto-expand on draft restore by @AndyMik90 in 12bf69d
- auto-claude: subtask-1-3 - Create an always-visible referenced files section by @AndyMik90 in 3818b46
- auto-claude: subtask-1-2 - Add drop zone wrapper around main modal content area by @AndyMik90 in 219b66d
- auto-claude: subtask-1-1 - Remove Reference Files toggle button by @AndyMik90 in 4e63e85
## 2.4.0 - Enhanced Cross-Platform Experience with OAuth & Auto-Updates
### ✨ New Features
- Claude account OAuth implementation on onboarding for seamless token setup
- Integrated release workflow with AI-powered version suggestion capabilities
- Auto-upgrading functionality supporting Windows, Linux, and macOS with automatic app updates
- Git repository initialization on app startup with project addition checks
- Debug logging for app updater to track update processes
- Auto-open settings to updates section when app update is ready
### 🛠️ Improvements
- Major Windows and Linux compatibility enhancements for cross-platform reliability
- Enhanced task status handling to support 'done' status in limbo state with worktree existence checks
- Better handling of lock files from worktrees upon merging
- Improved README documentation and build process
- Refined visual drop zone feedback for more subtle user experience
- Removed showFiles auto-expand on draft restore for better UX consistency
- Created always-visible referenced files section in task creation wizard
- Removed Reference Files toggle button for streamlined interface
- Worktree manual deletion enforcement for early access safety (prevents accidental work loss)
### 🐛 Bug Fixes
- Corrected git status parsing in merge preview functionality
- Fixed ESLint warnings and failing tests
- Fixed Windows/Linux Python handling for cross-platform compatibility
- Fixed Windows/Linux source path detection
- Refined TaskReview component conditional rendering for proper staged task display
---
## What's Changed
- docs: cleanup docs by @AndyMik90 in 8e891df
- fix: correct git status parsing in merge preview by @AndyMik90 in c721dc2
- refactor: Update TaskReview component to refine conditional rendering for staged tasks by @AndyMik90 in 1a2b7a1
- feat: Enhance task status handling to allow 'done' status in limbo state by @AndyMik90 in a20b8cf
- improvement: Worktree needs to be manually deleted for early access safety by @AndyMik90 in 0ed6afb
- feat: Claude account OAuth implementation on onboarding by @AndyMik90 in 914a09d
- fix: Better handling of lock files from worktrees upon merging by @AndyMik90 in e44202a
- feat: GitHub OAuth integration upon onboarding by @AndyMik90 in 4249644
- chore: lock update by @AndyMik90 in b0fc497
- improvement: Improved README and build process by @AndyMik90 in 462edcd
- fix: ESLint warnings and failing tests by @AndyMik90 in affbc48
- feat: Major Windows and Linux compatibility enhancements with auto-upgrade by @AndyMik90 in d7fd1a2
- feat: Add debug logging to app updater by @AndyMik90 in 96dd04d
- feat: Auto-open settings to updates section when app update is ready by @AndyMik90 in 1d0566f
- feat: Add integrated release workflow with AI version suggestion by @AndyMik90 in 7f3cd59
- fix: Windows/Linux Python handling by @AndyMik90 in 0ef0e15
- feat: Implement Electron app auto-updater by @AndyMik90 in efc112a
- fix: Windows/Linux source path detection by @AndyMik90 in d33a0aa
- refactor: Refine visual drop zone feedback to be more subtle by @AndyMik90 in 6cff442
- refactor: Remove showFiles auto-expand on draft restore by @AndyMik90 in 12bf69d
- feat: Create always-visible referenced files section by @AndyMik90 in 3818b46
- feat: Add drop zone wrapper around main modal content by @AndyMik90 in 219b66d
- feat: Remove Reference Files toggle button by @AndyMik90 in 4e63e85
- docs: Update README with git initialization and folder structure by @AndyMik90 in 2fa3c51
- chore: Version bump to 2.3.2 by @AndyMik90 in 59b091a
## 2.3.2 - UI Polish & Build Improvements
### 🛠️ Improvements
- Restructured SortableFeatureCard badge layout for improved visual presentation
Bug Fixes:
- Fixed spec runner path configuration for more reliable task execution
---
## What's Changed
- fix: fix to spec runner paths by @AndyMik90 in 9babdc2
- feat: auto-claude: subtask-1-1 - Restructure SortableFeatureCard badge layout by @AndyMik90 in dc886dc
## 2.3.1 - Linux Compatibility Fix
### 🐛 Bug Fixes
- Resolved path handling issues on Linux systems for improved cross-platform compatibility
---
## What's Changed
- fix: Fix to linux path issue by @AndyMik90 in 3276034
## 2.2.0 - 2025-12-17
### ✨ New Features
- Add usage monitoring with profile swap detection to prevent cascading resource issues
- Option to stash changes before merge operations for safer branch integration
- Add hideCloseButton prop to DialogContent component for improved UI flexibility
### 🛠️ Improvements
- Enhance AgentManager to manage task context cleanup and preserve swapCount on restarts
- Improve changelog feature with version tracking, markdown/preview, and persistent styling options
- Refactor merge conflict handling to use branch names instead of commit hashes for better clarity
- Streamline usage monitoring logic by removing unnecessary dynamic imports
- Better handling of lock files during merge conflicts
- Refactor code for improved readability and maintainability
- Refactor IdeationHeader and update handleDeleteSelected logic
### 🐛 Bug Fixes
- Fix worktree merge logic to correctly handle branch operations
- Fix spec_runner.py path resolution after move to runners/ directory
- Fix Discord release webhook failing on large changelogs
- Fix branch logic for merge AI operations
- Hotfix for spec-runner path location
---
## What's Changed
- fix: hotfix/spec-runner path location by @AndyMik90 in f201f7e
- refactor: Remove unnecessary dynamic imports of getUsageMonitor in terminal-handlers.ts to streamline usage monitoring logic by @AndyMik90 in 0da4bc4
- feat: Improve changelog feature, version tracking, markdown/preview, persistent styling options by @AndyMik90 in a0d142b
- refactor: Refactor code for improved readability and maintainability by @AndyMik90 in 473b045
- feat: Enhance AgentManager to manage task context cleanup and preserve swapCount on restarts. Update UsageMonitor to delay profile usage checks to prevent cascading swaps by @AndyMik90 in e5b9488
- feat: Usage-monitoring by @AndyMik90 in de33b2c
- feat: option to stash changes before merge by @AndyMik90 in 7e09739
- refactor: Refactor merge conflict check to use branch names instead of commit hashes by @AndyMik90 in e6d6cea
- fix: worktree merge logic by @AndyMik90 in dfb5cf9
- test: Sign off - all verification passed by @AndyMik90 in 34631c3
- feat: Pass hideCloseButton={showFileExplorer} to DialogContent by @AndyMik90 in 7c327ed
- feat: Add hideCloseButton prop to DialogContent component by @AndyMik90 in 5f9653a
- fix: branch logic for merge AI by @AndyMik90 in 2d2a813
- fix: spec_runner.py path resolution after move to runners/ directory by @AndyMik90 in ce9c2cd
- refactor: Better handling of lock files during merge conflicts by @AndyMik90 in 460c76d
- fix: Discord release webhook failing on large changelogs by @AndyMik90 in 4eb66f5
- chore: Update CHANGELOG with new features, improvements, bug fixes, and other changes by @AndyMik90 in 788b8d0
- refactor: Enhance merge conflict handling by excluding lock files by @AndyMik90 in 957746e
- refactor: Refactor IdeationHeader and update handleDeleteSelected logic by @AndyMik90 in 36338f3
## What's New
### ✨ New Features
+18 -3
View File
@@ -81,6 +81,21 @@ auto-claude/.venv/bin/pytest tests/ -m "not slow"
python auto-claude/validate_spec.py --spec-dir auto-claude/specs/001-feature --checkpoint all
```
### Releases
```bash
# Automated version bump and release (recommended)
node scripts/bump-version.js patch # 2.5.5 -> 2.5.6
node scripts/bump-version.js minor # 2.5.5 -> 2.6.0
node scripts/bump-version.js major # 2.5.5 -> 3.0.0
node scripts/bump-version.js 2.6.0 # Set specific version
# Then push to trigger GitHub release workflows
git push origin main
git push origin v2.6.0
```
See [RELEASE.md](RELEASE.md) for detailed release process documentation.
## Architecture
### Core Pipeline
@@ -103,7 +118,7 @@ python auto-claude/validate_spec.py --spec-dir auto-claude/specs/001-feature --c
- **worktree.py** - Git worktree isolation for safe feature development
- **memory.py** - File-based session memory (primary, always-available storage)
- **graphiti_memory.py** - Optional graph-based cross-session memory with semantic search
- **graphiti_providers.py** - Multi-provider factory for Graphiti (OpenAI, Anthropic, Azure, Ollama)
- **graphiti_providers.py** - Multi-provider factory for Graphiti (OpenAI, Anthropic, Azure, Ollama, Google AI)
- **graphiti_config.py** - Configuration and validation for Graphiti integration
- **linear_updater.py** - Optional Linear integration for progress tracking
@@ -177,8 +192,8 @@ Dual-layer memory architecture:
- Graph database with semantic search (FalkorDB)
- Cross-session context retrieval
- Multi-provider support (V2):
- LLM: OpenAI, Anthropic, Azure OpenAI, Ollama
- Embedders: OpenAI, Voyage AI, Azure OpenAI, Ollama
- LLM: OpenAI, Anthropic, Azure OpenAI, Ollama, Google AI (Gemini)
- Embedders: OpenAI, Voyage AI, Azure OpenAI, Ollama, Google AI
Enable with: `GRAPHITI_ENABLED=true` + provider credentials. See `.env.example`.
+57 -6
View File
@@ -4,7 +4,7 @@ Your AI coding companion. Build features, fix bugs, and ship faster — with aut
![Auto Claude Kanban Board](.github/assets/Auto-Claude-Kanban.png)
[![Discord](https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/maj9EWmY)
[![Discord](https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/KCXaPBr4Dj)
## What It Does ✨
@@ -35,10 +35,24 @@ The Desktop UI is the recommended way to use Auto Claude. It provides visual tas
### Prerequisites
1. **Node.js 18+** - [Download Node.js](https://nodejs.org/)
2. **Python 3.9+** - [Download Python](https://www.python.org/downloads/)
2. **Python 3.10+** - [Download Python](https://www.python.org/downloads/)
3. **Docker Desktop** - Required for the Memory Layer
4. **Claude Code CLI** - `npm install -g @anthropic-ai/claude-code`
5. **Claude Subscription** - Requires [Claude Pro or Max](https://claude.ai/upgrade) for Claude Code access
6. **Git Repository** - Your project must be initialized as a git repository
### Git Initialization
**Auto Claude requires a git repository** to create isolated worktrees for safe parallel development. If your project isn't a git repo yet:
```bash
cd your-project
git init
git add .
git commit -m "Initial commit"
```
> **Why git?** Auto Claude uses git branches and worktrees to isolate each task in its own workspace, keeping your main branch clean until you're ready to merge. This allows you to work on multiple features simultaneously without conflicts.
---
@@ -100,6 +114,18 @@ pnpm run build && pnpm run start
# or: npm run build && npm run start
```
<details>
<summary><b>Windows users:</b> If installation fails with node-gyp errors, click here</summary>
Auto Claude automatically downloads prebuilt binaries for Windows. If prebuilts aren't available for your Electron version yet, you'll need Visual Studio Build Tools:
1. Download [Visual Studio Build Tools 2022](https://visualstudio.microsoft.com/visual-cpp-build-tools/)
2. Select "Desktop development with C++" workload
3. In "Individual Components", add "MSVC v143 - VS 2022 C++ x64/x86 Spectre-mitigated libs"
4. Restart terminal and run `npm install` again
</details>
### Step 4: Start Building
1. Add your project in the UI
@@ -222,12 +248,13 @@ The Memory Layer is a **hybrid RAG system** combining graph nodes with semantic
**Architecture:**
- **Backend**: FalkorDB (graph database) via Docker
- **Library**: Graphiti for knowledge graph operations
- **Providers**: OpenAI, Anthropic, Azure OpenAI, or Ollama (local/offline)
- **Providers**: OpenAI, Anthropic, Azure OpenAI, Google AI, or Ollama (local/offline)
| Setup | LLM | Embeddings | Notes |
|-------|-----|------------|-------|
| **OpenAI** | OpenAI | OpenAI | Simplest - single API key |
| **Anthropic + Voyage** | Anthropic | Voyage AI | High quality |
| **Google AI** | Gemini | Google | Single API key, fast inference |
| **Ollama** | Ollama | Ollama | Fully offline |
| **Azure** | Azure OpenAI | Azure OpenAI | Enterprise |
@@ -251,6 +278,29 @@ your-project/
└── docker-compose.yml # FalkorDB for Memory Layer
```
### Understanding the Folders
**You don't create these folders manually** - they serve different purposes:
- **`auto-claude/`** - The framework repository itself (clone this once from GitHub)
- **`.auto-claude/`** - Created automatically in YOUR project when you run Auto Claude (stores specs, plans, QA reports)
- **`.worktrees/`** - Temporary isolated workspaces created during builds (git-ignored, deleted after merge)
**When using Auto Claude on your project:**
```bash
cd your-project/ # Your own project directory
python /path/to/auto-claude/run.py --spec 001
# Auto Claude creates .auto-claude/ automatically in your-project/
```
**When developing Auto Claude itself:**
```bash
git clone https://github.com/yourusername/auto-claude
cd auto-claude/ # You're working in the framework repo
```
The `.auto-claude/` directory is gitignored and project-specific - you'll have one per project you use Auto Claude on.
## Environment Variables (CLI Only)
> **Desktop UI users:** These are configured through the app settings — no manual setup needed.
@@ -260,11 +310,12 @@ your-project/
| `CLAUDE_CODE_OAUTH_TOKEN` | Yes | OAuth token from `claude setup-token` |
| `AUTO_BUILD_MODEL` | No | Model override (default: claude-opus-4-5-20251101) |
| `GRAPHITI_ENABLED` | Recommended | Set to `true` to enable Memory Layer |
| `GRAPHITI_LLM_PROVIDER` | For Memory | LLM provider: openai, anthropic, azure_openai, ollama |
| `GRAPHITI_EMBEDDER_PROVIDER` | For Memory | Embedder: openai, voyage, azure_openai, ollama |
| `GRAPHITI_LLM_PROVIDER` | For Memory | LLM provider: openai, anthropic, azure_openai, ollama, google |
| `GRAPHITI_EMBEDDER_PROVIDER` | For Memory | Embedder: openai, voyage, azure_openai, ollama, google |
| `OPENAI_API_KEY` | For OpenAI | Required for OpenAI provider |
| `ANTHROPIC_API_KEY` | For Anthropic | Required for Anthropic LLM |
| `VOYAGE_API_KEY` | For Voyage | Required for Voyage embeddings |
| `GOOGLE_API_KEY` | For Google | Required for Google AI (Gemini) provider |
See `auto-claude/.env.example` for complete configuration options.
@@ -272,7 +323,7 @@ See `auto-claude/.env.example` for complete configuration options.
Join our Discord to get help, share what you're building, and connect with other Auto Claude users:
[![Discord](https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/maj9EWmY)
[![Discord](https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/KCXaPBr4Dj)
## 🤝 Contributing
+186
View File
@@ -0,0 +1,186 @@
# Release Process
This document describes how to create a new release of Auto Claude.
## Automated Release Process (Recommended)
We provide an automated script that handles version bumping, git commits, and tagging to ensure version consistency.
### Prerequisites
- Clean git working directory (no uncommitted changes)
- You're on the branch you want to release from (usually `main`)
### Steps
1. **Run the version bump script:**
```bash
# Bump patch version (2.5.5 -> 2.5.6)
node scripts/bump-version.js patch
# Bump minor version (2.5.5 -> 2.6.0)
node scripts/bump-version.js minor
# Bump major version (2.5.5 -> 3.0.0)
node scripts/bump-version.js major
# Set specific version
node scripts/bump-version.js 2.6.0
```
This script will:
- ✅ Update `auto-claude-ui/package.json` with the new version
- ✅ Create a git commit with the version change
- ✅ Create a git tag (e.g., `v2.5.6`)
- ⚠️ **NOT** push to remote (you control when to push)
2. **Review the changes:**
```bash
git log -1 # View the commit
git show v2.5.6 # View the tag
```
3. **Push to GitHub:**
```bash
# Push the commit
git push origin main
# Push the tag
git push origin v2.5.6
```
4. **Create GitHub Release:**
- Go to [GitHub Releases](https://github.com/AndyMik90/Auto-Claude/releases)
- Click "Draft a new release"
- Select the tag you just pushed (e.g., `v2.5.6`)
- Add release notes (describe what changed)
- Click "Publish release"
5. **Automated builds will trigger:**
- ✅ Version validation workflow will verify version consistency
- ✅ Tests will run (`test-on-tag.yml`)
- ✅ Native module prebuilds will be created (`build-prebuilds.yml`)
- ✅ Discord notification will be sent (`discord-release.yml`)
## Manual Release Process (Not Recommended)
If you need to create a release manually, follow these steps **carefully** to avoid version mismatches:
1. **Update `auto-claude-ui/package.json`:**
```json
{
"version": "2.5.6"
}
```
2. **Commit the change:**
```bash
git add auto-claude-ui/package.json
git commit -m "chore: bump version to 2.5.6"
```
3. **Create and push tag:**
```bash
git tag -a v2.5.6 -m "Release v2.5.6"
git push origin main
git push origin v2.5.6
```
4. **Create GitHub Release** (same as step 4 above)
## Version Validation
A GitHub Action automatically validates that the version in `package.json` matches the git tag.
If there's a mismatch, the workflow will **fail** with a clear error message:
```
❌ ERROR: Version mismatch detected!
The version in package.json (2.5.0) does not match
the git tag version (2.5.5).
To fix this:
1. Delete this tag: git tag -d v2.5.5
2. Update package.json version to 2.5.5
3. Commit the change
4. Recreate the tag: git tag -a v2.5.5 -m 'Release v2.5.5'
```
This validation ensures we never ship a release where the updater shows the wrong version.
## Troubleshooting
### Version Mismatch Error
If you see a version mismatch error in GitHub Actions:
1. **Delete the incorrect tag:**
```bash
git tag -d v2.5.6 # Delete locally
git push origin :refs/tags/v2.5.6 # Delete remotely
```
2. **Use the automated script:**
```bash
node scripts/bump-version.js 2.5.6
git push origin main
git push origin v2.5.6
```
### Git Working Directory Not Clean
If the version bump script fails with "Git working directory is not clean":
```bash
# Commit or stash your changes first
git status
git add .
git commit -m "your changes"
# Then run the version bump script
node scripts/bump-version.js patch
```
## Release Checklist
Use this checklist when creating a new release:
- [ ] All tests passing on main branch
- [ ] CHANGELOG updated (if applicable)
- [ ] Run `node scripts/bump-version.js <type>`
- [ ] Review commit and tag
- [ ] Push commit and tag to GitHub
- [ ] Create GitHub Release with release notes
- [ ] Verify version validation passed
- [ ] Verify builds completed successfully
- [ ] Test the updater shows correct version
## What Gets Released
When you create a release, the following are built and published:
1. **Native module prebuilds** - Windows node-pty binaries
2. **Electron app packages** - Desktop installers (triggered manually or via electron-builder)
3. **Discord notification** - Sent to the Auto Claude community
## Version Numbering
We follow [Semantic Versioning (SemVer)](https://semver.org/):
- **MAJOR** version (X.0.0) - Breaking changes
- **MINOR** version (0.X.0) - New features (backward compatible)
- **PATCH** version (0.0.X) - Bug fixes (backward compatible)
Examples:
- `2.5.5 -> 2.5.6` - Bug fix
- `2.5.6 -> 2.6.0` - New feature
- `2.6.0 -> 3.0.0` - Breaking change
+48
View File
@@ -0,0 +1,48 @@
# Auto Claude UI Environment Variables
# Copy this file to .env and set your values
# ============================================
# DEBUG SETTINGS
# ============================================
# Enable general debug logging for ideation and roadmap features
# When enabled, you'll see detailed console logs for:
# - Ideation generation and stop functionality
# - Roadmap generation and stop functionality
# - IPC communication between processes
# - Store state updates
# Usage: Set to 'true' before starting the app
# DEBUG=true
# Enable debug logging for the auto-updater
# Shows detailed information about app update checks and downloads
# DEBUG_UPDATER=true
# Enable debug logging for Auto Claude features
# Affects changelog generation, project initialization, and other core features
# AUTO_CLAUDE_DEBUG=true
# ============================================
# HOW TO USE
# ============================================
# Option 1: Set in your shell before starting the app
# DEBUG=true npm start
#
# Option 2: Export in your shell profile (~/.bashrc, ~/.zshrc, etc.)
# export DEBUG=true
# export AUTO_CLAUDE_DEBUG=true
#
# Option 3: Create a .env file in this directory (auto-claude-ui/)
# Copy this file: cp .env.example .env
# Then uncomment and set the variables you need
#
# Note: The Electron app will read these from process.env
# The Python backend (auto-claude) has its own .env file
# ============================================
# DEVELOPMENT
# ============================================
# Node environment (automatically set by npm scripts)
# NODE_ENV=development
+108 -139
View File
@@ -2,161 +2,130 @@
A desktop application for managing AI-driven development tasks using the Auto Claude autonomous coding framework.
## Overview
## Quick Start
Auto Claude UI provides a visual Kanban board interface for creating, monitoring, and managing auto-claude tasks. It replaces the terminal-based workflow with an intuitive GUI while preserving all CLI functionality.
```bash
# 1. Clone the repo (if you haven't already)
git clone https://github.com/AndyMik90/Auto-Claude.git
cd Auto-Claude/auto-claude-ui
# 2. Install dependencies
npm install
# 3. Build the desktop app
npm run package:win # Windows
npm run package:mac # macOS
npm run package:linux # Linux
# 4. Run the app
# Windows: .\dist\win-unpacked\Auto Claude.exe
# macOS: open dist/mac-arm64/Auto\ Claude.app
# Linux: ./dist/linux-unpacked/auto-claude
```
## Prerequisites
- Node.js 18+
- npm or pnpm
- Python 3.10+ (for auto-claude backend)
- **Windows only**: Visual Studio Build Tools 2022 with "Desktop development with C++" workload
- **Windows only**: Developer Mode enabled (Settings → System → For developers)
## How to Run
### Building for Production (Recommended)
Build the Electron desktop app for your platform:
```bash
# Build for Windows
npm run package:win
# Build for macOS
npm run package:mac
# Build for Linux
npm run package:linux
```
### Running the Production Build
After building, run the application from the `dist` folder:
```bash
# Windows - run the executable
.\dist\win-unpacked\Auto Claude.exe
# Windows - or use the installer
.\dist\Auto Claude Setup X.X.X.exe
# macOS
open dist/mac-arm64/Auto\ Claude.app
# Linux
./dist/linux-unpacked/auto-claude
```
### Development Mode
For development with hot reload (optional):
```bash
npm run dev
```
> **Note**: Some features like auto-updates only work in packaged builds.
## Distribution Files
After packaging, the `dist` folder contains:
| Platform | Files |
|----------|-------|
| macOS | `Auto Claude.app`, `.dmg`, `.zip` |
| Windows | `Auto Claude Setup X.X.X.exe` (installer), `.zip`, `win-unpacked/` |
| Linux | `.AppImage`, `.deb`, `linux-unpacked/` |
## Testing
```bash
# Run tests
npm run test
```
## Linting
```bash
# Run ESLint
npm run lint
# Run type checking
npm run typecheck
```
## Features
- **Project Management**: Add, configure, and switch between multiple projects
- **Kanban Board**: Visual task board with columns for Backlog, In Progress, AI Review, Human Review, and Done
- **Task Creation Wizard**: Form-based interface for creating new tasks
- **Real-Time Progress**: Live updates from implementation_plan.json during agent execution
- **Real-Time Progress**: Live updates during agent execution
- **Human Review Workflow**: Review QA results and provide feedback
- **Theme Support**: Light and dark mode with system preference detection
- **Settings**: Per-project and app-wide configuration options
- **Theme Support**: Light and dark mode
- **Auto Updates**: Automatic update notifications
## Tech Stack
- **Framework**: Electron with React 18 (TypeScript)
- **Build Tool**: electron-vite with electron-builder
- **UI Components**: Radix UI primitives (shadcn/ui pattern)
- **Styling**: TailwindCSS with dark mode support
- **Framework**: Electron + React 18 (TypeScript)
- **Build Tool**: electron-vite + electron-builder
- **UI Components**: Radix UI (shadcn/ui pattern)
- **Styling**: TailwindCSS
- **State Management**: Zustand
- **File Watching**: chokidar
## Project Structure
```
auto-claude-ui/
├── src/
│ ├── main/ # Electron main process
│ │ ├── index.ts # App entry point
│ │ ├── agent-manager.ts # Python subprocess management
│ │ ├── file-watcher.ts # Implementation plan watching
│ │ ├── ipc-handlers.ts # IPC message handlers
│ │ └── project-store.ts # JSON project persistence
│ ├── preload/ # Preload scripts
│ │ └── index.ts # Secure contextBridge API
│ ├── renderer/ # React application
│ │ ├── components/ # React components
│ │ │ ├── ui/ # Wrapped Radix UI components
│ │ │ ├── Sidebar.tsx
│ │ │ ├── KanbanBoard.tsx
│ │ │ ├── TaskCard.tsx
│ │ │ ├── TaskDetailPanel.tsx
│ │ │ ├── TaskCreationWizard.tsx
│ │ │ ├── ProjectSettings.tsx
│ │ │ └── AppSettings.tsx
│ │ ├── stores/ # Zustand state stores
│ │ ├── hooks/ # Custom React hooks
│ │ ├── styles/ # Global CSS
│ │ └── App.tsx # Root component
│ └── shared/ # Shared code
│ ├── types.ts # TypeScript interfaces
│ └── constants.ts # Constants and IPC channels
├── electron.vite.config.ts # Build configuration
├── package.json
├── tsconfig.json
├── tailwind.config.js
└── postcss.config.js
```
## Getting Started
### Prerequisites
- Node.js 18+
- npm or pnpm
- Python 3.10+ (for auto-claude backend)
### Installation
```bash
# Navigate to auto-claude-ui directory
cd auto-claude-ui
# Install dependencies
npm install
```
### Development
```bash
# Start development server with hot reload
npm run dev
```
### Build
```bash
# Build for production
npm run build
# Package for macOS
npm run package:mac
# Package for Windows
npm run package:win
# Package for Linux
npm run package:linux
```
### Type Checking
```bash
npm run typecheck
```
### Linting
```bash
npm run lint
```
### Testing
```bash
npm run test
```
## Architecture
### Main Process
The main process handles:
- Window management
- Python subprocess spawning (agent-manager.ts)
- File system watching (file-watcher.ts)
- Project data persistence (project-store.ts)
- IPC communication with renderer
### Preload Script
Provides a secure bridge between main and renderer processes using Electron's contextBridge. All IPC channels are explicitly defined and typed.
### Renderer Process
A React application with:
- Zustand stores for state management
- Custom hooks for IPC event handling
- Radix UI components wrapped in the shadcn/ui pattern
- TailwindCSS for styling
## Security
The application follows Electron security best practices:
- `contextIsolation: true`
- `nodeIntegration: false`
- Minimal API surface via contextBridge
- No direct ipcRenderer exposure
## Environment Variables
- `CLAUDE_CODE_OAUTH_TOKEN`: OAuth token for Claude Code SDK (from auto-claude/.env)
- `FALKORDB_URL`: FalkorDB connection URL (optional, defaults to localhost:6379)
- `FALKORDB_URL`: FalkorDB connection URL (optional)
## License
MIT
AGPL-3.0
+5 -5
View File
@@ -9,7 +9,7 @@
* To run: npx playwright test --config=e2e/playwright.config.ts
*/
import { test, expect, _electron as electron, ElectronApplication, Page } from '@playwright/test';
import { mkdirSync, rmSync, existsSync, writeFileSync } from 'fs';
import { mkdirSync, rmSync, existsSync, writeFileSync, readFileSync } from 'fs';
import path from 'path';
// Test data directory
@@ -269,13 +269,13 @@ test.describe('E2E Flow Verification (Mock-based)', () => {
'implementation_plan.json'
);
const plan = JSON.parse(require('fs').readFileSync(planPath, 'utf-8'));
const plan = JSON.parse(readFileSync(planPath, 'utf-8'));
plan.phases[0].chunks[0].status = 'in_progress';
writeFileSync(planPath, JSON.stringify(plan, null, 2));
// Verify update
const updatedPlan = JSON.parse(require('fs').readFileSync(planPath, 'utf-8'));
const updatedPlan = JSON.parse(readFileSync(planPath, 'utf-8'));
expect(updatedPlan.phases[0].chunks[0].status).toBe('in_progress');
cleanupTestEnvironment();
@@ -298,7 +298,7 @@ test.describe('E2E Flow Verification (Mock-based)', () => {
expect(existsSync(qaReportPath)).toBe(true);
const content = require('fs').readFileSync(qaReportPath, 'utf-8');
const content = readFileSync(qaReportPath, 'utf-8');
expect(content).toContain('APPROVED');
cleanupTestEnvironment();
@@ -324,7 +324,7 @@ test.describe('E2E Flow Verification (Mock-based)', () => {
expect(existsSync(fixRequestPath)).toBe(true);
const content = require('fs').readFileSync(fixRequestPath, 'utf-8');
const content = readFileSync(fixRequestPath, 'utf-8');
expect(content).toContain('REJECTED');
expect(content).toContain('Needs more tests');
+1 -1
View File
@@ -1,7 +1,7 @@
/**
* Playwright configuration for Electron E2E tests
*/
import { defineConfig, devices } from '@playwright/test';
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: '.',
+10 -2
View File
@@ -5,14 +5,22 @@ import { resolve } from 'path';
export default defineConfig({
main: {
plugins: [externalizeDepsPlugin({
exclude: []
// Bundle these packages into the main process (they won't be in node_modules in packaged app)
exclude: [
'uuid',
'chokidar',
'ioredis',
'electron-updater',
'@electron-toolkit/utils'
]
})],
build: {
rollupOptions: {
input: {
index: resolve(__dirname, 'src/main/index.ts')
},
external: ['node-pty']
// Only node-pty needs to be external (native module rebuilt by electron-builder)
external: ['@lydell/node-pty']
}
}
},
+1 -1
View File
@@ -31,7 +31,7 @@ export default tseslint.config(
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_', varsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' }],
'@typescript-eslint/no-empty-object-type': 'off',
'@typescript-eslint/no-unsafe-function-type': 'off',
+1552 -32
View File
File diff suppressed because it is too large Load Diff
+44 -9
View File
@@ -1,12 +1,12 @@
{
"name": "auto-claude-ui",
"version": "2.0.1",
"version": "2.6.0",
"description": "Desktop UI for Auto Claude autonomous coding framework",
"main": "./out/main/index.js",
"author": "Auto Claude Team",
"license": "AGPL-3.0",
"scripts": {
"postinstall": "electron-rebuild",
"postinstall": "node scripts/postinstall.js",
"dev": "electron-vite dev",
"build": "electron-vite build",
"start": "electron .",
@@ -30,6 +30,7 @@
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@lydell/node-pty": "^1.1.0",
"@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-checkbox": "^1.1.4",
"@radix-ui/react-collapsible": "^1.1.3",
@@ -48,15 +49,17 @@
"@tailwindcss/typography": "^0.5.19",
"@tanstack/react-virtual": "^3.13.13",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-serialize": "^0.13.0",
"@xterm/addon-web-links": "^0.11.0",
"@xterm/addon-webgl": "^0.18.0",
"@xterm/xterm": "^5.5.0",
"chokidar": "^5.0.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"electron-updater": "^6.6.2",
"ioredis": "^5.8.2",
"lucide-react": "^0.560.0",
"motion": "^12.23.26",
"node-pty": "^1.0.0",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"react-markdown": "^10.1.0",
@@ -101,23 +104,54 @@
"pnpm": {
"overrides": {
"electron-builder-squirrel-windows": "^26.0.12",
"dmg-builder": "^26.0.12"
"dmg-builder": "^26.0.12",
"node-pty": "npm:@lydell/node-pty@^1.1.0"
},
"onlyBuiltDependencies": [
"electron",
"esbuild",
"node-pty"
"electron-winstaller",
"esbuild"
]
},
"build": {
"appId": "com.autoclaude.ui",
"productName": "Auto Claude",
"publish": [
{
"provider": "github",
"owner": "AndyMik90",
"repo": "Auto-Claude"
}
],
"directories": {
"output": "dist",
"buildResources": "resources"
},
"files": [
"out/**/*"
"out/**/*",
"package.json"
],
"extraResources": [
{
"from": "node_modules/@lydell/node-pty",
"to": "node_modules/@lydell/node-pty"
},
{
"from": "resources/icon.ico",
"to": "icon.ico"
},
{
"from": "../auto-claude",
"to": "auto-claude",
"filter": [
"!**/.git",
"!**/__pycache__",
"!**/*.pyc",
"!**/specs",
"!**/.venv",
"!**/.env"
]
}
],
"mac": {
"category": "public.app-category.developer-tools",
@@ -128,7 +162,7 @@
]
},
"win": {
"icon": "resources/icon-256.png",
"icon": "resources/icon.ico",
"target": [
"nsis",
"zip"
@@ -147,5 +181,6 @@
"*.{ts,tsx}": [
"eslint --fix"
]
}
},
"packageManager": "pnpm@10.26.1+sha512.664074abc367d2c9324fdc18037097ce0a8f126034160f709928e9e9f95d98714347044e5c3164d65bd5da6c59c6be362b107546292a8eecb7999196e5ce58fa"
}
+704 -335
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

@@ -0,0 +1,248 @@
#!/usr/bin/env node
/**
* Download prebuilt native modules for Windows
*
* This script downloads pre-compiled node-pty binaries from GitHub releases,
* eliminating the need for Visual Studio Build Tools on Windows.
*/
const https = require('https');
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const GITHUB_REPO = 'AndyMik90/Auto-Claude';
const GITHUB_API = 'https://api.github.com';
/**
* Get the Electron ABI version for the installed Electron
*/
function getElectronAbi() {
try {
// Try to get from electron-abi package
const result = execSync('npx electron-abi', {
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'pipe'],
}).trim();
return result;
} catch {
// Fallback: read from electron package
try {
const electronPkg = require('electron/package.json');
const version = electronPkg.version;
// Electron 39.x = ABI 140
const majorVersion = parseInt(version.split('.')[0], 10);
// This is a rough mapping, electron-abi is more accurate
const abiMap = {
39: 140,
38: 139,
37: 136,
36: 135,
35: 134,
34: 132,
33: 131,
32: 130,
31: 129,
30: 128,
};
return abiMap[majorVersion] || null;
} catch {
return null;
}
}
}
/**
* Get the latest release from GitHub
*/
function getLatestRelease() {
return new Promise((resolve, reject) => {
const options = {
hostname: 'api.github.com',
path: `/repos/${GITHUB_REPO}/releases/latest`,
headers: {
'User-Agent': 'Auto-Claude-Installer',
Accept: 'application/vnd.github.v3+json',
},
};
https
.get(options, (res) => {
let data = '';
res.on('data', (chunk) => (data += chunk));
res.on('end', () => {
if (res.statusCode === 200) {
resolve(JSON.parse(data));
} else if (res.statusCode === 404) {
resolve(null); // No releases yet
} else {
reject(new Error(`GitHub API returned ${res.statusCode}`));
}
});
})
.on('error', reject);
});
}
/**
* Find prebuild asset in release
*/
function findPrebuildAsset(release, arch, electronAbi) {
if (!release || !release.assets) return null;
const assetName = `node-pty-win32-${arch}-electron-${electronAbi}.zip`;
return release.assets.find((asset) => asset.name === assetName);
}
/**
* Download a file from URL
*/
function downloadFile(url, destPath) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(destPath);
const request = (url) => {
https
.get(url, { headers: { 'User-Agent': 'Auto-Claude-Installer' } }, (res) => {
if (res.statusCode === 302 || res.statusCode === 301) {
// Follow redirect
request(res.headers.location);
return;
}
if (res.statusCode !== 200) {
reject(new Error(`Download failed with status ${res.statusCode}`));
return;
}
res.pipe(file);
file.on('finish', () => {
file.close();
resolve();
});
})
.on('error', (err) => {
fs.unlink(destPath, () => {}); // Delete partial file
reject(err);
});
};
request(url);
});
}
/**
* Extract zip file (using built-in tools)
*/
function extractZip(zipPath, destDir) {
const { execSync } = require('child_process');
// Use PowerShell on Windows
execSync(`powershell -Command "Expand-Archive -Path '${zipPath}' -DestinationPath '${destDir}' -Force"`, {
stdio: 'inherit',
});
}
/**
* Main function to download and install prebuilds
*/
async function downloadPrebuilds() {
const arch = process.arch; // x64 or arm64
const electronAbi = getElectronAbi();
if (!electronAbi) {
console.log('[prebuilds] Could not determine Electron ABI version');
return { success: false, reason: 'unknown-abi' };
}
console.log(`[prebuilds] Looking for prebuilds: win32-${arch}, Electron ABI ${electronAbi}`);
// Check for prebuilds in GitHub releases
let release;
try {
release = await getLatestRelease();
} catch (err) {
console.log(`[prebuilds] Could not fetch releases: ${err.message}`);
return { success: false, reason: 'fetch-failed' };
}
if (!release) {
console.log('[prebuilds] No releases found');
return { success: false, reason: 'no-releases' };
}
const asset = findPrebuildAsset(release, arch, electronAbi);
if (!asset) {
console.log(`[prebuilds] No prebuild found for win32-${arch}-electron-${electronAbi}`);
console.log('[prebuilds] Available assets:', release.assets?.map((a) => a.name).join(', ') || 'none');
return { success: false, reason: 'no-matching-prebuild' };
}
console.log(`[prebuilds] Found prebuild: ${asset.name}`);
// Download the prebuild
const tempDir = path.join(__dirname, '..', '.prebuild-temp');
const zipPath = path.join(tempDir, asset.name);
const nodePtyDir = path.join(__dirname, '..', 'node_modules', 'node-pty');
const buildDir = path.join(nodePtyDir, 'build', 'Release');
try {
// Create temp directory
fs.mkdirSync(tempDir, { recursive: true });
console.log(`[prebuilds] Downloading ${asset.name}...`);
await downloadFile(asset.browser_download_url, zipPath);
console.log('[prebuilds] Extracting...');
extractZip(zipPath, tempDir);
// Find the extracted prebuild directory
const extractedDir = path.join(tempDir, 'prebuilds', `win32-${arch}-electron-${electronAbi}`);
if (!fs.existsSync(extractedDir)) {
throw new Error(`Extracted directory not found: ${extractedDir}`);
}
// Ensure build/Release directory exists
fs.mkdirSync(buildDir, { recursive: true });
// Copy files to node_modules/node-pty/build/Release
const files = fs.readdirSync(extractedDir);
for (const file of files) {
const src = path.join(extractedDir, file);
const dest = path.join(buildDir, file);
fs.copyFileSync(src, dest);
console.log(`[prebuilds] Installed: ${file}`);
}
// Cleanup temp directory
fs.rmSync(tempDir, { recursive: true, force: true });
console.log('[prebuilds] Successfully installed prebuilt binaries!');
return { success: true };
} catch (err) {
// Cleanup on error
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
}
console.log(`[prebuilds] Download/extract failed: ${err.message}`);
return { success: false, reason: 'install-failed', error: err.message };
}
}
// Export for use by postinstall
module.exports = { downloadPrebuilds, getElectronAbi };
// Run if called directly
if (require.main === module) {
downloadPrebuilds()
.then((result) => {
if (!result.success) {
process.exit(1);
}
})
.catch((err) => {
console.error('[prebuilds] Error:', err);
process.exit(1);
});
}
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env node
/**
* Post-install script for Auto Claude UI
*
* On Windows:
* 1. Try to download prebuilt node-pty binaries from GitHub releases
* 2. Fall back to electron-rebuild if prebuilds aren't available
* 3. Show helpful error message if compilation fails
*
* On macOS/Linux:
* 1. Run electron-rebuild (compilers are typically available)
*/
const { spawn } = require('child_process');
const os = require('os');
const path = require('path');
const fs = require('fs');
const isWindows = os.platform() === 'win32';
const WINDOWS_BUILD_TOOLS_HELP = `
================================================================================
VISUAL STUDIO BUILD TOOLS REQUIRED
================================================================================
Prebuilt binaries weren't available for your Electron version, and compilation
requires Visual Studio Build Tools.
To install:
1. Download Visual Studio Build Tools 2022:
https://visualstudio.microsoft.com/visual-cpp-build-tools/
2. Run installer and select:
- "Desktop development with C++" workload
3. In "Individual Components", also select:
- "MSVC v143 - VS 2022 C++ x64/x86 Spectre-mitigated libs"
4. Restart your terminal and run: npm install
================================================================================
`;
/**
* Run electron-rebuild
*/
function runElectronRebuild() {
return new Promise((resolve, reject) => {
const npx = isWindows ? 'npx.cmd' : 'npx';
const child = spawn(npx, ['electron-rebuild'], {
stdio: 'inherit',
shell: isWindows,
cwd: path.join(__dirname, '..'),
});
child.on('close', (code) => {
if (code === 0) {
resolve({ success: true });
} else {
reject(new Error(`electron-rebuild exited with code ${code}`));
}
});
child.on('error', reject);
});
}
/**
* Check if node-pty is already built
*/
function isNodePtyBuilt() {
const buildDir = path.join(__dirname, '..', 'node_modules', 'node-pty', 'build', 'Release');
if (!fs.existsSync(buildDir)) return false;
// Check for the main .node file
const files = fs.readdirSync(buildDir);
return files.some((f) => f.endsWith('.node'));
}
/**
* Main postinstall logic
*/
async function main() {
console.log('[postinstall] Setting up native modules for Electron...\n');
// If node-pty is already built (e.g., from a previous successful install), skip
if (isNodePtyBuilt()) {
console.log('[postinstall] Native modules already built, skipping rebuild.');
return;
}
if (isWindows) {
// On Windows, try prebuilds first
console.log('[postinstall] Windows detected - checking for prebuilt binaries...\n');
try {
// Dynamic import to handle case where the script doesn't exist yet
const { downloadPrebuilds } = require('./download-prebuilds.js');
const result = await downloadPrebuilds();
if (result.success) {
console.log('\n[postinstall] Successfully installed prebuilt binaries!');
console.log('[postinstall] No Visual Studio Build Tools required.\n');
return;
}
console.log(`\n[postinstall] Prebuilds not available (${result.reason})`);
console.log('[postinstall] Falling back to electron-rebuild...\n');
} catch (err) {
console.log('[postinstall] Could not check for prebuilds:', err.message);
console.log('[postinstall] Falling back to electron-rebuild...\n');
}
}
// Run electron-rebuild
try {
console.log('[postinstall] Running electron-rebuild...\n');
await runElectronRebuild();
console.log('\n[postinstall] Native modules built successfully!');
} catch (error) {
console.error('\n[postinstall] Failed to build native modules.\n');
if (isWindows) {
console.error(WINDOWS_BUILD_TOOLS_HELP);
} else {
console.error('Error:', error.message);
console.error('\nYou may need to install build tools for your platform:');
console.error(' macOS: xcode-select --install');
console.error(' Linux: sudo apt-get install build-essential\n');
}
process.exit(1);
}
}
main().catch((err) => {
console.error('[postinstall] Unexpected error:', err);
process.exit(1);
});
@@ -3,7 +3,6 @@
* Tests IPC messages flow between main and renderer
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
// Mock ipcRenderer for renderer-side tests
const mockIpcRenderer = {
@@ -285,7 +284,8 @@ describe('IPC Bridge Integration', () => {
const getAppVersion = electronAPI['getAppVersion'] as () => Promise<unknown>;
await getAppVersion();
expect(mockIpcRenderer.invoke).toHaveBeenCalledWith('app:version');
// getAppVersion now uses the app-update channel (from AppUpdateAPI which is spread last)
expect(mockIpcRenderer.invoke).toHaveBeenCalledWith('app-update:get-version');
});
});
});
@@ -29,6 +29,14 @@ vi.mock('child_process', () => ({
spawn: vi.fn(() => mockProcess)
}));
// Mock claude-profile-manager to bypass auth checks in tests
vi.mock('../../main/claude-profile-manager', () => ({
getClaudeProfileManager: () => ({
hasValidAuth: () => true,
getActiveProfile: () => ({ profileId: 'default', profileName: 'Default' })
})
}));
// Auto-claude source path (for getAutoBuildSourcePath to find)
const AUTO_CLAUDE_SOURCE = path.join(TEST_DIR, 'auto-claude-source');
@@ -39,12 +47,15 @@ function setupTestDirs(): void {
// Create auto-claude source directory that getAutoBuildSourcePath looks for
mkdirSync(AUTO_CLAUDE_SOURCE, { recursive: true });
// Create VERSION file (required by getAutoBuildSourcePath)
writeFileSync(path.join(AUTO_CLAUDE_SOURCE, 'VERSION'), '1.0.0');
// Create requirements.txt file (used as marker by getAutoBuildSourcePath)
writeFileSync(path.join(AUTO_CLAUDE_SOURCE, 'requirements.txt'), '# Mock requirements');
// Create mock spec_runner.py
// Create runners subdirectory (where spec_runner.py lives after restructure)
mkdirSync(path.join(AUTO_CLAUDE_SOURCE, 'runners'), { recursive: true });
// Create mock spec_runner.py in runners/ subdirectory
writeFileSync(
path.join(AUTO_CLAUDE_SOURCE, 'spec_runner.py'),
path.join(AUTO_CLAUDE_SOURCE, 'runners', 'spec_runner.py'),
'# Mock spec runner\nprint("Starting spec creation")'
);
// Create mock run.py
+1 -1
View File
@@ -12,7 +12,7 @@ export const TEST_DATA_DIR = '/tmp/auto-claude-ui-tests';
beforeEach(() => {
// Use a unique subdirectory per test to avoid race conditions in parallel tests
const testId = `test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const testDir = path.join(TEST_DATA_DIR, testId);
const _testDir = path.join(TEST_DATA_DIR, testId);
try {
if (existsSync(TEST_DATA_DIR)) {
@@ -11,6 +11,34 @@ import path from 'path';
const TEST_DIR = '/tmp/ipc-handlers-test';
const TEST_PROJECT_PATH = path.join(TEST_DIR, 'test-project');
// Mock electron-updater before importing
vi.mock('electron-updater', () => ({
autoUpdater: {
autoDownload: true,
autoInstallOnAppQuit: true,
on: vi.fn(),
checkForUpdates: vi.fn(() => Promise.resolve(null)),
downloadUpdate: vi.fn(() => Promise.resolve()),
quitAndInstall: vi.fn()
}
}));
// Mock @electron-toolkit/utils before importing
vi.mock('@electron-toolkit/utils', () => ({
is: {
dev: true,
windows: process.platform === 'win32',
macos: process.platform === 'darwin',
linux: process.platform === 'linux'
},
electronApp: {
setAppUserModelId: vi.fn()
},
optimizer: {
watchWindowShortcuts: vi.fn()
}
}));
// Mock modules before importing
vi.mock('electron', () => {
const mockIpcMain = new (class extends EventEmitter {
@@ -1,463 +0,0 @@
/**
* Unit tests for IPC handlers
* Tests all IPC communication patterns between main and renderer processes
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
import { mkdirSync, writeFileSync, rmSync, existsSync } from 'fs';
import path from 'path';
// Test data directory
const TEST_DIR = '/tmp/ipc-handlers-test';
const TEST_PROJECT_PATH = path.join(TEST_DIR, 'test-project');
// Mock modules before importing
vi.mock('electron', () => {
const mockIpcMain = new (class extends EventEmitter {
private handlers: Map<string, Function> = new Map();
handle(channel: string, handler: Function): void {
this.handlers.set(channel, handler);
}
removeHandler(channel: string): void {
this.handlers.delete(channel);
}
async invokeHandler(channel: string, event: unknown, ...args: unknown[]): Promise<unknown> {
const handler = this.handlers.get(channel);
if (handler) {
return handler(event, ...args);
}
throw new Error(`No handler for channel: ${channel}`);
}
getHandler(channel: string): Function | undefined {
return this.handlers.get(channel);
}
})();
return {
app: {
getPath: vi.fn((name: string) => {
if (name === 'userData') return path.join(TEST_DIR, 'userData');
return TEST_DIR;
}),
getVersion: vi.fn(() => '0.1.0'),
isPackaged: false
},
ipcMain: mockIpcMain,
dialog: {
showOpenDialog: vi.fn(() => Promise.resolve({ canceled: false, filePaths: [TEST_PROJECT_PATH] }))
},
BrowserWindow: class {
webContents = { send: vi.fn() };
}
};
});
// Setup test project structure
function setupTestProject(): void {
mkdirSync(TEST_PROJECT_PATH, { recursive: true });
mkdirSync(path.join(TEST_PROJECT_PATH, 'auto-claude', 'specs'), { recursive: true });
}
// Cleanup test directories
function cleanupTestDirs(): void {
if (existsSync(TEST_DIR)) {
rmSync(TEST_DIR, { recursive: true, force: true });
}
}
describe('IPC Handlers', () => {
let ipcMain: EventEmitter & {
handlers: Map<string, Function>;
invokeHandler: (channel: string, event: unknown, ...args: unknown[]) => Promise<unknown>;
getHandler: (channel: string) => Function | undefined;
};
let mockMainWindow: { webContents: { send: ReturnType<typeof vi.fn> } };
let mockAgentManager: EventEmitter & {
startSpecCreation: ReturnType<typeof vi.fn>;
startTaskExecution: ReturnType<typeof vi.fn>;
startQAProcess: ReturnType<typeof vi.fn>;
killTask: ReturnType<typeof vi.fn>;
configure: ReturnType<typeof vi.fn>;
};
let mockTerminalManager: {
create: ReturnType<typeof vi.fn>;
destroy: ReturnType<typeof vi.fn>;
write: ReturnType<typeof vi.fn>;
resize: ReturnType<typeof vi.fn>;
invokeClaude: ReturnType<typeof vi.fn>;
killAll: ReturnType<typeof vi.fn>;
};
beforeEach(async () => {
cleanupTestDirs();
setupTestProject();
mkdirSync(path.join(TEST_DIR, 'userData', 'store'), { recursive: true });
// Get mocked ipcMain
const electron = await import('electron');
ipcMain = electron.ipcMain as unknown as typeof ipcMain;
// Create mock window
mockMainWindow = {
webContents: { send: vi.fn() }
};
// Create mock agent manager
mockAgentManager = Object.assign(new EventEmitter(), {
startSpecCreation: vi.fn(),
startTaskExecution: vi.fn(),
startQAProcess: vi.fn(),
killTask: vi.fn(),
configure: vi.fn()
});
// Create mock terminal manager
mockTerminalManager = {
create: vi.fn(() => Promise.resolve({ success: true })),
destroy: vi.fn(() => Promise.resolve({ success: true })),
write: vi.fn(),
resize: vi.fn(),
invokeClaude: vi.fn(),
killAll: vi.fn(() => Promise.resolve())
};
// Need to reset modules to re-register handlers
vi.resetModules();
});
afterEach(() => {
cleanupTestDirs();
vi.clearAllMocks();
});
describe('project:add handler', () => {
it('should return error for non-existent path', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
const result = await ipcMain.invokeHandler('project:add', {}, '/nonexistent/path');
expect(result).toEqual({
success: false,
error: 'Directory does not exist'
});
});
it('should successfully add an existing project', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
const result = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
expect(result).toHaveProperty('success', true);
expect(result).toHaveProperty('data');
const data = (result as { data: { path: string; name: string } }).data;
expect(data.path).toBe(TEST_PROJECT_PATH);
expect(data.name).toBe('test-project');
});
it('should return existing project if already added', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
// Add project twice
const result1 = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
const result2 = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
const data1 = (result1 as { data: { id: string } }).data;
const data2 = (result2 as { data: { id: string } }).data;
expect(data1.id).toBe(data2.id);
});
});
describe('project:list handler', () => {
it('should return empty array when no projects', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
const result = await ipcMain.invokeHandler('project:list', {});
expect(result).toEqual({
success: true,
data: []
});
});
it('should return all added projects', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
// Add a project
await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
const result = await ipcMain.invokeHandler('project:list', {});
expect(result).toHaveProperty('success', true);
const data = (result as { data: unknown[] }).data;
expect(data).toHaveLength(1);
});
});
describe('project:remove handler', () => {
it('should return false for non-existent project', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
const result = await ipcMain.invokeHandler('project:remove', {}, 'nonexistent-id');
expect(result).toEqual({ success: false });
});
it('should successfully remove an existing project', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
// Add a project first
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
const projectId = (addResult as { data: { id: string } }).data.id;
// Remove it
const removeResult = await ipcMain.invokeHandler('project:remove', {}, projectId);
expect(removeResult).toEqual({ success: true });
// Verify it's gone
const listResult = await ipcMain.invokeHandler('project:list', {});
const data = (listResult as { data: unknown[] }).data;
expect(data).toHaveLength(0);
});
});
describe('project:updateSettings handler', () => {
it('should return error for non-existent project', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
const result = await ipcMain.invokeHandler(
'project:updateSettings',
{},
'nonexistent-id',
{ parallelEnabled: true }
);
expect(result).toEqual({
success: false,
error: 'Project not found'
});
});
it('should successfully update project settings', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
// Add a project first
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
const projectId = (addResult as { data: { id: string } }).data.id;
// Update settings
const result = await ipcMain.invokeHandler(
'project:updateSettings',
{},
projectId,
{ parallelEnabled: true, maxWorkers: 4 }
);
expect(result).toEqual({ success: true });
});
});
describe('task:list handler', () => {
it('should return empty array for project with no specs', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
// Add a project first
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
const projectId = (addResult as { data: { id: string } }).data.id;
const result = await ipcMain.invokeHandler('task:list', {}, projectId);
expect(result).toEqual({
success: true,
data: []
});
});
it('should return tasks when specs exist', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
// Add a project first
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
const projectId = (addResult as { data: { id: string } }).data.id;
// Create a spec directory with implementation plan
const specDir = path.join(TEST_PROJECT_PATH, 'auto-claude', 'specs', '001-test-feature');
mkdirSync(specDir, { recursive: true });
writeFileSync(path.join(specDir, 'implementation_plan.json'), JSON.stringify({
feature: 'Test Feature',
workflow_type: 'feature',
services_involved: [],
phases: [{
phase: 1,
name: 'Test Phase',
type: 'implementation',
subtasks: [{ id: 'subtask-1', description: 'Test subtask', status: 'pending' }]
}],
final_acceptance: [],
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
spec_file: ''
}));
const result = await ipcMain.invokeHandler('task:list', {}, projectId);
expect(result).toHaveProperty('success', true);
const data = (result as { data: unknown[] }).data;
expect(data).toHaveLength(1);
});
});
describe('task:create handler', () => {
it('should return error for non-existent project', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
const result = await ipcMain.invokeHandler(
'task:create',
{},
'nonexistent-id',
'Test Task',
'Test description'
);
expect(result).toEqual({
success: false,
error: 'Project not found'
});
});
it('should create task and start spec creation', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
// Add a project first
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
const projectId = (addResult as { data: { id: string } }).data.id;
const result = await ipcMain.invokeHandler(
'task:create',
{},
projectId,
'Test Task',
'Test description'
);
expect(result).toHaveProperty('success', true);
expect(mockAgentManager.startSpecCreation).toHaveBeenCalled();
});
});
describe('settings:get handler', () => {
it('should return default settings when no settings file exists', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
const result = await ipcMain.invokeHandler('settings:get', {});
expect(result).toHaveProperty('success', true);
const data = (result as { data: { theme: string } }).data;
expect(data).toHaveProperty('theme', 'system');
});
});
describe('settings:save handler', () => {
it('should save settings successfully', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
const result = await ipcMain.invokeHandler(
'settings:save',
{},
{ theme: 'dark', defaultModel: 'opus' }
);
expect(result).toEqual({ success: true });
// Verify settings were saved
const getResult = await ipcMain.invokeHandler('settings:get', {});
const data = (getResult as { data: { theme: string; defaultModel: string } }).data;
expect(data.theme).toBe('dark');
expect(data.defaultModel).toBe('opus');
});
it('should configure agent manager when paths change', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
await ipcMain.invokeHandler(
'settings:save',
{},
{ pythonPath: '/usr/bin/python3' }
);
expect(mockAgentManager.configure).toHaveBeenCalledWith('/usr/bin/python3', undefined);
});
});
describe('app:version handler', () => {
it('should return app version', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
const result = await ipcMain.invokeHandler('app:version', {});
expect(result).toBe('0.1.0');
});
});
describe('Agent Manager event forwarding', () => {
it('should forward log events to renderer', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
mockAgentManager.emit('log', 'task-1', 'Test log message');
expect(mockMainWindow.webContents.send).toHaveBeenCalledWith(
'task:log',
'task-1',
'Test log message'
);
});
it('should forward error events to renderer', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
mockAgentManager.emit('error', 'task-1', 'Test error message');
expect(mockMainWindow.webContents.send).toHaveBeenCalledWith(
'task:error',
'task-1',
'Test error message'
);
});
it('should forward exit events with status change', async () => {
const { setupIpcHandlers } = await import('../ipc-handlers');
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
mockAgentManager.emit('exit', 'task-1', 0);
expect(mockMainWindow.webContents.send).toHaveBeenCalledWith(
'task:statusChange',
'task-1',
'ai_review'
);
});
});
});
@@ -0,0 +1,560 @@
/**
* Unit tests for rate limit and auth failure detection
* Tests detection patterns for rate limiting and authentication failures
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// Mock the claude-profile-manager before importing
vi.mock('../claude-profile-manager', () => ({
getClaudeProfileManager: vi.fn(() => ({
getActiveProfile: vi.fn(() => ({
id: 'test-profile-id',
name: 'Test Profile',
isDefault: true
})),
getProfile: vi.fn((id: string) => ({
id,
name: 'Test Profile',
isDefault: true
})),
getBestAvailableProfile: vi.fn(() => null),
recordRateLimitEvent: vi.fn()
}))
}));
describe('Rate Limit Detector', () => {
beforeEach(() => {
vi.resetModules();
});
afterEach(() => {
vi.clearAllMocks();
});
describe('detectRateLimit', () => {
it('should detect rate limit with reset time', async () => {
const { detectRateLimit } = await import('../rate-limit-detector');
const output = 'Limit reached · resets Dec 17 at 6am (Europe/Oslo)';
const result = detectRateLimit(output);
expect(result.isRateLimited).toBe(true);
expect(result.resetTime).toBe('Dec 17 at 6am (Europe/Oslo)');
expect(result.limitType).toBe('weekly');
});
it('should detect rate limit with bullet character', async () => {
const { detectRateLimit } = await import('../rate-limit-detector');
const output = 'Limit reached • resets 11:59pm';
const result = detectRateLimit(output);
expect(result.isRateLimited).toBe(true);
expect(result.resetTime).toBe('11:59pm');
expect(result.limitType).toBe('session');
});
it('should detect secondary rate limit indicators', async () => {
const { detectRateLimit } = await import('../rate-limit-detector');
const testCases = [
'rate limit exceeded',
'usage limit reached',
'You have exceeded your limit',
'too many requests'
];
for (const output of testCases) {
const result = detectRateLimit(output);
expect(result.isRateLimited).toBe(true);
}
});
it('should return false for non-rate-limit output', async () => {
const { detectRateLimit } = await import('../rate-limit-detector');
const output = 'Task completed successfully';
const result = detectRateLimit(output);
expect(result.isRateLimited).toBe(false);
});
it('should return false for empty output', async () => {
const { detectRateLimit } = await import('../rate-limit-detector');
const result = detectRateLimit('');
expect(result.isRateLimited).toBe(false);
});
});
describe('isRateLimitError', () => {
it('should return true for rate limit errors', async () => {
const { isRateLimitError } = await import('../rate-limit-detector');
expect(isRateLimitError('Limit reached · resets Dec 17 at 6am')).toBe(true);
expect(isRateLimitError('rate limit exceeded')).toBe(true);
});
it('should return false for non-rate-limit errors', async () => {
const { isRateLimitError } = await import('../rate-limit-detector');
expect(isRateLimitError('authentication required')).toBe(false);
expect(isRateLimitError('Task completed')).toBe(false);
});
});
describe('extractResetTime', () => {
it('should extract reset time from rate limit message', async () => {
const { extractResetTime } = await import('../rate-limit-detector');
const output = 'Limit reached · resets Dec 17 at 6am (Europe/Oslo)';
const resetTime = extractResetTime(output);
expect(resetTime).toBe('Dec 17 at 6am (Europe/Oslo)');
});
it('should return null for non-rate-limit output', async () => {
const { extractResetTime } = await import('../rate-limit-detector');
const output = 'Task completed successfully';
const resetTime = extractResetTime(output);
expect(resetTime).toBeNull();
});
});
});
describe('Auth Failure Detection', () => {
beforeEach(() => {
vi.resetModules();
});
afterEach(() => {
vi.clearAllMocks();
});
describe('detectAuthFailure', () => {
it('should detect "authentication required" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Error: authentication required';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('missing');
expect(result.message).toContain('authentication required');
});
it('should detect "authentication is required" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Authentication is required to proceed';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('missing');
});
it('should detect "not authenticated" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Error: not authenticated';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('missing');
});
it('should detect "not yet authenticated" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'You are not yet authenticated';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('missing');
});
it('should detect "login required" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Login required';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('missing');
});
it('should detect "oauth token invalid" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'OAuth token is invalid';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('invalid');
});
it('should detect "oauth token expired" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'OAuth token expired';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('expired');
});
it('should detect "oauth token missing" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'OAuth token missing';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('missing');
});
it('should detect "unauthorized" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Error: Unauthorized';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('invalid');
});
it('should detect "please log in" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Please log in to continue';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
// "please log in" doesn't contain 'required' keyword, so classified as 'unknown'
expect(result.failureType).toBeDefined();
});
it('should detect "please authenticate" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Please authenticate before proceeding';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
// "please authenticate" doesn't contain 'required' keyword, so classified as 'unknown'
expect(result.failureType).toBeDefined();
});
it('should detect "invalid credentials" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Invalid credentials provided';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('invalid');
});
it('should detect "invalid token" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Invalid token';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('invalid');
});
it('should detect "auth failed" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Auth failed';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
});
it('should detect "authentication error" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Authentication error occurred';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
});
it('should detect "session expired" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Your session expired';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('expired');
});
it('should detect "access denied" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Access denied';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('invalid');
});
it('should detect "permission denied" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Permission denied';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('invalid');
});
it('should detect "401 unauthorized" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'HTTP 401 Unauthorized';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('invalid');
});
it('should detect "credentials missing" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Credentials are missing';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('missing');
});
it('should detect "credentials expired" pattern', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Credentials expired';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.failureType).toBe('expired');
});
it('should return false for rate limit errors (not auth failure)', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Limit reached · resets Dec 17 at 6am';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(false);
});
it('should return false for normal output', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Task completed successfully';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(false);
});
it('should return false for empty output', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const result = detectAuthFailure('');
expect(result.isAuthFailure).toBe(false);
});
it('should include profile ID in result', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const result = detectAuthFailure('authentication required', 'custom-profile');
expect(result.isAuthFailure).toBe(true);
expect(result.profileId).toBe('custom-profile');
});
it('should use active profile ID when not specified', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const result = detectAuthFailure('authentication required');
expect(result.isAuthFailure).toBe(true);
expect(result.profileId).toBe('test-profile-id');
});
it('should include original error in result', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = 'Error: authentication required for this action';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
expect(result.originalError).toBe(output);
});
it('should provide user-friendly message for missing auth', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const result = detectAuthFailure('authentication required');
expect(result.isAuthFailure).toBe(true);
expect(result.message).toContain('Settings');
expect(result.message).toContain('Claude Profiles');
});
it('should provide user-friendly message for expired auth', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const result = detectAuthFailure('session expired');
expect(result.isAuthFailure).toBe(true);
expect(result.message).toContain('expired');
expect(result.message).toContain('re-authenticate');
});
it('should provide user-friendly message for invalid auth', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const result = detectAuthFailure('unauthorized');
expect(result.isAuthFailure).toBe(true);
expect(result.message).toContain('Invalid');
});
});
describe('isAuthFailureError', () => {
it('should return true for auth failure errors', async () => {
const { isAuthFailureError } = await import('../rate-limit-detector');
expect(isAuthFailureError('authentication required')).toBe(true);
expect(isAuthFailureError('not authenticated')).toBe(true);
expect(isAuthFailureError('unauthorized')).toBe(true);
expect(isAuthFailureError('invalid token')).toBe(true);
});
it('should return false for non-auth-failure errors', async () => {
const { isAuthFailureError } = await import('../rate-limit-detector');
expect(isAuthFailureError('Limit reached · resets Dec 17')).toBe(false);
expect(isAuthFailureError('Task completed')).toBe(false);
expect(isAuthFailureError('')).toBe(false);
});
});
describe('auth failure does not match rate limit patterns', () => {
it('should not detect auth failure as rate limit', async () => {
const { detectRateLimit } = await import('../rate-limit-detector');
const authErrors = [
'authentication required',
'not authenticated',
'unauthorized',
'invalid token',
'session expired',
'please log in'
];
for (const error of authErrors) {
const result = detectRateLimit(error);
expect(result.isRateLimited).toBe(false);
}
});
it('should not detect rate limit as auth failure', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const rateLimitErrors = [
'Limit reached · resets Dec 17 at 6am',
'rate limit exceeded',
'too many requests',
'usage limit reached'
];
for (const error of rateLimitErrors) {
const result = detectAuthFailure(error);
expect(result.isAuthFailure).toBe(false);
}
});
});
describe('edge cases', () => {
it('should handle multiline output with auth failure', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = `Starting task...
Processing...
Error: authentication required
Please authenticate and try again.`;
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
});
it('should handle case-insensitive matching', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const testCases = [
'AUTHENTICATION REQUIRED',
'Authentication Required',
'UNAUTHORIZED',
'Unauthorized',
'NOT AUTHENTICATED',
'Not Authenticated'
];
for (const output of testCases) {
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
}
});
it('should handle partial matches correctly', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
// Should NOT match - word is part of a different context
const falsePositives = [
'The authenticated user can proceed', // has 'authenticated' but not an error
'Authorization header set correctly' // different word
];
// Note: Some false positives may still match due to pattern design
// The patterns are intentionally broad to catch errors
for (const output of falsePositives) {
const result = detectAuthFailure(output);
// Just verify it runs without error - actual match depends on pattern design
expect(typeof result.isAuthFailure).toBe('boolean');
}
});
it('should handle JSON error responses', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = '{"error": "unauthorized", "message": "Please authenticate"}';
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
});
it('should handle error stack traces with auth failure', async () => {
const { detectAuthFailure } = await import('../rate-limit-detector');
const output = `Error: authentication required
at validateToken (/app/auth.js:42)
at processRequest (/app/handler.js:15)
at main (/app/index.js:8)`;
const result = detectAuthFailure(output);
expect(result.isAuthFailure).toBe(true);
});
});
});
+46 -14
View File
@@ -5,10 +5,8 @@ import { AgentState } from './agent-state';
import { AgentEvents } from './agent-events';
import { AgentProcessManager } from './agent-process';
import { AgentQueueManager } from './agent-queue';
import { getClaudeProfileManager } from '../claude-profile-manager';
import {
AgentManagerEvents,
ExecutionProgressData,
ProcessType,
SpecCreationMetadata,
TaskExecutionOptions,
IdeationConfig
@@ -44,8 +42,7 @@ export class AgentManager extends EventEmitter {
this.queueManager = new AgentQueueManager(this.state, this.events, this.processManager, this);
// Listen for auto-swap restart events
this.on('auto-swap-restart-task', (taskId: string, newProfileId: string) => {
console.log('[AgentManager] Auto-swap restart:', taskId, newProfileId);
this.on('auto-swap-restart-task', (taskId: string, _newProfileId: string) => {
this.restartTask(taskId);
});
@@ -64,14 +61,12 @@ export class AgentManager extends EventEmitter {
// If task completed successfully, always clean up
if (code === 0) {
this.taskExecutionContext.delete(taskId);
console.log('[AgentManager] Cleaned up context for completed task:', taskId);
return;
}
// If task failed and hit max retries, clean up
if (context.swapCount >= 2) {
this.taskExecutionContext.delete(taskId);
console.log('[AgentManager] Cleaned up context for max-retry task:', taskId);
}
// Otherwise keep context for potential restart
}, 1000); // Delay to allow restart logic to run first
@@ -95,6 +90,13 @@ export class AgentManager extends EventEmitter {
specDir?: string,
metadata?: SpecCreationMetadata
): void {
// Pre-flight auth check: Verify active profile has valid authentication
const profileManager = getClaudeProfileManager();
if (!profileManager.hasValidAuth()) {
this.emit('error', taskId, 'Claude authentication required. Please authenticate in Settings > Claude Profiles before starting tasks.');
return;
}
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
if (!autoBuildSource) {
@@ -102,7 +104,7 @@ export class AgentManager extends EventEmitter {
return;
}
const specRunnerPath = path.join(autoBuildSource, 'spec_runner.py');
const specRunnerPath = path.join(autoBuildSource, 'runners', 'spec_runner.py');
if (!existsSync(specRunnerPath)) {
this.emit('error', taskId, `Spec runner not found at: ${specRunnerPath}`);
@@ -126,6 +128,20 @@ export class AgentManager extends EventEmitter {
args.push('--auto-approve');
}
// Pass model and thinking level configuration
// For auto profile, use phase-specific config; otherwise use single model/thinking
if (metadata?.isAutoProfile && metadata.phaseModels && metadata.phaseThinking) {
// Pass the spec phase model and thinking level to spec_runner
args.push('--model', metadata.phaseModels.spec);
args.push('--thinking-level', metadata.phaseThinking.spec);
} else if (metadata?.model) {
// Non-auto profile: use single model and thinking level
args.push('--model', metadata.model);
if (metadata.thinkingLevel) {
args.push('--thinking-level', metadata.thinkingLevel);
}
}
// Store context for potential restart
this.storeTaskContext(taskId, projectPath, '', {}, true, taskDescription, specDir, metadata);
@@ -142,21 +158,23 @@ export class AgentManager extends EventEmitter {
specId: string,
options: TaskExecutionOptions = {}
): void {
console.log('[AgentManager] startTaskExecution called for:', taskId, specId);
// Pre-flight auth check: Verify active profile has valid authentication
const profileManager = getClaudeProfileManager();
if (!profileManager.hasValidAuth()) {
this.emit('error', taskId, 'Claude authentication required. Please authenticate in Settings > Claude Profiles before starting tasks.');
return;
}
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
if (!autoBuildSource) {
console.log('[AgentManager] ERROR: Auto-build source path not found');
this.emit('error', taskId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const runPath = path.join(autoBuildSource, 'run.py');
console.log('[AgentManager] runPath:', runPath);
if (!existsSync(runPath)) {
console.log('[AgentManager] ERROR: Run script not found at:', runPath);
this.emit('error', taskId, `Run script not found at: ${runPath}`);
return;
}
@@ -179,11 +197,12 @@ export class AgentManager extends EventEmitter {
// Note: --parallel was removed from run.py CLI - parallel execution is handled internally by the agent
// The options.parallel and options.workers are kept for future use or logging purposes
// Note: Model configuration is read from task_metadata.json by the Python scripts,
// which allows per-phase configuration for planner, coder, and QA phases
// Store context for potential restart
this.storeTaskContext(taskId, projectPath, specId, options, false);
console.log('[AgentManager] Spawning process with args:', args);
this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution');
}
@@ -262,6 +281,20 @@ export class AgentManager extends EventEmitter {
return this.queueManager.isIdeationRunning(projectId);
}
/**
* Stop roadmap generation for a project
*/
stopRoadmap(projectId: string): boolean {
return this.queueManager.stopRoadmap(projectId);
}
/**
* Check if roadmap is running for a project
*/
isRoadmapRunning(projectId: string): boolean {
return this.queueManager.isRoadmapRunning(projectId);
}
/**
* Kill all running processes
*/
@@ -329,7 +362,6 @@ export class AgentManager extends EventEmitter {
}
context.swapCount++;
console.log('[AgentManager] Restarting task:', taskId, 'swap count:', context.swapCount);
// Kill current process
this.killTask(taskId);
+37 -36
View File
@@ -1,4 +1,4 @@
import { spawn, ChildProcess } from 'child_process';
import { spawn } from 'child_process';
import path from 'path';
import { existsSync, readFileSync } from 'fs';
import { app } from 'electron';
@@ -6,9 +6,10 @@ import { EventEmitter } from 'events';
import { AgentState } from './agent-state';
import { AgentEvents } from './agent-events';
import { ProcessType, ExecutionProgressData } from './types';
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from '../rate-limit-detector';
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv, detectAuthFailure } from '../rate-limit-detector';
import { projectStore } from '../project-store';
import { getClaudeProfileManager } from '../claude-profile-manager';
import { findPythonCommand, parsePythonCommand } from '../python-detector';
/**
* Process spawning and lifecycle management
@@ -17,7 +18,8 @@ export class AgentProcessManager {
private state: AgentState;
private events: AgentEvents;
private emitter: EventEmitter;
private pythonPath: string = 'python3';
// Auto-detect Python command on initialization
private pythonPath: string = findPythonCommand() || 'python';
private autoBuildSourcePath: string = '';
constructor(state: AgentState, events: AgentEvents, emitter: EventEmitter) {
@@ -65,7 +67,8 @@ export class AgentProcessManager {
];
for (const p of possiblePaths) {
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
// Use requirements.txt as marker - it always exists in auto-claude source
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
return p;
}
}
@@ -99,14 +102,11 @@ export class AgentProcessManager {
loadAutoBuildEnv(): Record<string, string> {
const autoBuildSource = this.getAutoBuildSourcePath();
if (!autoBuildSource) {
console.log('[loadAutoBuildEnv] No auto-build source path found');
return {};
}
const envPath = path.join(autoBuildSource, '.env');
console.log('[loadAutoBuildEnv] Looking for .env at:', envPath);
if (!existsSync(envPath)) {
console.log('[loadAutoBuildEnv] .env file does not exist');
return {};
}
@@ -160,26 +160,23 @@ export class AgentProcessManager {
// Generate unique spawn ID for this process instance
const spawnId = this.state.generateSpawnId();
console.log('[spawnProcess] Spawning with pythonPath:', this.pythonPath);
console.log('[spawnProcess] cwd:', cwd);
console.log('[spawnProcess] processType:', processType);
console.log('[spawnProcess] spawnId:', spawnId);
// Get active Claude profile environment (CLAUDE_CONFIG_DIR if not default)
const profileEnv = getProfileEnv();
const childProcess = spawn(this.pythonPath, args, {
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.pythonPath);
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, ...args], {
cwd,
env: {
...process.env,
...extraEnv,
...profileEnv, // Include active Claude profile config
PYTHONUNBUFFERED: '1' // Ensure real-time output
PYTHONUNBUFFERED: '1', // Ensure real-time output
PYTHONIOENCODING: 'utf-8', // Ensure UTF-8 encoding on Windows
PYTHONUTF8: '1' // Force Python UTF-8 mode on Windows (Python 3.7+)
}
});
console.log('[spawnProcess] Process spawned, pid:', childProcess.pid);
this.state.addProcess(taskId, {
taskId,
process: childProcess,
@@ -239,33 +236,37 @@ export class AgentProcessManager {
}
};
// Handle stdout
// Handle stdout - explicitly decode as UTF-8 for cross-platform Unicode support
childProcess.stdout?.on('data', (data: Buffer) => {
const log = data.toString();
console.log('[spawnProcess] stdout:', log.substring(0, 200));
const log = data.toString('utf8');
this.emitter.emit('log', taskId, log);
processLog(log);
// Print to console when DEBUG is enabled (visible in pnpm dev terminal)
if (['true', '1', 'yes', 'on'].includes(process.env.DEBUG?.toLowerCase() ?? '')) {
console.log(`[Agent:${taskId}] ${log.trim()}`);
}
});
// Handle stderr
// Handle stderr - explicitly decode as UTF-8 for cross-platform Unicode support
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString();
console.log('[spawnProcess] stderr:', log.substring(0, 200));
const log = data.toString('utf8');
// Some Python output goes to stderr (like progress bars)
// so we treat it as log, not error
this.emitter.emit('log', taskId, log);
processLog(log);
// Print to console when DEBUG is enabled (visible in pnpm dev terminal)
if (['true', '1', 'yes', 'on'].includes(process.env.DEBUG?.toLowerCase() ?? '')) {
console.log(`[Agent:${taskId}] ${log.trim()}`);
}
});
// Handle process exit
childProcess.on('exit', (code: number | null) => {
console.log('[spawnProcess] Process exited with code:', code, 'spawnId:', spawnId);
this.state.deleteProcess(taskId);
// Check if this specific spawn was killed (vs exited naturally)
// If killed, don't emit exit event to prevent race condition with new process
if (this.state.wasSpawnKilled(spawnId)) {
console.log('[spawnProcess] Process was killed, skipping exit event for spawnId:', spawnId);
this.state.clearKilledSpawn(spawnId);
return;
}
@@ -274,26 +275,15 @@ export class AgentProcessManager {
if (code !== 0) {
const rateLimitDetection = detectRateLimit(allOutput);
if (rateLimitDetection.isRateLimited) {
console.log('[spawnProcess] Rate limit detected in task output:', {
taskId,
resetTime: rateLimitDetection.resetTime,
limitType: rateLimitDetection.limitType,
suggestedProfile: rateLimitDetection.suggestedProfile?.name
});
// Check if auto-swap is enabled
const profileManager = getClaudeProfileManager();
const autoSwitchSettings = profileManager.getAutoSwitchSettings();
if (autoSwitchSettings.enabled && autoSwitchSettings.autoSwitchOnRateLimit) {
console.log('[spawnProcess] Reactive auto-swap enabled');
const currentProfileId = rateLimitDetection.profileId;
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
if (bestProfile) {
console.log('[spawnProcess] Reactive swap to:', bestProfile.name);
// Switch active profile
profileManager.setActiveProfile(bestProfile.id);
@@ -322,6 +312,17 @@ export class AgentProcessManager {
taskId
});
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
} else {
// Not rate limited - check for authentication failure
const authFailureDetection = detectAuthFailure(allOutput);
if (authFailureDetection.isAuthFailure) {
this.emitter.emit('auth-failure', taskId, {
profileId: authFailureDetection.profileId,
failureType: authFailureDetection.failureType,
message: authFailureDetection.message,
originalError: authFailureDetection.originalError
});
}
}
}
@@ -339,7 +340,7 @@ export class AgentProcessManager {
// Handle process error
childProcess.on('error', (err: Error) => {
console.log('[spawnProcess] Process error:', err.message);
console.error('[AgentProcess] Process error:', err.message);
this.state.deleteProcess(taskId);
this.emitter.emit('execution-progress', taskId, {
+186 -49
View File
@@ -7,6 +7,8 @@ import { AgentEvents } from './agent-events';
import { AgentProcessManager } from './agent-process';
import { IdeationConfig } from './types';
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from '../rate-limit-detector';
import { debugLog, debugError } from '../../shared/utils/debug-logger';
import { parsePythonCommand } from '../python-detector';
/**
* Queue management for ideation and roadmap generation
@@ -38,16 +40,25 @@ export class AgentQueueManager {
refresh: boolean = false,
enableCompetitorAnalysis: boolean = false
): void {
debugLog('[Agent Queue] Starting roadmap generation:', {
projectId,
projectPath,
refresh,
enableCompetitorAnalysis
});
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
if (!autoBuildSource) {
debugError('[Agent Queue] Auto-build source path not found');
this.emitter.emit('roadmap-error', projectId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const roadmapRunnerPath = path.join(autoBuildSource, 'roadmap_runner.py');
const roadmapRunnerPath = path.join(autoBuildSource, 'runners', 'roadmap_runner.py');
if (!existsSync(roadmapRunnerPath)) {
debugError('[Agent Queue] Roadmap runner not found at:', roadmapRunnerPath);
this.emitter.emit('roadmap-error', projectId, `Roadmap runner not found at: ${roadmapRunnerPath}`);
return;
}
@@ -63,6 +74,8 @@ export class AgentQueueManager {
args.push('--competitor-analysis');
}
debugLog('[Agent Queue] Spawning roadmap process with args:', args);
// Use projectId as taskId for roadmap operations
this.spawnRoadmapProcess(projectId, projectPath, args);
}
@@ -76,16 +89,25 @@ export class AgentQueueManager {
config: IdeationConfig,
refresh: boolean = false
): void {
debugLog('[Agent Queue] Starting ideation generation:', {
projectId,
projectPath,
config,
refresh
});
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
if (!autoBuildSource) {
debugError('[Agent Queue] Auto-build source path not found');
this.emitter.emit('ideation-error', projectId, 'Auto-build source path not found. Please configure it in App Settings.');
return;
}
const ideationRunnerPath = path.join(autoBuildSource, 'ideation_runner.py');
const ideationRunnerPath = path.join(autoBuildSource, 'runners', 'ideation_runner.py');
if (!existsSync(ideationRunnerPath)) {
debugError('[Agent Queue] Ideation runner not found at:', ideationRunnerPath);
this.emitter.emit('ideation-error', projectId, `Ideation runner not found at: ${ideationRunnerPath}`);
return;
}
@@ -119,6 +141,8 @@ export class AgentQueueManager {
args.push('--append');
}
debugLog('[Agent Queue] Spawning ideation process with args:', args);
// Use projectId as taskId for ideation operations
this.spawnIdeationProcess(projectId, projectPath, args);
}
@@ -131,11 +155,17 @@ export class AgentQueueManager {
projectPath: string,
args: string[]
): void {
debugLog('[Agent Queue] Spawning ideation process:', { projectId, projectPath });
// Kill existing process for this project if any
this.processManager.killProcess(projectId);
const wasKilled = this.processManager.killProcess(projectId);
if (wasKilled) {
debugLog('[Agent Queue] Killed existing process for project:', projectId);
}
// Generate unique spawn ID for this process instance
const spawnId = this.state.generateSpawnId();
debugLog('[Agent Queue] Generated spawn ID:', spawnId);
// Run from auto-claude source directory so imports work correctly
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
@@ -144,20 +174,44 @@ export class AgentQueueManager {
// Get combined environment variables
const combinedEnv = this.processManager.getCombinedEnv(projectPath);
// Get active Claude profile environment (CLAUDE_CONFIG_DIR if not default)
// Get active Claude profile environment (CLAUDE_CODE_OAUTH_TOKEN if not default)
const profileEnv = getProfileEnv();
// Get Python path from process manager (uses venv if configured)
const pythonPath = this.processManager.getPythonPath();
const childProcess = spawn(pythonPath, args, {
// Build final environment with proper precedence:
// 1. process.env (system)
// 2. combinedEnv (auto-claude/.env for CLI usage)
// 3. profileEnv (Electron app OAuth token - highest priority)
// 4. Our specific overrides
const finalEnv = {
...process.env,
...combinedEnv,
...profileEnv,
PYTHONPATH: autoBuildSource || '', // Allow imports from auto-claude directory
PYTHONUNBUFFERED: '1',
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
};
// Debug: Show OAuth token source
const tokenSource = profileEnv['CLAUDE_CODE_OAUTH_TOKEN']
? 'Electron app profile'
: (combinedEnv['CLAUDE_CODE_OAUTH_TOKEN'] ? 'auto-claude/.env' : 'not found');
const oauthToken = (finalEnv as Record<string, string | undefined>)['CLAUDE_CODE_OAUTH_TOKEN'];
const hasToken = !!oauthToken;
debugLog('[Agent Queue] OAuth token status:', {
source: tokenSource,
hasToken,
tokenPreview: hasToken ? oauthToken?.substring(0, 20) + '...' : 'none'
});
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(pythonPath);
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, ...args], {
cwd,
env: {
...process.env,
...combinedEnv,
...profileEnv,
PYTHONUNBUFFERED: '1'
}
env: finalEnv
});
this.state.addProcess(projectId, {
@@ -165,7 +219,8 @@ export class AgentQueueManager {
process: childProcess,
startedAt: new Date(),
projectPath, // Store project path for loading session on completion
spawnId
spawnId,
queueProcessType: 'ideation'
});
// Track progress through output
@@ -180,22 +235,18 @@ export class AgentQueueManager {
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length > 0) {
console.log('[Ideation]', trimmed);
this.emitter.emit('ideation-log', projectId, trimmed);
}
}
};
console.log('[Ideation] Starting ideation process with args:', args);
console.log('[Ideation] CWD:', cwd);
// Track completed types for progress calculation
const completedTypes = new Set<string>();
const totalTypes = 7; // Default all types
// Handle stdout
// Handle stdout - explicitly decode as UTF-8 for cross-platform Unicode support
childProcess.stdout?.on('data', (data: Buffer) => {
const log = data.toString();
const log = data.toString('utf8');
// Collect output for rate limit detection (keep last 10KB)
allOutput = (allOutput + log).slice(-10000);
@@ -207,7 +258,13 @@ export class AgentQueueManager {
if (typeCompleteMatch) {
const [, ideationType, ideasCount] = typeCompleteMatch;
completedTypes.add(ideationType);
console.log(`[Ideation] Type complete: ${ideationType} with ${ideasCount} ideas`);
debugLog('[Agent Queue] Ideation type completed:', {
projectId,
ideationType,
ideasCount: parseInt(ideasCount, 10),
totalCompleted: completedTypes.size
});
// Emit event for UI to load this type's ideas immediately
this.emitter.emit('ideation-type-complete', projectId, ideationType, parseInt(ideasCount, 10));
@@ -217,7 +274,8 @@ export class AgentQueueManager {
if (typeFailedMatch) {
const [, ideationType] = typeFailedMatch;
completedTypes.add(ideationType);
console.log(`[Ideation] Type failed: ${ideationType}`);
debugError('[Agent Queue] Ideation type failed:', { projectId, ideationType });
this.emitter.emit('ideation-type-failed', projectId, ideationType);
}
@@ -242,9 +300,9 @@ export class AgentQueueManager {
});
});
// Handle stderr - also emit as logs
// Handle stderr - also emit as logs, explicitly decode as UTF-8
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString();
const log = data.toString('utf8');
// Collect stderr for rate limit detection too
allOutput = (allOutput + log).slice(-10000);
console.error('[Ideation STDERR]', log);
@@ -258,7 +316,7 @@ export class AgentQueueManager {
// Handle process exit
childProcess.on('exit', (code: number | null) => {
console.log('[Ideation] Process exited with code:', code);
debugLog('[Agent Queue] Ideation process exited:', { projectId, code, spawnId });
// Get the stored project path before deleting from map
const processInfo = this.state.getProcess(projectId);
@@ -267,8 +325,10 @@ export class AgentQueueManager {
// Check for rate limit if process failed
if (code !== 0) {
debugLog('[Agent Queue] Checking for rate limit (non-zero exit)');
const rateLimitDetection = detectRateLimit(allOutput);
if (rateLimitDetection.isRateLimited) {
debugLog('[Agent Queue] Rate limit detected for ideation');
const rateLimitInfo = createSDKRateLimitInfo('ideation', rateLimitDetection, {
projectId
});
@@ -277,6 +337,7 @@ export class AgentQueueManager {
}
if (code === 0) {
debugLog('[Agent Queue] Ideation generation completed successfully');
this.emitter.emit('ideation-progress', projectId, {
phase: 'complete',
progress: 100,
@@ -292,19 +353,25 @@ export class AgentQueueManager {
'ideation',
'ideation.json'
);
debugLog('[Agent Queue] Loading ideation session from:', ideationFilePath);
if (existsSync(ideationFilePath)) {
const content = readFileSync(ideationFilePath, 'utf-8');
const session = JSON.parse(content);
console.log('[Ideation] Emitting ideation-complete with session data');
debugLog('[Agent Queue] Loaded ideation session:', {
totalIdeas: session.ideas?.length || 0
});
this.emitter.emit('ideation-complete', projectId, session);
} else {
debugError('[Ideation] ideation.json not found at:', ideationFilePath);
console.warn('[Ideation] ideation.json not found at:', ideationFilePath);
}
} catch (err) {
debugError('[Ideation] Failed to load ideation session:', err);
console.error('[Ideation] Failed to load ideation session:', err);
}
}
} else {
debugError('[Agent Queue] Ideation generation failed:', { projectId, code });
this.emitter.emit('ideation-error', projectId, `Ideation generation failed with exit code ${code}`);
}
});
@@ -325,11 +392,17 @@ export class AgentQueueManager {
projectPath: string,
args: string[]
): void {
debugLog('[Agent Queue] Spawning roadmap process:', { projectId, projectPath });
// Kill existing process for this project if any
this.processManager.killProcess(projectId);
const wasKilled = this.processManager.killProcess(projectId);
if (wasKilled) {
debugLog('[Agent Queue] Killed existing roadmap process for project:', projectId);
}
// Generate unique spawn ID for this process instance
const spawnId = this.state.generateSpawnId();
debugLog('[Agent Queue] Generated roadmap spawn ID:', spawnId);
// Run from auto-claude source directory so imports work correctly
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
@@ -338,24 +411,44 @@ export class AgentQueueManager {
// Get combined environment variables
const combinedEnv = this.processManager.getCombinedEnv(projectPath);
// Get active Claude profile environment (CLAUDE_CONFIG_DIR if not default)
// Get active Claude profile environment (CLAUDE_CODE_OAUTH_TOKEN if not default)
const profileEnv = getProfileEnv();
// Get Python path from process manager (uses venv if configured)
const pythonPath = this.processManager.getPythonPath();
console.log('[Roadmap] Starting roadmap process with args:', args);
console.log('[Roadmap] CWD:', cwd);
console.log('[Roadmap] Python path:', pythonPath);
// Build final environment with proper precedence:
// 1. process.env (system)
// 2. combinedEnv (auto-claude/.env for CLI usage)
// 3. profileEnv (Electron app OAuth token - highest priority)
// 4. Our specific overrides
const finalEnv = {
...process.env,
...combinedEnv,
...profileEnv,
PYTHONPATH: autoBuildSource || '', // Allow imports from auto-claude directory
PYTHONUNBUFFERED: '1',
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
};
const childProcess = spawn(pythonPath, args, {
// Debug: Show OAuth token source
const tokenSource = profileEnv['CLAUDE_CODE_OAUTH_TOKEN']
? 'Electron app profile'
: (combinedEnv['CLAUDE_CODE_OAUTH_TOKEN'] ? 'auto-claude/.env' : 'not found');
const oauthToken = (finalEnv as Record<string, string | undefined>)['CLAUDE_CODE_OAUTH_TOKEN'];
const hasToken = !!oauthToken;
debugLog('[Agent Queue] OAuth token status:', {
source: tokenSource,
hasToken,
tokenPreview: hasToken ? oauthToken?.substring(0, 20) + '...' : 'none'
});
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(pythonPath);
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, ...args], {
cwd,
env: {
...process.env,
...combinedEnv,
...profileEnv,
PYTHONUNBUFFERED: '1'
}
env: finalEnv
});
this.state.addProcess(projectId, {
@@ -363,7 +456,8 @@ export class AgentQueueManager {
process: childProcess,
startedAt: new Date(),
projectPath, // Store project path for loading roadmap on completion
spawnId
spawnId,
queueProcessType: 'roadmap'
});
// Track progress through output
@@ -378,15 +472,14 @@ export class AgentQueueManager {
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length > 0) {
console.log('[Roadmap]', trimmed);
this.emitter.emit('roadmap-log', projectId, trimmed);
}
}
};
// Handle stdout
// Handle stdout - explicitly decode as UTF-8 for cross-platform Unicode support
childProcess.stdout?.on('data', (data: Buffer) => {
const log = data.toString();
const log = data.toString('utf8');
// Collect output for rate limit detection (keep last 10KB)
allRoadmapOutput = (allRoadmapOutput + log).slice(-10000);
@@ -406,9 +499,9 @@ export class AgentQueueManager {
});
});
// Handle stderr
// Handle stderr - explicitly decode as UTF-8
childProcess.stderr?.on('data', (data: Buffer) => {
const log = data.toString();
const log = data.toString('utf8');
// Collect stderr for rate limit detection too
allRoadmapOutput = (allRoadmapOutput + log).slice(-10000);
console.error('[Roadmap STDERR]', log);
@@ -422,7 +515,7 @@ export class AgentQueueManager {
// Handle process exit
childProcess.on('exit', (code: number | null) => {
console.log('[Roadmap] Process exited with code:', code);
debugLog('[Agent Queue] Roadmap process exited:', { projectId, code, spawnId });
// Get the stored project path before deleting from map
const processInfo = this.state.getProcess(projectId);
@@ -431,8 +524,10 @@ export class AgentQueueManager {
// Check for rate limit if process failed
if (code !== 0) {
debugLog('[Agent Queue] Checking for rate limit (non-zero exit)');
const rateLimitDetection = detectRateLimit(allRoadmapOutput);
if (rateLimitDetection.isRateLimited) {
debugLog('[Agent Queue] Rate limit detected for roadmap');
const rateLimitInfo = createSDKRateLimitInfo('roadmap', rateLimitDetection, {
projectId
});
@@ -441,7 +536,7 @@ export class AgentQueueManager {
}
if (code === 0) {
console.log('[Roadmap] Roadmap generation completed successfully');
debugLog('[Agent Queue] Roadmap generation completed successfully');
this.emitter.emit('roadmap-progress', projectId, {
phase: 'complete',
progress: 100,
@@ -457,20 +552,26 @@ export class AgentQueueManager {
'roadmap',
'roadmap.json'
);
debugLog('[Agent Queue] Loading roadmap from:', roadmapFilePath);
if (existsSync(roadmapFilePath)) {
const content = readFileSync(roadmapFilePath, 'utf-8');
const roadmap = JSON.parse(content);
console.log('[Roadmap] Emitting roadmap-complete with roadmap data');
debugLog('[Agent Queue] Loaded roadmap:', {
featuresCount: roadmap.features?.length || 0,
phasesCount: roadmap.phases?.length || 0
});
this.emitter.emit('roadmap-complete', projectId, roadmap);
} else {
debugError('[Roadmap] roadmap.json not found at:', roadmapFilePath);
console.warn('[Roadmap] roadmap.json not found at:', roadmapFilePath);
}
} catch (err) {
debugError('[Roadmap] Failed to load roadmap:', err);
console.error('[Roadmap] Failed to load roadmap:', err);
}
}
} else {
console.error('[Roadmap] Roadmap generation failed with exit code:', code);
debugError('[Agent Queue] Roadmap generation failed:', { projectId, code });
this.emitter.emit('roadmap-error', projectId, `Roadmap generation failed with exit code ${code}`);
}
});
@@ -487,12 +588,19 @@ export class AgentQueueManager {
* Stop ideation generation for a project
*/
stopIdeation(projectId: string): boolean {
const wasRunning = this.state.hasProcess(projectId);
if (wasRunning) {
debugLog('[Agent Queue] Stop ideation requested:', { projectId });
const processInfo = this.state.getProcess(projectId);
const isIdeation = processInfo?.queueProcessType === 'ideation';
debugLog('[Agent Queue] Process running?', { projectId, isIdeation, processType: processInfo?.queueProcessType });
if (isIdeation) {
debugLog('[Agent Queue] Killing ideation process:', projectId);
this.processManager.killProcess(projectId);
this.emitter.emit('ideation-stopped', projectId);
return true;
}
debugLog('[Agent Queue] No running ideation process found for:', projectId);
return false;
}
@@ -500,6 +608,35 @@ export class AgentQueueManager {
* Check if ideation is running for a project
*/
isIdeationRunning(projectId: string): boolean {
return this.state.hasProcess(projectId);
const processInfo = this.state.getProcess(projectId);
return processInfo?.queueProcessType === 'ideation';
}
/**
* Stop roadmap generation for a project
*/
stopRoadmap(projectId: string): boolean {
debugLog('[Agent Queue] Stop roadmap requested:', { projectId });
const processInfo = this.state.getProcess(projectId);
const isRoadmap = processInfo?.queueProcessType === 'roadmap';
debugLog('[Agent Queue] Roadmap process running?', { projectId, isRoadmap, processType: processInfo?.queueProcessType });
if (isRoadmap) {
debugLog('[Agent Queue] Killing roadmap process:', projectId);
this.processManager.killProcess(projectId);
this.emitter.emit('roadmap-stopped', projectId);
return true;
}
debugLog('[Agent Queue] No running roadmap process found for:', projectId);
return false;
}
/**
* Check if roadmap is running for a project
*/
isRoadmapRunning(projectId: string): boolean {
const processInfo = this.state.getProcess(projectId);
return processInfo?.queueProcessType === 'roadmap';
}
}
+20
View File
@@ -4,12 +4,15 @@ import { ChildProcess } from 'child_process';
* Agent-specific types for process and state management
*/
export type QueueProcessType = 'ideation' | 'roadmap';
export interface AgentProcess {
taskId: string;
process: ChildProcess;
startedAt: Date;
projectPath?: string; // For ideation processes to load session on completion
spawnId: number; // Unique ID to identify this specific spawn
queueProcessType?: QueueProcessType; // Type of queue process (ideation or roadmap)
}
export interface ExecutionProgressData {
@@ -45,6 +48,23 @@ export interface TaskExecutionOptions {
export interface SpecCreationMetadata {
requireReviewBeforeCoding?: boolean;
// Auto profile - phase-based model and thinking configuration
isAutoProfile?: boolean;
phaseModels?: {
spec: 'haiku' | 'sonnet' | 'opus';
planning: 'haiku' | 'sonnet' | 'opus';
coding: 'haiku' | 'sonnet' | 'opus';
qa: 'haiku' | 'sonnet' | 'opus';
};
phaseThinking?: {
spec: 'none' | 'low' | 'medium' | 'high' | 'ultrathink';
planning: 'none' | 'low' | 'medium' | 'high' | 'ultrathink';
coding: 'none' | 'low' | 'medium' | 'high' | 'ultrathink';
qa: 'none' | 'low' | 'medium' | 'high' | 'ultrathink';
};
// Non-auto profile - single model and thinking level
model?: 'haiku' | 'sonnet' | 'opus';
thinkingLevel?: 'none' | 'low' | 'medium' | 'high' | 'ultrathink';
}
export interface IdeationProgressData {
+224
View File
@@ -0,0 +1,224 @@
/**
* Electron App Auto-Updater
*
* Manages automatic updates for the packaged Electron application using electron-updater.
* Updates are published through GitHub Releases and automatically downloaded and installed.
*
* Update flow:
* 1. Check for updates 3 seconds after app launch
* 2. Download updates automatically when available
* 3. Notify user when update is downloaded
* 4. Install and restart when user confirms
*
* Events sent to renderer:
* - APP_UPDATE_AVAILABLE: New update available (with version info)
* - APP_UPDATE_DOWNLOADED: Update downloaded and ready to install
* - APP_UPDATE_PROGRESS: Download progress updates
* - APP_UPDATE_ERROR: Error during update process
*/
import { autoUpdater } from 'electron-updater';
import { app } from 'electron';
import type { BrowserWindow } from 'electron';
import { IPC_CHANNELS } from '../shared/constants';
import type { AppUpdateInfo } from '../shared/types';
// Debug mode - set via environment variable
const DEBUG_UPDATER = process.env.DEBUG_UPDATER === 'true' || process.env.DEBUG === 'true';
// Configure electron-updater
autoUpdater.autoDownload = true; // Automatically download updates when available
autoUpdater.autoInstallOnAppQuit = true; // Automatically install on app quit
// Enable more verbose logging in debug mode
if (DEBUG_UPDATER) {
autoUpdater.logger = {
info: (msg: string) => console.warn('[app-updater:debug]', msg),
warn: (msg: string) => console.warn('[app-updater:debug]', msg),
error: (msg: string) => console.error('[app-updater:debug]', msg),
debug: (msg: string) => console.warn('[app-updater:debug]', msg)
};
}
let mainWindow: BrowserWindow | null = null;
/**
* Initialize the app updater system
*
* Sets up event handlers and starts periodic update checks.
* Should only be called in production (app.isPackaged).
*
* @param window - The main BrowserWindow for sending update events
*/
export function initializeAppUpdater(window: BrowserWindow): void {
mainWindow = window;
// Log updater configuration
console.warn('[app-updater] ========================================');
console.warn('[app-updater] Initializing app auto-updater');
console.warn('[app-updater] App packaged:', app.isPackaged);
console.warn('[app-updater] Current version:', autoUpdater.currentVersion.version);
console.warn('[app-updater] Auto-download enabled:', autoUpdater.autoDownload);
console.warn('[app-updater] Debug mode:', DEBUG_UPDATER);
console.warn('[app-updater] ========================================');
// ============================================
// Event Handlers
// ============================================
// Update available - new version found
autoUpdater.on('update-available', (info) => {
console.warn('[app-updater] Update available:', info.version);
if (mainWindow) {
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_AVAILABLE, {
version: info.version,
releaseNotes: info.releaseNotes,
releaseDate: info.releaseDate
});
}
});
// Update downloaded - ready to install
autoUpdater.on('update-downloaded', (info) => {
console.warn('[app-updater] Update downloaded:', info.version);
if (mainWindow) {
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_DOWNLOADED, {
version: info.version,
releaseNotes: info.releaseNotes,
releaseDate: info.releaseDate
});
}
});
// Download progress
autoUpdater.on('download-progress', (progress) => {
console.warn(`[app-updater] Download progress: ${progress.percent.toFixed(2)}%`);
if (mainWindow) {
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_PROGRESS, {
percent: progress.percent,
bytesPerSecond: progress.bytesPerSecond,
transferred: progress.transferred,
total: progress.total
});
}
});
// Error handling
autoUpdater.on('error', (error) => {
console.error('[app-updater] Update error:', error);
if (mainWindow) {
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_ERROR, {
message: error.message,
stack: error.stack
});
}
});
// No update available
autoUpdater.on('update-not-available', (info) => {
console.warn('[app-updater] No updates available - you are on the latest version');
console.warn('[app-updater] Current version:', info.version);
if (DEBUG_UPDATER) {
console.warn('[app-updater:debug] Full info:', JSON.stringify(info, null, 2));
}
});
// Checking for updates
autoUpdater.on('checking-for-update', () => {
console.warn('[app-updater] Checking for updates...');
});
// ============================================
// Update Check Schedule
// ============================================
// Check for updates 3 seconds after launch
const INITIAL_DELAY = 3000;
console.warn(`[app-updater] Will check for updates in ${INITIAL_DELAY / 1000} seconds...`);
setTimeout(() => {
console.warn('[app-updater] Performing initial update check');
autoUpdater.checkForUpdates().catch((error) => {
console.error('[app-updater] ❌ Initial update check failed:', error.message);
if (DEBUG_UPDATER) {
console.error('[app-updater:debug] Full error:', error);
}
});
}, INITIAL_DELAY);
// Check for updates every 4 hours
const FOUR_HOURS = 4 * 60 * 60 * 1000;
console.warn(`[app-updater] Periodic checks scheduled every ${FOUR_HOURS / 1000 / 60 / 60} hours`);
setInterval(() => {
console.warn('[app-updater] Performing periodic update check');
autoUpdater.checkForUpdates().catch((error) => {
console.error('[app-updater] ❌ Periodic update check failed:', error.message);
if (DEBUG_UPDATER) {
console.error('[app-updater:debug] Full error:', error);
}
});
}, FOUR_HOURS);
console.warn('[app-updater] Auto-updater initialized successfully');
}
/**
* Manually check for updates
* Called from IPC handler when user requests manual check
*/
export async function checkForUpdates(): Promise<AppUpdateInfo | null> {
try {
console.warn('[app-updater] Manual update check requested');
const result = await autoUpdater.checkForUpdates();
if (!result) {
return null;
}
const updateAvailable = result.updateInfo.version !== autoUpdater.currentVersion.version;
if (!updateAvailable) {
return null;
}
return {
version: result.updateInfo.version,
releaseNotes: result.updateInfo.releaseNotes as string | undefined,
releaseDate: result.updateInfo.releaseDate
};
} catch (error) {
console.error('[app-updater] Manual update check failed:', error);
throw error;
}
}
/**
* Manually download update
* Called from IPC handler when user requests manual download
*/
export async function downloadUpdate(): Promise<void> {
try {
console.warn('[app-updater] Manual update download requested');
await autoUpdater.downloadUpdate();
} catch (error) {
console.error('[app-updater] Manual update download failed:', error);
throw error;
}
}
/**
* Quit and install update
* Called from IPC handler when user confirms installation
*/
export function quitAndInstall(): void {
console.warn('[app-updater] Quitting and installing update');
autoUpdater.quitAndInstall(false, true);
}
/**
* Get current app version
*/
export function getCurrentVersion(): string {
return autoUpdater.currentVersion.version;
}
@@ -27,7 +27,7 @@ export type {
} from './updater/types';
// Export version management
export { getBundledVersion } from './updater/version-manager';
export { getBundledVersion, getEffectiveVersion } from './updater/version-manager';
// Export path resolution
export {
@@ -27,13 +27,15 @@ import {
getCommits,
getBranchDiffCommits
} from './git-integration';
import { findPythonCommand } from '../python-detector';
/**
* Main changelog service - orchestrates all changelog operations
* Delegates to specialized modules for specific concerns
*/
export class ChangelogService extends EventEmitter {
private pythonPath: string = 'python3';
// Auto-detect Python command on initialization
private pythonPath: string = findPythonCommand() || 'python';
private claudePath: string = 'claude';
private autoBuildSourcePath: string = '';
private cachedEnv: Record<string, string> | null = null;
@@ -119,7 +121,7 @@ export class ChangelogService extends EventEmitter {
*/
private debug(...args: unknown[]): void {
if (this.isDebugEnabled()) {
console.log('[ChangelogService]', ...args);
console.warn('[ChangelogService]', ...args);
}
}
@@ -150,7 +152,8 @@ export class ChangelogService extends EventEmitter {
];
for (const p of possiblePaths) {
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
// Use requirements.txt as marker - it always exists in auto-claude source
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
return p;
}
}
+36 -1
View File
@@ -160,11 +160,32 @@ export function buildChangelogPrompt(
return parts.join('');
}).join('\n');
// Format-specific instructions for tasks mode
let formatSpecificInstructions = '';
if (request.format === 'github-release') {
formatSpecificInstructions = `
For GitHub Release format:
RELEASE TITLE (CRITICAL):
- First, analyze all completed tasks to identify the main theme or focus of this release
- Create a concise, descriptive title (2-5 words) that captures what this release is about
- Examples of good titles:
* "Improved Terminal Experience" (for terminal-related improvements)
* "Enhanced Security Features" (for security updates)
* "UI/UX Refinements" (for interface changes)
* "Agent Performance Boost" (for performance improvements)
- The version header MUST be: "## ${request.version} - [Your Thematic Title]"
- Focus on the USER BENEFIT or FUNCTIONAL AREA, not technical implementation details
- The title should be what the release is "about" in layman's terms
`;
}
return `${audienceInstruction}
Format:
${formatInstruction}
${emojiInstruction ? `\nEmoji Usage:\n${emojiInstruction}` : ''}
${formatSpecificInstructions}
Completed tasks:
${taskSummaries}
@@ -223,7 +244,21 @@ export function buildGitPrompt(
let formatSpecificInstructions = '';
if (request.format === 'github-release') {
formatSpecificInstructions = `
For GitHub Release format, create TWO parts after the version header:
For GitHub Release format, you MUST follow this structure:
RELEASE TITLE (CRITICAL):
- First, analyze all commits to identify the main theme or focus of this release
- Create a concise, descriptive title (2-5 words) that captures what this release is about
- Examples of good titles:
* "Improved Terminal Experience" (for terminal-related improvements)
* "Enhanced Security Features" (for security updates)
* "Performance Optimizations" (for speed improvements)
* "UI/UX Refinements" (for interface changes)
* "Agent System Overhaul" (for major architectural changes)
* "Build Pipeline Enhancements" (for CI/CD improvements)
- The version header MUST be: "## ${request.version} - [Your Thematic Title]"
- Focus on the USER BENEFIT or FUNCTIONAL AREA, not technical implementation details
- The title should be what the release is "about" in layman's terms
PART 1 - Categorized changes (summarized):
- Use category sections: New Features, Improvements, Bug Fixes, Documentation, Other Changes
@@ -12,6 +12,7 @@ import { buildChangelogPrompt, buildGitPrompt, createGenerationScript } from './
import { extractChangelog } from './parser';
import { getCommits, getBranchDiffCommits } from './git-integration';
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from '../rate-limit-detector';
import { parsePythonCommand } from '../python-detector';
/**
* Core changelog generation logic
@@ -34,7 +35,7 @@ export class ChangelogGenerator extends EventEmitter {
private debug(...args: unknown[]): void {
if (this.debugEnabled) {
console.log('[ChangelogGenerator]', ...args);
console.warn('[ChangelogGenerator]', ...args);
}
}
@@ -139,7 +140,9 @@ export class ChangelogGenerator extends EventEmitter {
// Build environment with explicit critical variables
const spawnEnv = this.buildSpawnEnvironment();
const childProcess = spawn(this.pythonPath, ['-c', script], {
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.pythonPath);
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, '-c', script], {
cwd: this.autoBuildSourcePath,
env: spawnEnv
});
@@ -277,7 +280,9 @@ export class ChangelogGenerator extends EventEmitter {
USER: process.env.USER || process.env.USERNAME || 'user',
// Add common binary locations to PATH for claude CLI
PATH: [process.env.PATH || '', ...pathAdditions].filter(Boolean).join(path.delimiter),
PYTHONUNBUFFERED: '1'
PYTHONUNBUFFERED: '1',
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
};
this.debug('Spawn environment', {
@@ -13,7 +13,7 @@ import { parseGitLogOutput } from './parser';
*/
function debug(enabled: boolean, ...args: unknown[]): void {
if (enabled) {
console.log('[GitIntegration]', ...args);
console.warn('[GitIntegration]', ...args);
}
}
+1 -1
View File
@@ -9,7 +9,7 @@ export function extractSpecOverview(spec: string): string {
// Handle both Unix (\n) and Windows (\r\n) line endings
const lines = spec.split(/\r?\n/);
let inOverview = false;
let overview: string[] = [];
const overview: string[] = [];
for (const line of lines) {
// Start capturing at Overview heading
@@ -3,6 +3,7 @@ import * as path from 'path';
import * as os from 'os';
import type { GitCommit } from '../../shared/types';
import { getProfileEnv } from '../rate-limit-detector';
import { parsePythonCommand } from '../python-detector';
interface VersionSuggestion {
version: string;
@@ -28,7 +29,7 @@ export class VersionSuggester {
private debug(...args: unknown[]): void {
if (this.debugEnabled) {
console.log('[VersionSuggester]', ...args);
console.warn('[VersionSuggester]', ...args);
}
}
@@ -51,8 +52,10 @@ export class VersionSuggester {
// Build environment
const spawnEnv = this.buildSpawnEnvironment();
return new Promise((resolve, reject) => {
const childProcess = spawn(this.pythonPath, ['-c', script], {
return new Promise((resolve, _reject) => {
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.pythonPath);
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, '-c', script], {
cwd: this.autoBuildSourcePath,
env: spawnEnv
});
@@ -98,7 +101,7 @@ export class VersionSuggester {
*/
private buildPrompt(commits: GitCommit[], currentVersion: string): string {
const commitSummary = commits
.map((c, i) => `${i + 1}. ${c.shortHash} - ${c.message}`)
.map((c, i) => `${i + 1}. ${c.hash} - ${c.subject}`)
.join('\n');
return `You are a semantic versioning expert analyzing git commits to suggest the appropriate version bump.
@@ -237,7 +240,9 @@ except Exception as e:
...(isWindows ? { USERPROFILE: homeDir } : { HOME: homeDir }),
USER: process.env.USER || process.env.USERNAME || 'user',
PATH: [process.env.PATH || '', ...pathAdditions].filter(Boolean).join(path.delimiter),
PYTHONUNBUFFERED: '1'
PYTHONUNBUFFERED: '1',
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
};
return spawnEnv;
@@ -240,7 +240,7 @@ export class ClaudeProfileManager {
profile.name = newName.trim();
this.save();
console.log('[ClaudeProfileManager] Renamed profile:', profileId, 'to:', newName);
console.warn('[ClaudeProfileManager] Renamed profile:', profileId, 'to:', newName);
return true;
}
@@ -317,7 +317,7 @@ export class ClaudeProfileManager {
this.save();
const isEncrypted = profile.oauthToken.startsWith('enc:');
console.log('[ClaudeProfileManager] Set OAuth token for profile:', profile.name, {
console.warn('[ClaudeProfileManager] Set OAuth token for profile:', profile.name, {
email: email || '(not captured)',
encrypted: isEncrypted,
tokenLength: token.length
@@ -350,14 +350,14 @@ export class ClaudeProfileManager {
const decryptedToken = decryptToken(profile.oauthToken);
if (decryptedToken) {
env.CLAUDE_CODE_OAUTH_TOKEN = decryptedToken;
console.log('[ClaudeProfileManager] Using OAuth token for profile:', profile.name);
console.warn('[ClaudeProfileManager] Using OAuth token for profile:', profile.name);
} else {
console.warn('[ClaudeProfileManager] Failed to decrypt token for profile:', profile.name);
}
} else if (profile?.configDir && !profile.isDefault) {
// Fallback to configDir for backward compatibility
env.CLAUDE_CONFIG_DIR = profile.configDir;
console.log('[ClaudeProfileManager] Using configDir for profile:', profile.name);
console.warn('[ClaudeProfileManager] Using configDir for profile:', profile.name);
}
return env;
@@ -376,7 +376,7 @@ export class ClaudeProfileManager {
profile.usage = usage;
this.save();
console.log('[ClaudeProfileManager] Updated usage for', profile.name, ':', usage);
console.warn('[ClaudeProfileManager] Updated usage for', profile.name, ':', usage);
return usage;
}
@@ -392,7 +392,7 @@ export class ClaudeProfileManager {
const event = recordRateLimitEventImpl(profile, resetTimeStr);
this.save();
console.log('[ClaudeProfileManager] Recorded rate limit event for', profile.name, ':', event);
console.warn('[ClaudeProfileManager] Recorded rate limit event for', profile.name, ':', event);
return event;
}
@@ -451,6 +451,34 @@ export class ClaudeProfileManager {
return isProfileAuthenticatedImpl(profile);
}
/**
* Check if a profile has valid authentication for starting tasks.
* A profile is considered authenticated if:
* 1) It has a valid OAuth token (not expired), OR
* 2) It has an authenticated configDir (credential files exist)
*
* @param profileId - Optional profile ID to check. If not provided, checks active profile.
* @returns true if the profile can authenticate, false otherwise
*/
hasValidAuth(profileId?: string): boolean {
const profile = profileId ? this.getProfile(profileId) : this.getActiveProfile();
if (!profile) {
return false;
}
// Check 1: Profile has a valid OAuth token
if (hasValidToken(profile)) {
return true;
}
// Check 2 & 3: Profile has authenticated configDir (works for both default and non-default)
if (this.isProfileAuthenticated(profile)) {
return true;
}
return false;
}
/**
* Get environment variables for invoking Claude with a specific profile
*/
@@ -86,12 +86,12 @@ export function getBestAvailableProfile(
// Return the best candidate if it has a positive score
const best = scoredProfiles[0];
if (best && best.score > 0) {
console.log('[ProfileScorer] Best available profile:', best.profile.name, 'score:', best.score);
console.warn('[ProfileScorer] Best available profile:', best.profile.name, 'score:', best.score);
return best.profile;
}
// All profiles are rate-limited or have issues
console.log('[ProfileScorer] No good profile available, all are rate-limited or have issues');
console.warn('[ProfileScorer] No good profile available, all are rate-limited or have issues');
return null;
}
@@ -143,7 +143,7 @@ export function shouldProactivelySwitch(
* Get profiles sorted by availability (best first)
*/
export function getProfilesSortedByAvailability(profiles: ClaudeProfile[]): ClaudeProfile[] {
const now = new Date();
const _now = new Date();
return [...profiles].sort((a, b) => {
// Not rate-limited profiles first
@@ -117,7 +117,7 @@ export function hasValidToken(profile: ClaudeProfile): boolean {
const oneYearAgo = new Date();
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
if (new Date(profile.tokenCreatedAt) < oneYearAgo) {
console.log('[ProfileUtils] Token expired for profile:', profile.name);
console.warn('[ProfileUtils] Token expired for profile:', profile.name);
return false;
}
}
@@ -22,7 +22,7 @@ export class UsageMonitor extends EventEmitter {
private constructor() {
super();
console.log('[UsageMonitor] Initialized');
console.warn('[UsageMonitor] Initialized');
}
static getInstance(): UsageMonitor {
@@ -40,17 +40,17 @@ export class UsageMonitor extends EventEmitter {
const settings = profileManager.getAutoSwitchSettings();
if (!settings.enabled || !settings.proactiveSwapEnabled) {
console.log('[UsageMonitor] Proactive monitoring disabled');
console.warn('[UsageMonitor] Proactive monitoring disabled');
return;
}
if (this.intervalId) {
console.log('[UsageMonitor] Already running');
console.warn('[UsageMonitor] Already running');
return;
}
const interval = settings.usageCheckInterval || 30000;
console.log('[UsageMonitor] Starting with interval:', interval, 'ms');
console.warn('[UsageMonitor] Starting with interval:', interval, 'ms');
// Check immediately
this.checkUsageAndSwap();
@@ -68,7 +68,7 @@ export class UsageMonitor extends EventEmitter {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
console.log('[UsageMonitor] Stopped');
console.warn('[UsageMonitor] Stopped');
}
}
@@ -94,14 +94,16 @@ export class UsageMonitor extends EventEmitter {
const activeProfile = profileManager.getActiveProfile();
if (!activeProfile) {
console.log('[UsageMonitor] No active profile');
console.warn('[UsageMonitor] No active profile');
return;
}
// Fetch current usage (hybrid approach)
const usage = await this.fetchUsage(activeProfile.id, activeProfile.oauthToken);
// Get decrypted token from ProfileManager (activeProfile.oauthToken is encrypted)
const decryptedToken = profileManager.getProfileToken(activeProfile.id);
const usage = await this.fetchUsage(activeProfile.id, decryptedToken ?? undefined);
if (!usage) {
console.log('[UsageMonitor] Failed to fetch usage');
console.warn('[UsageMonitor] Failed to fetch usage');
return;
}
@@ -116,7 +118,7 @@ export class UsageMonitor extends EventEmitter {
const weeklyExceeded = usage.weeklyPercent >= settings.weeklyThreshold;
if (sessionExceeded || weeklyExceeded) {
console.log('[UsageMonitor] Threshold exceeded:', {
console.warn('[UsageMonitor] Threshold exceeded:', {
sessionPercent: usage.sessionPercent,
sessionThreshold: settings.sessionThreshold,
weeklyPercent: usage.weeklyPercent,
@@ -154,12 +156,12 @@ export class UsageMonitor extends EventEmitter {
if (this.useApiMethod && oauthToken) {
const apiUsage = await this.fetchUsageViaAPI(oauthToken, profileId, profile.name);
if (apiUsage) {
console.log('[UsageMonitor] Successfully fetched via API');
console.warn('[UsageMonitor] Successfully fetched via API');
return apiUsage;
}
// API failed - switch to CLI method for future calls
console.log('[UsageMonitor] API method failed, falling back to CLI');
console.warn('[UsageMonitor] API method failed, falling back to CLI');
this.useApiMethod = false;
}
@@ -191,7 +193,12 @@ export class UsageMonitor extends EventEmitter {
return null;
}
const data: any = await response.json();
const data = await response.json() as {
five_hour_utilization?: number;
seven_day_utilization?: number;
five_hour_reset_at?: string;
seven_day_reset_at?: string;
};
// Expected response format:
// {
@@ -232,7 +239,7 @@ export class UsageMonitor extends EventEmitter {
// CLI-based usage fetching is not implemented yet.
// The API method should handle most cases. If we need CLI fallback,
// we would need to spawn a Claude process with /usage command and parse the output.
console.log('[UsageMonitor] CLI fallback not implemented, API method should be used');
console.warn('[UsageMonitor] CLI fallback not implemented, API method should be used');
return null;
}
@@ -256,7 +263,7 @@ export class UsageMonitor extends EventEmitter {
const diffDays = Math.floor(diffHours / 24);
const remainingHours = diffHours % 24;
return `${diffDays}d ${remainingHours}h`;
} catch (error) {
} catch (_error) {
return isoTimestamp;
}
}
@@ -272,7 +279,7 @@ export class UsageMonitor extends EventEmitter {
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
if (!bestProfile) {
console.log('[UsageMonitor] No alternative profile for proactive swap');
console.warn('[UsageMonitor] No alternative profile for proactive swap');
this.emit('proactive-swap-failed', {
reason: 'no_alternative',
currentProfile: currentProfileId
@@ -280,7 +287,7 @@ export class UsageMonitor extends EventEmitter {
return;
}
console.log('[UsageMonitor] Proactive swap:', {
console.warn('[UsageMonitor] Proactive swap:', {
from: currentProfileId,
to: bestProfile.id,
reason: limitType
+4 -4
View File
@@ -158,7 +158,7 @@ export async function checkFalkorDBStatus(port: number = FALKORDB_DEFAULT_PORT):
/**
* Check if FalkorDB is responding to connections
*/
async function checkFalkorDBHealth(port: number): Promise<boolean> {
async function checkFalkorDBHealth(_port: number): Promise<boolean> {
try {
// Try to ping FalkorDB using redis-cli (FalkorDB uses Redis protocol)
// Since we may not have redis-cli, we'll check if the port is listening
@@ -482,10 +482,10 @@ export async function validateOpenAIApiKey(
timeout: 15000,
};
const req = https.request(options, (res: any) => {
const req = https.request(options, (res: { statusCode: number; on: (event: string, callback: (chunk: Buffer) => void) => void }) => {
let data = '';
res.on('data', (chunk: any) => {
res.on('data', (chunk: Buffer) => {
data += chunk;
});
@@ -533,7 +533,7 @@ export async function validateOpenAIApiKey(
});
});
req.on('error', (error: any) => {
req.on('error', (error: Error) => {
resolve({
success: false,
message: `Connection error: ${error.message}`,
+38 -4
View File
@@ -7,6 +7,7 @@ import { TerminalManager } from './terminal-manager';
import { pythonEnvManager } from './python-env-manager';
import { getUsageMonitor } from './claude-profile/usage-monitor';
import { initializeUsageMonitorForwarding } from './ipc-handlers/terminal-handlers';
import { initializeAppUpdater } from './app-updater';
// Get icon path based on platform
function getIconPath(): string {
@@ -21,7 +22,7 @@ function getIconPath(): string {
// Use PNG in dev mode (works better), ICNS in production
iconName = is.dev ? 'icon-256.png' : 'icon.icns';
} else if (process.platform === 'win32') {
iconName = 'icon-256.png';
iconName = 'icon.ico';
} else {
iconName = 'icon.png';
}
@@ -51,7 +52,8 @@ function createWindow(): void {
preload: join(__dirname, '../preload/index.js'),
sandbox: false,
contextIsolation: true,
nodeIntegration: false
nodeIntegration: false,
backgroundThrottling: false // Prevent terminal lag when window loses focus
}
});
@@ -135,7 +137,39 @@ app.whenReady().then(() => {
// Start the usage monitor
const usageMonitor = getUsageMonitor();
usageMonitor.start();
console.log('[main] Usage monitor initialized and started');
console.warn('[main] Usage monitor initialized and started');
// Log debug mode status
const isDebugMode = process.env.DEBUG === 'true';
const isAutoClaudeDebug = process.env.AUTO_CLAUDE_DEBUG === 'true';
if (isDebugMode || isAutoClaudeDebug) {
console.warn('[main] ========================================');
console.warn('[main] DEBUG MODE ENABLED');
if (isDebugMode) {
console.warn('[main] - DEBUG=true (Ideation/Roadmap debug logging)');
}
if (isAutoClaudeDebug) {
console.warn('[main] - AUTO_CLAUDE_DEBUG=true (Core features debug logging)');
}
console.warn('[main] ========================================');
}
// Initialize app auto-updater (only in production, or when DEBUG_UPDATER is set)
const forceUpdater = process.env.DEBUG_UPDATER === 'true';
if (app.isPackaged || forceUpdater) {
initializeAppUpdater(mainWindow);
console.warn('[main] App auto-updater initialized');
if (forceUpdater && !app.isPackaged) {
console.warn('[main] Updater forced in dev mode via DEBUG_UPDATER=true');
console.warn('[main] Note: Updates won\'t actually work in dev mode');
}
} else {
console.warn('[main] ========================================');
console.warn('[main] App auto-updater DISABLED (development mode)');
console.warn('[main] To test updater logging, set DEBUG_UPDATER=true');
console.warn('[main] Note: Actual updates only work in packaged builds');
console.warn('[main] ========================================');
}
}
// macOS: re-create window when dock icon is clicked
@@ -158,7 +192,7 @@ app.on('before-quit', async () => {
// Stop usage monitor
const usageMonitor = getUsageMonitor();
usageMonitor.stop();
console.log('[main] Usage monitor stopped');
console.warn('[main] Usage monitor stopped');
// Kill all running agent processes
if (agentManager) {
+19 -5
View File
@@ -3,9 +3,7 @@ import type {
InsightsSession,
InsightsSessionSummary,
InsightsChatMessage,
InsightsChatStatus,
InsightsStreamChunk,
InsightsToolUsage
InsightsModelConfig
} from '../shared/types';
import { InsightsConfig } from './insights/config';
import { InsightsPaths } from './insights/paths';
@@ -114,7 +112,12 @@ export class InsightsService extends EventEmitter {
/**
* Send a message and get AI response
*/
async sendMessage(projectId: string, projectPath: string, message: string): Promise<void> {
async sendMessage(
projectId: string,
projectPath: string,
message: string,
modelConfig?: InsightsModelConfig
): Promise<void> {
// Cancel any existing session
this.executor.cancelSession(projectId);
@@ -153,13 +156,17 @@ export class InsightsService extends EventEmitter {
content: m.content
}));
// Use provided modelConfig or fall back to session's config
const configToUse = modelConfig || session.modelConfig;
try {
// Execute insights query
const result = await this.executor.execute(
projectId,
projectPath,
message,
conversationHistory
conversationHistory,
configToUse
);
// Add assistant message to session
@@ -180,6 +187,13 @@ export class InsightsService extends EventEmitter {
console.error('[InsightsService] Error executing insights:', error);
}
}
/**
* Update model configuration for a session
*/
updateSessionModelConfig(projectPath: string, sessionId: string, modelConfig: InsightsModelConfig): boolean {
return this.sessionManager.updateSessionModelConfig(projectPath, sessionId, modelConfig);
}
}
// Singleton instance
+8 -3
View File
@@ -2,13 +2,15 @@ import path from 'path';
import { existsSync, readFileSync } from 'fs';
import { app } from 'electron';
import { getProfileEnv } from '../rate-limit-detector';
import { findPythonCommand } from '../python-detector';
/**
* Configuration manager for insights service
* Handles path detection and environment variable loading
*/
export class InsightsConfig {
private pythonPath: string = 'python3';
// Auto-detect Python command on initialization
private pythonPath: string = findPythonCommand() || 'python';
private autoBuildSourcePath: string = '';
/**
@@ -45,7 +47,8 @@ export class InsightsConfig {
];
for (const p of possiblePaths) {
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
// Use requirements.txt as marker - it always exists in auto-claude source
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
return p;
}
}
@@ -103,7 +106,9 @@ export class InsightsConfig {
...process.env as Record<string, string>,
...autoBuildEnv,
...profileEnv,
PYTHONUNBUFFERED: '1'
PYTHONUNBUFFERED: '1',
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
};
}
}
@@ -1,13 +1,16 @@
import { spawn, ChildProcess } from 'child_process';
import { existsSync } from 'fs';
import { existsSync, writeFileSync, unlinkSync } from 'fs';
import path from 'path';
import os from 'os';
import { EventEmitter } from 'events';
import type {
InsightsChatMessage,
InsightsChatStatus,
InsightsStreamChunk,
InsightsToolUsage
InsightsToolUsage,
InsightsModelConfig
} from '../../shared/types';
import { MODEL_ID_MAP } from '../../shared/constants';
import { InsightsConfig } from './config';
import { detectRateLimit, createSDKRateLimitInfo } from '../rate-limit-detector';
@@ -59,7 +62,8 @@ export class InsightsExecutor extends EventEmitter {
projectId: string,
projectPath: string,
message: string,
conversationHistory: Array<{ role: string; content: string }>
conversationHistory: Array<{ role: string; content: string }>,
modelConfig?: InsightsModelConfig
): Promise<ProcessorResult> {
// Cancel any existing session
this.cancelSession(projectId);
@@ -69,7 +73,7 @@ export class InsightsExecutor extends EventEmitter {
throw new Error('Auto Claude source not found');
}
const runnerPath = path.join(autoBuildSource, 'insights_runner.py');
const runnerPath = path.join(autoBuildSource, 'runners', 'insights_runner.py');
if (!existsSync(runnerPath)) {
throw new Error('insights_runner.py not found in auto-claude directory');
}
@@ -83,13 +87,38 @@ export class InsightsExecutor extends EventEmitter {
// Get process environment
const processEnv = this.config.getProcessEnv();
// Spawn Python process
const proc = spawn(this.config.getPythonPath(), [
// Write conversation history to temp file to avoid Windows command-line length limit
const historyFile = path.join(
os.tmpdir(),
`insights-history-${projectId}-${Date.now()}.json`
);
let historyFileCreated = false;
try {
writeFileSync(historyFile, JSON.stringify(conversationHistory), 'utf-8');
historyFileCreated = true;
} catch (err) {
console.error('[Insights] Failed to write history file:', err);
throw new Error('Failed to write conversation history to temp file');
}
// Build command arguments
const args = [
runnerPath,
'--project-dir', projectPath,
'--message', message,
'--history', JSON.stringify(conversationHistory)
], {
'--history-file', historyFile
];
// Add model config if provided
if (modelConfig) {
const modelId = MODEL_ID_MAP[modelConfig.model] || MODEL_ID_MAP['sonnet'];
args.push('--model', modelId);
args.push('--thinking-level', modelConfig.thinkingLevel);
}
// Spawn Python process
const proc = spawn(this.config.getPythonPath(), args, {
cwd: autoBuildSource,
env: processEnv
});
@@ -138,6 +167,15 @@ export class InsightsExecutor extends EventEmitter {
proc.on('close', (code) => {
this.activeSessions.delete(projectId);
// Cleanup temp file
if (historyFileCreated && existsSync(historyFile)) {
try {
unlinkSync(historyFile);
} catch (cleanupErr) {
console.error('[Insights] Failed to cleanup history file:', cleanupErr);
}
}
// Check for rate limit if process failed
if (code !== 0) {
this.handleRateLimit(projectId, allInsightsOutput);
@@ -171,6 +209,16 @@ export class InsightsExecutor extends EventEmitter {
proc.on('error', (err) => {
this.activeSessions.delete(projectId);
// Cleanup temp file
if (historyFileCreated && existsSync(historyFile)) {
try {
unlinkSync(historyFile);
} catch (cleanupErr) {
console.error('[Insights] Failed to cleanup history file:', cleanupErr);
}
}
this.emit('error', projectId, err.message);
reject(err);
});
@@ -251,7 +299,7 @@ export class InsightsExecutor extends EventEmitter {
private handleRateLimit(projectId: string, output: string): void {
const rateLimitDetection = detectRateLimit(output);
if (rateLimitDetection.isRateLimited) {
console.log('[Insights] Rate limit detected:', {
console.warn('[Insights] Rate limit detected:', {
projectId,
resetTime: rateLimitDetection.resetTime,
limitType: rateLimitDetection.limitType,
@@ -1,4 +1,4 @@
import type { InsightsSession, InsightsSessionSummary } from '../../shared/types';
import type { InsightsSession, InsightsSessionSummary, InsightsModelConfig } from '../../shared/types';
import { SessionStorage } from './session-storage';
import { InsightsPaths } from './paths';
@@ -119,6 +119,30 @@ export class SessionManager {
return true;
}
/**
* Update model configuration for a session
*/
updateSessionModelConfig(projectPath: string, sessionId: string, modelConfig: InsightsModelConfig): boolean {
const session = this.storage.loadSessionById(projectPath, sessionId);
if (!session) return false;
session.modelConfig = modelConfig;
session.updatedAt = new Date();
this.storage.saveSession(projectPath, session);
// Update cache if this session is cached
for (const [projectId, cachedSession] of this.sessions) {
if (cachedSession.id === sessionId) {
cachedSession.modelConfig = modelConfig;
cachedSession.updatedAt = new Date();
this.sessions.set(projectId, cachedSession);
break;
}
}
return true;
}
/**
* Save session to disk and update cache
*/
@@ -1,16 +1,13 @@
import { ipcMain } from 'electron';
import type { BrowserWindow } from 'electron';
import path from 'path';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { IPC_CHANNELS, getSpecsDir, AUTO_BUILD_PATHS } from '../../shared/constants';
import type {
IPCResult,
SDKRateLimitInfo,
Task,
TaskStatus,
Project,
ImplementationPlan,
ExecutionProgress
ImplementationPlan
} from '../../shared/types';
import { AgentManager } from '../agent';
import type { ProcessType, ExecutionProgressData } from '../agent';
@@ -82,7 +79,7 @@ export function registerAgenteventsHandlers(
} else if (processType === 'spec-creation') {
// Pure spec creation (shouldn't happen with current flow, but handle it)
// Stay in backlog/planning
console.log(`[Task ${taskId}] Spec creation completed with code ${code}`);
console.warn(`[Task ${taskId}] Spec creation completed with code ${code}`);
return;
} else {
// Unknown process type
@@ -130,7 +127,7 @@ export function registerAgenteventsHandlers(
plan.planStatus = 'review';
plan.updated_at = new Date().toISOString();
writeFileSync(planPath, JSON.stringify(plan, null, 2));
console.log(`[Task ${taskId}] Persisted status '${newStatus}' to implementation_plan.json`);
console.warn(`[Task ${taskId}] Persisted status '${newStatus}' to implementation_plan.json`);
}
}
}
@@ -141,7 +138,7 @@ export function registerAgenteventsHandlers(
// Send notifications based on task completion status
if (task && project) {
const taskTitle = task.title || task.specId;
if (code === 0) {
// Task completed successfully - ready for review
notificationService.notifyReviewNeeded(taskTitle, project.id, taskId);
@@ -0,0 +1,106 @@
/**
* App Update IPC Handlers
*
* Handles IPC communication for Electron app auto-updates.
* Provides manual controls for checking, downloading, and installing updates.
*/
import { ipcMain } from 'electron';
import { IPC_CHANNELS } from '../../shared/constants';
import type { IPCResult, AppUpdateInfo } from '../../shared/types';
import {
checkForUpdates,
downloadUpdate,
quitAndInstall,
getCurrentVersion
} from '../app-updater';
/**
* Register all app-update-related IPC handlers
*/
export function registerAppUpdateHandlers(): void {
console.warn('[IPC] Registering app update handlers');
// ============================================
// App Update Operations
// ============================================
/**
* APP_UPDATE_CHECK: Manually check for updates
* Returns update availability and version information
*/
ipcMain.handle(
IPC_CHANNELS.APP_UPDATE_CHECK,
async (): Promise<IPCResult<AppUpdateInfo | null>> => {
try {
const result = await checkForUpdates();
return { success: true, data: result };
} catch (error) {
console.error('[app-update-handlers] Check for updates failed:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to check for updates'
};
}
}
);
/**
* APP_UPDATE_DOWNLOAD: Manually download update
* Triggers download of available update
*/
ipcMain.handle(
IPC_CHANNELS.APP_UPDATE_DOWNLOAD,
async (): Promise<IPCResult> => {
try {
await downloadUpdate();
return { success: true };
} catch (error) {
console.error('[app-update-handlers] Download update failed:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to download update'
};
}
}
);
/**
* APP_UPDATE_INSTALL: Quit and install update
* Quits the app and installs the downloaded update
*/
ipcMain.handle(
IPC_CHANNELS.APP_UPDATE_INSTALL,
async (): Promise<IPCResult> => {
try {
quitAndInstall();
return { success: true };
} catch (error) {
console.error('[app-update-handlers] Install update failed:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to install update'
};
}
}
);
/**
* APP_UPDATE_GET_VERSION: Get current app version
* Returns the current application version
*/
ipcMain.handle(
IPC_CHANNELS.APP_UPDATE_GET_VERSION,
async (): Promise<string> => {
try {
const version = getCurrentVersion();
return version;
} catch (error) {
console.error('[app-update-handlers] Get version failed:', error);
throw error;
}
}
);
console.warn('[IPC] App update handlers registered successfully');
}
@@ -5,7 +5,8 @@ import type { IPCResult } from '../../shared/types';
import path from 'path';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import type { AutoBuildSourceUpdateProgress, SourceEnvConfig, SourceEnvCheckResult } from '../../shared/types';
import { checkForUpdates as checkSourceUpdates, downloadAndApplyUpdate, getBundledVersion, getEffectiveSourcePath } from '../auto-claude-updater';
import { checkForUpdates as checkSourceUpdates, downloadAndApplyUpdate, getBundledVersion, getEffectiveVersion, getEffectiveSourcePath } from '../auto-claude-updater';
import { debugLog } from '../../shared/utils/debug-logger';
/**
@@ -21,10 +22,16 @@ export function registerAutobuildSourceHandlers(
ipcMain.handle(
IPC_CHANNELS.AUTOBUILD_SOURCE_CHECK,
async (): Promise<IPCResult<{ updateAvailable: boolean; currentVersion: string; latestVersion?: string; releaseNotes?: string; releaseUrl?: string; error?: string }>> => {
console.log('[autobuild-source] Check for updates called');
debugLog('[IPC] AUTOBUILD_SOURCE_CHECK called');
try {
const result = await checkSourceUpdates();
console.log('[autobuild-source] Check result:', JSON.stringify(result, null, 2));
debugLog('[IPC] AUTOBUILD_SOURCE_CHECK result:', result);
return { success: true, data: result };
} catch (error) {
console.error('[autobuild-source] Check error:', error);
debugLog('[IPC] AUTOBUILD_SOURCE_CHECK error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to check for updates'
@@ -36,25 +43,33 @@ export function registerAutobuildSourceHandlers(
ipcMain.on(
IPC_CHANNELS.AUTOBUILD_SOURCE_DOWNLOAD,
() => {
debugLog('[IPC] Autobuild source download requested');
const mainWindow = getMainWindow();
if (!mainWindow) return;
if (!mainWindow) {
debugLog('[IPC] No main window available, aborting update');
return;
}
// Start download in background
downloadAndApplyUpdate((progress) => {
debugLog('[IPC] Update progress:', progress.stage, progress.message);
mainWindow.webContents.send(
IPC_CHANNELS.AUTOBUILD_SOURCE_PROGRESS,
progress
);
}).then((result) => {
if (result.success) {
debugLog('[IPC] Update completed successfully, version:', result.version);
mainWindow.webContents.send(
IPC_CHANNELS.AUTOBUILD_SOURCE_PROGRESS,
{
stage: 'complete',
message: `Updated to version ${result.version}`
message: `Updated to version ${result.version}`,
newVersion: result.version // Include new version for UI refresh
} as AutoBuildSourceUpdateProgress
);
} else {
debugLog('[IPC] Update failed:', result.error);
mainWindow.webContents.send(
IPC_CHANNELS.AUTOBUILD_SOURCE_PROGRESS,
{
@@ -64,6 +79,7 @@ export function registerAutobuildSourceHandlers(
);
}
}).catch((error) => {
debugLog('[IPC] Update error:', error instanceof Error ? error.message : error);
mainWindow.webContents.send(
IPC_CHANNELS.AUTOBUILD_SOURCE_PROGRESS,
{
@@ -88,7 +104,9 @@ export function registerAutobuildSourceHandlers(
IPC_CHANNELS.AUTOBUILD_SOURCE_VERSION,
async (): Promise<IPCResult<string>> => {
try {
const version = getBundledVersion();
// Use effective version which accounts for source updates
const version = getEffectiveVersion();
debugLog('[IPC] Returning effective version:', version);
return { success: true, data: version };
} catch (error) {
return {
@@ -1,8 +1,7 @@
import { ipcMain } from 'electron';
import type { BrowserWindow } from 'electron';
import path from 'path';
import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
import { execSync } from 'child_process';
import { existsSync, mkdirSync, writeFileSync } from 'fs';
import { IPC_CHANNELS, getSpecsDir } from '../../shared/constants';
import type {
IPCResult,
@@ -155,7 +155,7 @@ export function searchFileBasedMemories(
* Register memory data handlers
*/
export function registerMemoryDataHandlers(
getMainWindow: () => BrowserWindow | null
_getMainWindow: () => BrowserWindow | null
): void {
// Get all memories
ipcMain.handle(
@@ -109,7 +109,7 @@ export function buildMemoryStatus(
* Register memory status handlers
*/
export function registerMemoryStatusHandlers(
getMainWindow: () => BrowserWindow | null
_getMainWindow: () => BrowserWindow | null
): void {
ipcMain.handle(
IPC_CHANNELS.CONTEXT_MEMORY_STATUS,
@@ -13,10 +13,7 @@ import type {
import { projectStore } from '../../project-store';
import { getFalkorDBService } from '../../falkordb-service';
import {
getAutoBuildSourcePath,
loadProjectEnvVars,
isGraphitiEnabled,
getGraphitiConnectionDetails
getAutoBuildSourcePath
} from './utils';
import {
loadGraphitiStateFromSpecs,
@@ -83,7 +80,7 @@ async function loadRecentMemories(
* Register project context handlers
*/
export function registerProjectContextHandlers(
getMainWindow: () => BrowserWindow | null
_getMainWindow: () => BrowserWindow | null
): void {
// Get full project context
ipcMain.handle(
@@ -5,7 +5,7 @@ import type { IPCResult, ProjectEnvConfig, ClaudeAuthResult, AppSettings } from
import path from 'path';
import { app } from 'electron';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { execSync, spawn } from 'child_process';
import { spawn } from 'child_process';
import { projectStore } from '../project-store';
import { parseEnvFile } from './utils';
@@ -14,7 +14,7 @@ import { parseEnvFile } from './utils';
* Register all env-related IPC handlers
*/
export function registerEnvHandlers(
getMainWindow: () => BrowserWindow | null
_getMainWindow: () => BrowserWindow | null
): void {
// ============================================
// Environment Configuration Operations
@@ -62,9 +62,48 @@ export function registerEnvHandlers(
if (config.githubAutoSync !== undefined) {
existingVars['GITHUB_AUTO_SYNC'] = config.githubAutoSync ? 'true' : 'false';
}
// Git/Worktree Settings
if (config.defaultBranch !== undefined) {
existingVars['DEFAULT_BRANCH'] = config.defaultBranch;
}
if (config.graphitiEnabled !== undefined) {
existingVars['GRAPHITI_ENABLED'] = config.graphitiEnabled ? 'true' : 'false';
}
// Graphiti Provider Configuration
if (config.graphitiProviderConfig) {
const pc = config.graphitiProviderConfig;
if (pc.llmProvider) existingVars['GRAPHITI_LLM_PROVIDER'] = pc.llmProvider;
if (pc.embeddingProvider) existingVars['GRAPHITI_EMBEDDER_PROVIDER'] = pc.embeddingProvider;
// OpenAI
if (pc.openaiApiKey) existingVars['OPENAI_API_KEY'] = pc.openaiApiKey;
if (pc.openaiModel) existingVars['OPENAI_MODEL'] = pc.openaiModel;
if (pc.openaiEmbeddingModel) existingVars['OPENAI_EMBEDDING_MODEL'] = pc.openaiEmbeddingModel;
// Anthropic
if (pc.anthropicApiKey) existingVars['ANTHROPIC_API_KEY'] = pc.anthropicApiKey;
if (pc.anthropicModel) existingVars['GRAPHITI_ANTHROPIC_MODEL'] = pc.anthropicModel;
// Azure OpenAI
if (pc.azureOpenaiApiKey) existingVars['AZURE_OPENAI_API_KEY'] = pc.azureOpenaiApiKey;
if (pc.azureOpenaiBaseUrl) existingVars['AZURE_OPENAI_BASE_URL'] = pc.azureOpenaiBaseUrl;
if (pc.azureOpenaiLlmDeployment) existingVars['AZURE_OPENAI_LLM_DEPLOYMENT'] = pc.azureOpenaiLlmDeployment;
if (pc.azureOpenaiEmbeddingDeployment) existingVars['AZURE_OPENAI_EMBEDDING_DEPLOYMENT'] = pc.azureOpenaiEmbeddingDeployment;
// Voyage
if (pc.voyageApiKey) existingVars['VOYAGE_API_KEY'] = pc.voyageApiKey;
if (pc.voyageEmbeddingModel) existingVars['VOYAGE_EMBEDDING_MODEL'] = pc.voyageEmbeddingModel;
// Google
if (pc.googleApiKey) existingVars['GOOGLE_API_KEY'] = pc.googleApiKey;
if (pc.googleLlmModel) existingVars['GOOGLE_LLM_MODEL'] = pc.googleLlmModel;
if (pc.googleEmbeddingModel) existingVars['GOOGLE_EMBEDDING_MODEL'] = pc.googleEmbeddingModel;
// Ollama
if (pc.ollamaBaseUrl) existingVars['OLLAMA_BASE_URL'] = pc.ollamaBaseUrl;
if (pc.ollamaLlmModel) existingVars['OLLAMA_LLM_MODEL'] = pc.ollamaLlmModel;
if (pc.ollamaEmbeddingModel) existingVars['OLLAMA_EMBEDDING_MODEL'] = pc.ollamaEmbeddingModel;
if (pc.ollamaEmbeddingDim) existingVars['OLLAMA_EMBEDDING_DIM'] = String(pc.ollamaEmbeddingDim);
// FalkorDB
if (pc.falkorDbHost) existingVars['GRAPHITI_FALKORDB_HOST'] = pc.falkorDbHost;
if (pc.falkorDbPort) existingVars['GRAPHITI_FALKORDB_PORT'] = String(pc.falkorDbPort);
if (pc.falkorDbPassword) existingVars['GRAPHITI_FALKORDB_PASSWORD'] = pc.falkorDbPassword;
}
// Legacy fields (still supported)
if (config.openaiApiKey !== undefined) {
existingVars['OPENAI_API_KEY'] = config.openaiApiKey;
}
@@ -85,7 +124,7 @@ export function registerEnvHandlers(
}
// Generate content with sections
let content = `# Auto Claude Framework Environment Variables
const content = `# Auto Claude Framework Environment Variables
# Managed by Auto Claude UI
# Claude Code OAuth Token (REQUIRED)
@@ -109,6 +148,13 @@ ${existingVars['GITHUB_TOKEN'] ? `GITHUB_TOKEN=${existingVars['GITHUB_TOKEN']}`
${existingVars['GITHUB_REPO'] ? `GITHUB_REPO=${existingVars['GITHUB_REPO']}` : '# GITHUB_REPO=owner/repo'}
${existingVars['GITHUB_AUTO_SYNC'] !== undefined ? `GITHUB_AUTO_SYNC=${existingVars['GITHUB_AUTO_SYNC']}` : '# GITHUB_AUTO_SYNC=false'}
# =============================================================================
# GIT/WORKTREE SETTINGS (OPTIONAL)
# =============================================================================
# Default base branch for worktree creation
# If not set, Auto Claude will auto-detect main/master, or fall back to current branch
${existingVars['DEFAULT_BRANCH'] ? `DEFAULT_BRANCH=${existingVars['DEFAULT_BRANCH']}` : '# DEFAULT_BRANCH=main'}
# =============================================================================
# UI SETTINGS (OPTIONAL)
# =============================================================================
@@ -116,9 +162,45 @@ ${existingVars['ENABLE_FANCY_UI'] !== undefined ? `ENABLE_FANCY_UI=${existingVar
# =============================================================================
# GRAPHITI MEMORY INTEGRATION (OPTIONAL)
# Multi-provider support: OpenAI, Anthropic, Google AI, Azure OpenAI, Ollama, Voyage
# =============================================================================
${existingVars['GRAPHITI_ENABLED'] ? `GRAPHITI_ENABLED=${existingVars['GRAPHITI_ENABLED']}` : '# GRAPHITI_ENABLED=false'}
# Provider Selection
${existingVars['GRAPHITI_LLM_PROVIDER'] ? `GRAPHITI_LLM_PROVIDER=${existingVars['GRAPHITI_LLM_PROVIDER']}` : '# GRAPHITI_LLM_PROVIDER=openai'}
${existingVars['GRAPHITI_EMBEDDER_PROVIDER'] ? `GRAPHITI_EMBEDDER_PROVIDER=${existingVars['GRAPHITI_EMBEDDER_PROVIDER']}` : '# GRAPHITI_EMBEDDER_PROVIDER=openai'}
# OpenAI Settings
${existingVars['OPENAI_API_KEY'] ? `OPENAI_API_KEY=${existingVars['OPENAI_API_KEY']}` : '# OPENAI_API_KEY='}
${existingVars['OPENAI_MODEL'] ? `OPENAI_MODEL=${existingVars['OPENAI_MODEL']}` : '# OPENAI_MODEL=gpt-4o-mini'}
${existingVars['OPENAI_EMBEDDING_MODEL'] ? `OPENAI_EMBEDDING_MODEL=${existingVars['OPENAI_EMBEDDING_MODEL']}` : '# OPENAI_EMBEDDING_MODEL=text-embedding-3-small'}
# Anthropic Settings (LLM only - use with Voyage or OpenAI for embeddings)
${existingVars['ANTHROPIC_API_KEY'] ? `ANTHROPIC_API_KEY=${existingVars['ANTHROPIC_API_KEY']}` : '# ANTHROPIC_API_KEY='}
${existingVars['GRAPHITI_ANTHROPIC_MODEL'] ? `GRAPHITI_ANTHROPIC_MODEL=${existingVars['GRAPHITI_ANTHROPIC_MODEL']}` : '# GRAPHITI_ANTHROPIC_MODEL=claude-sonnet-4-5-latest'}
# Azure OpenAI Settings
${existingVars['AZURE_OPENAI_API_KEY'] ? `AZURE_OPENAI_API_KEY=${existingVars['AZURE_OPENAI_API_KEY']}` : '# AZURE_OPENAI_API_KEY='}
${existingVars['AZURE_OPENAI_BASE_URL'] ? `AZURE_OPENAI_BASE_URL=${existingVars['AZURE_OPENAI_BASE_URL']}` : '# AZURE_OPENAI_BASE_URL='}
${existingVars['AZURE_OPENAI_LLM_DEPLOYMENT'] ? `AZURE_OPENAI_LLM_DEPLOYMENT=${existingVars['AZURE_OPENAI_LLM_DEPLOYMENT']}` : '# AZURE_OPENAI_LLM_DEPLOYMENT='}
${existingVars['AZURE_OPENAI_EMBEDDING_DEPLOYMENT'] ? `AZURE_OPENAI_EMBEDDING_DEPLOYMENT=${existingVars['AZURE_OPENAI_EMBEDDING_DEPLOYMENT']}` : '# AZURE_OPENAI_EMBEDDING_DEPLOYMENT='}
# Voyage AI Settings (Embeddings only - great with Anthropic)
${existingVars['VOYAGE_API_KEY'] ? `VOYAGE_API_KEY=${existingVars['VOYAGE_API_KEY']}` : '# VOYAGE_API_KEY='}
${existingVars['VOYAGE_EMBEDDING_MODEL'] ? `VOYAGE_EMBEDDING_MODEL=${existingVars['VOYAGE_EMBEDDING_MODEL']}` : '# VOYAGE_EMBEDDING_MODEL=voyage-3'}
# Google AI Settings (LLM and Embeddings - Gemini)
${existingVars['GOOGLE_API_KEY'] ? `GOOGLE_API_KEY=${existingVars['GOOGLE_API_KEY']}` : '# GOOGLE_API_KEY='}
${existingVars['GOOGLE_LLM_MODEL'] ? `GOOGLE_LLM_MODEL=${existingVars['GOOGLE_LLM_MODEL']}` : '# GOOGLE_LLM_MODEL=gemini-2.0-flash'}
${existingVars['GOOGLE_EMBEDDING_MODEL'] ? `GOOGLE_EMBEDDING_MODEL=${existingVars['GOOGLE_EMBEDDING_MODEL']}` : '# GOOGLE_EMBEDDING_MODEL=text-embedding-004'}
# Ollama Settings (Local - free)
${existingVars['OLLAMA_BASE_URL'] ? `OLLAMA_BASE_URL=${existingVars['OLLAMA_BASE_URL']}` : '# OLLAMA_BASE_URL=http://localhost:11434'}
${existingVars['OLLAMA_LLM_MODEL'] ? `OLLAMA_LLM_MODEL=${existingVars['OLLAMA_LLM_MODEL']}` : '# OLLAMA_LLM_MODEL='}
${existingVars['OLLAMA_EMBEDDING_MODEL'] ? `OLLAMA_EMBEDDING_MODEL=${existingVars['OLLAMA_EMBEDDING_MODEL']}` : '# OLLAMA_EMBEDDING_MODEL='}
${existingVars['OLLAMA_EMBEDDING_DIM'] ? `OLLAMA_EMBEDDING_DIM=${existingVars['OLLAMA_EMBEDDING_DIM']}` : '# OLLAMA_EMBEDDING_DIM=768'}
# FalkorDB Connection
${existingVars['GRAPHITI_FALKORDB_HOST'] ? `GRAPHITI_FALKORDB_HOST=${existingVars['GRAPHITI_FALKORDB_HOST']}` : '# GRAPHITI_FALKORDB_HOST=localhost'}
${existingVars['GRAPHITI_FALKORDB_PORT'] ? `GRAPHITI_FALKORDB_PORT=${existingVars['GRAPHITI_FALKORDB_PORT']}` : '# GRAPHITI_FALKORDB_PORT=6380'}
${existingVars['GRAPHITI_FALKORDB_PASSWORD'] ? `GRAPHITI_FALKORDB_PASSWORD=${existingVars['GRAPHITI_FALKORDB_PASSWORD']}` : '# GRAPHITI_FALKORDB_PASSWORD='}
@@ -216,6 +298,11 @@ ${existingVars['GRAPHITI_DATABASE'] ? `GRAPHITI_DATABASE=${existingVars['GRAPHIT
config.githubAutoSync = true;
}
// Git/Worktree config
if (vars['DEFAULT_BRANCH']) {
config.defaultBranch = vars['DEFAULT_BRANCH'];
}
if (vars['GRAPHITI_ENABLED']?.toLowerCase() === 'true') {
config.graphitiEnabled = true;
}
@@ -246,6 +333,45 @@ ${existingVars['GRAPHITI_DATABASE'] ? `GRAPHITI_DATABASE=${existingVars['GRAPHIT
config.enableFancyUi = false;
}
// Populate graphitiProviderConfig from .env file
const llmProvider = vars['GRAPHITI_LLM_PROVIDER'];
const embeddingProvider = vars['GRAPHITI_EMBEDDER_PROVIDER'];
if (llmProvider || embeddingProvider || vars['ANTHROPIC_API_KEY'] || vars['AZURE_OPENAI_API_KEY'] ||
vars['VOYAGE_API_KEY'] || vars['GOOGLE_API_KEY'] || vars['OLLAMA_BASE_URL']) {
config.graphitiProviderConfig = {
llmProvider: (llmProvider as 'openai' | 'anthropic' | 'azure_openai' | 'ollama' | 'google' | 'groq') || 'openai',
embeddingProvider: (embeddingProvider as 'openai' | 'voyage' | 'azure_openai' | 'ollama' | 'google' | 'huggingface') || 'openai',
// OpenAI
openaiApiKey: vars['OPENAI_API_KEY'],
openaiModel: vars['OPENAI_MODEL'],
openaiEmbeddingModel: vars['OPENAI_EMBEDDING_MODEL'],
// Anthropic
anthropicApiKey: vars['ANTHROPIC_API_KEY'],
anthropicModel: vars['GRAPHITI_ANTHROPIC_MODEL'],
// Azure OpenAI
azureOpenaiApiKey: vars['AZURE_OPENAI_API_KEY'],
azureOpenaiBaseUrl: vars['AZURE_OPENAI_BASE_URL'],
azureOpenaiLlmDeployment: vars['AZURE_OPENAI_LLM_DEPLOYMENT'],
azureOpenaiEmbeddingDeployment: vars['AZURE_OPENAI_EMBEDDING_DEPLOYMENT'],
// Voyage
voyageApiKey: vars['VOYAGE_API_KEY'],
voyageEmbeddingModel: vars['VOYAGE_EMBEDDING_MODEL'],
// Google
googleApiKey: vars['GOOGLE_API_KEY'],
googleLlmModel: vars['GOOGLE_LLM_MODEL'],
googleEmbeddingModel: vars['GOOGLE_EMBEDDING_MODEL'],
// Ollama
ollamaBaseUrl: vars['OLLAMA_BASE_URL'],
ollamaLlmModel: vars['OLLAMA_LLM_MODEL'],
ollamaEmbeddingModel: vars['OLLAMA_EMBEDDING_MODEL'],
ollamaEmbeddingDim: vars['OLLAMA_EMBEDDING_DIM'] ? parseInt(vars['OLLAMA_EMBEDDING_DIM'], 10) : undefined,
// FalkorDB
falkorDbHost: vars['GRAPHITI_FALKORDB_HOST'],
falkorDbPort: vars['GRAPHITI_FALKORDB_PORT'] ? parseInt(vars['GRAPHITI_FALKORDB_PORT'], 10) : undefined,
falkorDbPassword: vars['GRAPHITI_FALKORDB_PASSWORD'],
};
}
return { success: true, data: config };
}
);
@@ -304,15 +430,15 @@ ${existingVars['GRAPHITI_DATABASE'] ? `GRAPHITI_DATABASE=${existingVars['GRAPHIT
shell: true
});
let stdout = '';
let stderr = '';
let _stdout = '';
let _stderr = '';
proc.stdout?.on('data', (data: Buffer) => {
stdout += data.toString();
_stdout += data.toString();
});
proc.stderr?.on('data', (data: Buffer) => {
stderr += data.toString();
_stderr += data.toString();
});
proc.on('close', (code: number | null) => {
@@ -8,8 +8,8 @@ import type { IPCResult, FileNode } from '../../shared/types';
const IGNORED_DIRS = new Set([
'node_modules', '.git', '__pycache__', 'dist', 'build',
'.next', '.nuxt', 'coverage', '.cache', '.venv', 'venv',
'.idea', '.vscode', 'out', '.turbo', '.auto-claude',
'.worktrees', 'vendor', 'target', '.gradle', '.maven'
'out', '.turbo', '.worktrees',
'vendor', 'target', '.gradle', '.maven'
]);
/**
@@ -29,8 +29,11 @@ export function registerFileHandlers(): void {
// Filter and map entries
const nodes: FileNode[] = [];
for (const entry of entries) {
// Skip hidden files (except .env which is often useful)
if (entry.name.startsWith('.') && entry.name !== '.env') continue;
// Skip hidden files (not directories) except useful ones like .env, .gitignore
if (!entry.isDirectory() && entry.name.startsWith('.') &&
!['.env', '.gitignore', '.env.example', '.env.local'].includes(entry.name)) {
continue;
}
// Skip ignored directories
if (entry.isDirectory() && IGNORED_DIRS.has(entry.name)) continue;
@@ -0,0 +1,548 @@
/**
* Unit tests for GitHub OAuth handlers
* Tests device code parsing, shell.openExternal handling, and error recovery
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'events';
// Mock child_process before importing
const mockSpawn = vi.fn();
const mockExecSync = vi.fn();
const mockExecFileSync = vi.fn();
vi.mock('child_process', () => ({
spawn: (...args: unknown[]) => mockSpawn(...args),
execSync: (...args: unknown[]) => mockExecSync(...args),
execFileSync: (...args: unknown[]) => mockExecFileSync(...args)
}));
// Mock shell.openExternal
const mockOpenExternal = vi.fn();
vi.mock('electron', () => {
const mockIpcMain = new (class extends EventEmitter {
private handlers: Map<string, Function> = new Map();
handle(channel: string, handler: Function): void {
this.handlers.set(channel, handler);
}
removeHandler(channel: string): void {
this.handlers.delete(channel);
}
async invokeHandler(channel: string, event: unknown, ...args: unknown[]): Promise<unknown> {
const handler = this.handlers.get(channel);
if (handler) {
return handler(event, ...args);
}
throw new Error(`No handler for channel: ${channel}`);
}
getHandler(channel: string): Function | undefined {
return this.handlers.get(channel);
}
})();
return {
ipcMain: mockIpcMain,
shell: {
openExternal: (...args: unknown[]) => mockOpenExternal(...args)
}
};
});
// Mock @electron-toolkit/utils
vi.mock('@electron-toolkit/utils', () => ({
is: {
dev: true,
windows: process.platform === 'win32',
macos: process.platform === 'darwin',
linux: process.platform === 'linux'
}
}));
// Create mock process for spawn
function createMockProcess(): EventEmitter & {
stdout: EventEmitter | null;
stderr: EventEmitter | null;
stdin: { write: ReturnType<typeof vi.fn>; end: ReturnType<typeof vi.fn> } | null;
} {
const proc = new EventEmitter() as EventEmitter & {
stdout: EventEmitter | null;
stderr: EventEmitter | null;
stdin: { write: ReturnType<typeof vi.fn>; end: ReturnType<typeof vi.fn> } | null;
};
proc.stdout = new EventEmitter();
proc.stderr = new EventEmitter();
proc.stdin = { write: vi.fn(), end: vi.fn() };
return proc;
}
describe('GitHub OAuth Handlers', () => {
let ipcMain: EventEmitter & {
handlers: Map<string, Function>;
invokeHandler: (channel: string, event: unknown, ...args: unknown[]) => Promise<unknown>;
getHandler: (channel: string) => Function | undefined;
};
beforeEach(async () => {
vi.clearAllMocks();
vi.resetModules();
// Get mocked ipcMain
const electron = await import('electron');
ipcMain = electron.ipcMain as unknown as typeof ipcMain;
});
afterEach(() => {
vi.clearAllMocks();
});
describe('Device Code Parsing', () => {
it('should parse device code from standard gh CLI output format', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
mockOpenExternal.mockResolvedValue(undefined);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
// Start the handler
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
// Simulate gh CLI output with device code
mockProcess.stderr?.emit('data', '! First copy your one-time code: ABCD-1234\n');
mockProcess.stderr?.emit('data', '- Press Enter to open github.com in your browser...\n');
// Complete the process
mockProcess.emit('close', 0);
const result = await resultPromise;
expect(result).toHaveProperty('success', true);
expect(result).toHaveProperty('data');
const data = (result as { data: { deviceCode: string } }).data;
expect(data.deviceCode).toBe('ABCD-1234');
});
it('should parse device code from alternate output format (lowercase "code")', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
mockOpenExternal.mockResolvedValue(undefined);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
// Alternate format: "code: XXXX-XXXX" without "one-time"
mockProcess.stderr?.emit('data', 'Enter the code: EFGH-5678\n');
mockProcess.emit('close', 0);
const result = await resultPromise;
expect(result).toHaveProperty('success', true);
const data = (result as { data: { deviceCode: string } }).data;
expect(data.deviceCode).toBe('EFGH-5678');
});
it('should parse device code from stdout (not just stderr)', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
mockOpenExternal.mockResolvedValue(undefined);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
// Device code in stdout instead of stderr
mockProcess.stdout?.emit('data', '! First copy your one-time code: IJKL-9012\n');
mockProcess.emit('close', 0);
const result = await resultPromise;
expect(result).toHaveProperty('success', true);
const data = (result as { data: { deviceCode: string } }).data;
expect(data.deviceCode).toBe('IJKL-9012');
});
it('should handle output without device code gracefully', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
// Output without device code
mockProcess.stderr?.emit('data', 'Some other message\n');
mockProcess.emit('close', 0);
const result = await resultPromise;
expect(result).toHaveProperty('success', true);
const data = (result as { data: { deviceCode?: string } }).data;
expect(data.deviceCode).toBeUndefined();
});
it('should extract URL from output containing https://github.com/login/device', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
mockOpenExternal.mockResolvedValue(undefined);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
mockProcess.stderr?.emit('data', '! First copy your one-time code: MNOP-3456\n');
mockProcess.stderr?.emit('data', 'Then visit https://github.com/login/device to authenticate\n');
mockProcess.emit('close', 0);
const result = await resultPromise;
expect(result).toHaveProperty('success', true);
const data = (result as { data: { authUrl: string } }).data;
expect(data.authUrl).toBe('https://github.com/login/device');
});
});
describe('shell.openExternal Handling', () => {
it('should call shell.openExternal with extracted URL when device code found', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
mockOpenExternal.mockResolvedValue(undefined);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
mockProcess.stderr?.emit('data', '! First copy your one-time code: QRST-7890\n');
// Wait for next tick to allow async browser opening
await new Promise(resolve => setTimeout(resolve, 10));
mockProcess.emit('close', 0);
await resultPromise;
expect(mockOpenExternal).toHaveBeenCalledWith('https://github.com/login/device');
});
it('should set browserOpened to true when shell.openExternal succeeds', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
mockOpenExternal.mockResolvedValue(undefined);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
mockProcess.stderr?.emit('data', '! First copy your one-time code: UVWX-1234\n');
// Wait for async browser opening
await new Promise(resolve => setTimeout(resolve, 10));
mockProcess.emit('close', 0);
const result = await resultPromise;
expect(result).toHaveProperty('success', true);
const data = (result as { data: { browserOpened: boolean } }).data;
expect(data.browserOpened).toBe(true);
});
it('should set browserOpened to false when shell.openExternal fails', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
mockOpenExternal.mockRejectedValue(new Error('Failed to open browser'));
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
mockProcess.stderr?.emit('data', '! First copy your one-time code: YZAB-5678\n');
// Wait for async browser opening to fail
await new Promise(resolve => setTimeout(resolve, 10));
mockProcess.emit('close', 0);
const result = await resultPromise;
expect(result).toHaveProperty('success', true);
const data = (result as { data: { browserOpened: boolean } }).data;
expect(data.browserOpened).toBe(false);
});
it('should provide fallbackUrl when browser fails to open', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
mockOpenExternal.mockRejectedValue(new Error('Failed to open browser'));
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
mockProcess.stderr?.emit('data', '! First copy your one-time code: CDEF-9012\n');
// Wait for async browser opening to fail
await new Promise(resolve => setTimeout(resolve, 10));
mockProcess.emit('close', 0);
const result = await resultPromise;
expect(result).toHaveProperty('success', true);
const data = (result as { data: { fallbackUrl?: string } }).data;
expect(data.fallbackUrl).toBe('https://github.com/login/device');
});
it('should not provide fallbackUrl when browser opens successfully', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
mockOpenExternal.mockResolvedValue(undefined);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
mockProcess.stderr?.emit('data', '! First copy your one-time code: GHIJ-3456\n');
// Wait for async browser opening
await new Promise(resolve => setTimeout(resolve, 10));
mockProcess.emit('close', 0);
const result = await resultPromise;
expect(result).toHaveProperty('success', true);
const data = (result as { data: { fallbackUrl?: string } }).data;
expect(data.fallbackUrl).toBeUndefined();
});
});
describe('Error Handling', () => {
it('should handle gh CLI process error', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
// Emit error event
mockProcess.emit('error', new Error('spawn gh ENOENT'));
const result = await resultPromise;
expect(result).toHaveProperty('success', false);
expect(result).toHaveProperty('error', 'spawn gh ENOENT');
const data = (result as { data: { fallbackUrl: string } }).data;
expect(data.fallbackUrl).toBe('https://github.com/login/device');
});
it('should handle non-zero exit code', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
mockProcess.stderr?.emit('data', 'error: some authentication error\n');
mockProcess.emit('close', 1);
const result = await resultPromise;
expect(result).toHaveProperty('success', false);
const data = (result as { data: { fallbackUrl: string } }).data;
expect(data.fallbackUrl).toBe('https://github.com/login/device');
});
it('should include device code in error result if it was extracted before failure', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
mockOpenExternal.mockResolvedValue(undefined);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
// Device code output followed by failure
mockProcess.stderr?.emit('data', '! First copy your one-time code: KLMN-7890\n');
// Wait for async browser opening
await new Promise(resolve => setTimeout(resolve, 10));
mockProcess.stderr?.emit('data', 'error: authentication failed\n');
mockProcess.emit('close', 1);
const result = await resultPromise;
expect(result).toHaveProperty('success', false);
const data = (result as { data: { deviceCode: string; fallbackUrl: string } }).data;
expect(data.deviceCode).toBe('KLMN-7890');
expect(data.fallbackUrl).toBe('https://github.com/login/device');
});
it('should provide user-friendly error message on process spawn failure', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
mockProcess.emit('error', new Error('spawn gh ENOENT'));
const result = await resultPromise;
expect(result).toHaveProperty('success', false);
const data = (result as { data: { message: string } }).data;
expect(data.message).toContain('Failed to start GitHub CLI');
});
});
describe('gh CLI Check Handler', () => {
it('should return installed: true when gh CLI is found', async () => {
mockExecSync.mockImplementation((cmd: string) => {
if (cmd.includes('which gh') || cmd.includes('where gh')) {
return '/usr/local/bin/gh\n';
}
if (cmd === 'gh --version') {
return 'gh version 2.65.0 (2024-01-15)\n';
}
return '';
});
const { registerCheckGhCli } = await import('../oauth-handlers');
registerCheckGhCli();
const result = await ipcMain.invokeHandler('github:checkCli', {});
expect(result).toHaveProperty('success', true);
const data = (result as { data: { installed: boolean; version: string } }).data;
expect(data.installed).toBe(true);
expect(data.version).toContain('gh version');
});
it('should return installed: false when gh CLI is not found', async () => {
mockExecSync.mockImplementation(() => {
throw new Error('Command not found');
});
const { registerCheckGhCli } = await import('../oauth-handlers');
registerCheckGhCli();
const result = await ipcMain.invokeHandler('github:checkCli', {});
expect(result).toHaveProperty('success', true);
const data = (result as { data: { installed: boolean } }).data;
expect(data.installed).toBe(false);
});
});
describe('gh Auth Check Handler', () => {
it('should return authenticated: true with username when logged in', async () => {
mockExecSync.mockImplementation((cmd: string) => {
if (cmd === 'gh auth status') {
return 'Logged in to github.com as testuser\n';
}
if (cmd === 'gh api user --jq .login') {
return 'testuser\n';
}
return '';
});
const { registerCheckGhAuth } = await import('../oauth-handlers');
registerCheckGhAuth();
const result = await ipcMain.invokeHandler('github:checkAuth', {});
expect(result).toHaveProperty('success', true);
const data = (result as { data: { authenticated: boolean; username: string } }).data;
expect(data.authenticated).toBe(true);
expect(data.username).toBe('testuser');
});
it('should return authenticated: false when not logged in', async () => {
mockExecSync.mockImplementation(() => {
throw new Error('You are not logged into any GitHub hosts');
});
const { registerCheckGhAuth } = await import('../oauth-handlers');
registerCheckGhAuth();
const result = await ipcMain.invokeHandler('github:checkAuth', {});
expect(result).toHaveProperty('success', true);
const data = (result as { data: { authenticated: boolean } }).data;
expect(data.authenticated).toBe(false);
});
});
describe('Spawn Arguments', () => {
it('should spawn gh with correct auth login arguments', async () => {
const mockProcess = createMockProcess();
mockSpawn.mockReturnValue(mockProcess);
const { registerStartGhAuth } = await import('../oauth-handlers');
registerStartGhAuth();
ipcMain.invokeHandler('github:startAuth', {});
expect(mockSpawn).toHaveBeenCalledWith(
'gh',
['auth', 'login', '--web', '--scopes', 'repo'],
expect.objectContaining({
stdio: ['pipe', 'pipe', 'pipe']
})
);
});
});
describe('Repository Validation', () => {
it('should reject invalid repository format', async () => {
const { registerGetGitHubBranches } = await import('../oauth-handlers');
registerGetGitHubBranches();
// Test with injection attempt
const result = await ipcMain.invokeHandler(
'github:getBranches',
{},
'owner/repo; rm -rf /',
'token'
);
expect(result).toHaveProperty('success', false);
expect(result).toHaveProperty('error', 'Invalid repository format. Expected: owner/repo');
});
it('should accept valid repository format', async () => {
mockExecFileSync.mockReturnValue('main\nfeature-branch\n');
const { registerGetGitHubBranches } = await import('../oauth-handlers');
registerGetGitHubBranches();
const result = await ipcMain.invokeHandler(
'github:getBranches',
{},
'valid-owner/valid-repo',
'token'
);
expect(result).toHaveProperty('success', true);
const data = (result as { data: string[] }).data;
expect(data).toContain('main');
expect(data).toContain('feature-branch');
});
});
});
@@ -47,11 +47,12 @@ export function registerImportIssues(agentManager: AgentManager): void {
};
// Build description with metadata
const labels = issue.labels.map(l => l.name).join(', ');
const labelNames = issue.labels.map(l => l.name);
const labelsString = labelNames.join(', ');
const description = `# ${issue.title}
**GitHub Issue:** [#${issue.number}](${issue.html_url})
${labels ? `**Labels:** ${labels}` : ''}
${labelsString ? `**Labels:** ${labelsString}` : ''}
## Description
@@ -64,7 +65,8 @@ ${issue.body || 'No description provided.'}
issue.number,
issue.title,
description,
issue.html_url
issue.html_url,
labelNames
);
// Start spec creation with the existing spec directory
@@ -66,7 +66,7 @@ export function registerInvestigateIssue(
): void {
ipcMain.on(
IPC_CHANNELS.GITHUB_INVESTIGATE_ISSUE,
async (_, projectId: string, issueNumber: number) => {
async (_, projectId: string, issueNumber: number, selectedCommentIds?: number[]) => {
const mainWindow = getMainWindow();
if (!mainWindow) return;
@@ -104,11 +104,16 @@ export function registerInvestigateIssue(
};
// Fetch issue comments for more context
const comments = await githubFetch(
const allComments = await githubFetch(
config.token,
`/repos/${config.repo}/issues/${issueNumber}/comments`
) as GitHubAPIComment[];
// Filter comments based on selection (if provided)
const comments = selectedCommentIds && selectedCommentIds.length > 0
? allComments.filter(c => selectedCommentIds.includes(c.id))
: allComments;
// Build context for the AI investigation
const labels = issue.labels.map(l => l.name);
const issueContext = buildIssueContext(
@@ -141,17 +146,13 @@ export function registerInvestigateIssue(
issue.number,
issue.title,
taskDescription,
issue.html_url
issue.html_url,
labels
);
// Start spec creation with the existing spec directory
agentManager.startSpecCreation(
specData.specId,
project.path,
specData.taskDescription,
specData.specDir,
specData.metadata
);
// NOTE: We intentionally do NOT call agentManager.startSpecCreation() here
// This allows the task to stay in "backlog" status until the user manually starts it
// Previously, calling startSpecCreation would auto-start the task immediately
// Phase 3: Creating task
sendProgress(mainWindow, projectId, {
@@ -6,8 +6,8 @@ import { ipcMain } from 'electron';
import { IPC_CHANNELS } from '../../../shared/constants';
import type { IPCResult, GitHubIssue } from '../../../shared/types';
import { projectStore } from '../../project-store';
import { getGitHubConfig, githubFetch } from './utils';
import type { GitHubAPIIssue } from './types';
import { getGitHubConfig, githubFetch, normalizeRepoReference } from './utils';
import type { GitHubAPIIssue, GitHubAPIComment } from './types';
/**
* Transform GitHub API issue to application format
@@ -57,16 +57,32 @@ export function registerGetIssues(): void {
}
try {
const normalizedRepo = normalizeRepoReference(config.repo);
if (!normalizedRepo) {
return {
success: false,
error: 'Invalid repository format. Use owner/repo or GitHub URL.'
};
}
const issues = await githubFetch(
config.token,
`/repos/${config.repo}/issues?state=${state}&per_page=100&sort=updated`
) as GitHubAPIIssue[];
`/repos/${normalizedRepo}/issues?state=${state}&per_page=100&sort=updated`
);
// Ensure issues is an array
if (!Array.isArray(issues)) {
return {
success: false,
error: 'Unexpected response format from GitHub API'
};
}
// Filter out pull requests
const issuesOnly = issues.filter(issue => !issue.pull_request);
const issuesOnly = issues.filter((issue: GitHubAPIIssue) => !issue.pull_request);
const result: GitHubIssue[] = issuesOnly.map(issue =>
transformIssue(issue, config.repo)
const result: GitHubIssue[] = issuesOnly.map((issue: GitHubAPIIssue) =>
transformIssue(issue, normalizedRepo)
);
return { success: true, data: result };
@@ -98,12 +114,20 @@ export function registerGetIssue(): void {
}
try {
const normalizedRepo = normalizeRepoReference(config.repo);
if (!normalizedRepo) {
return {
success: false,
error: 'Invalid repository format. Use owner/repo or GitHub URL.'
};
}
const issue = await githubFetch(
config.token,
`/repos/${config.repo}/issues/${issueNumber}`
`/repos/${normalizedRepo}/issues/${issueNumber}`
) as GitHubAPIIssue;
const result = transformIssue(issue, config.repo);
const result = transformIssue(issue, normalizedRepo);
return { success: true, data: result };
} catch (error) {
@@ -116,10 +140,53 @@ export function registerGetIssue(): void {
);
}
/**
* Get comments for a specific issue
*/
export function registerGetIssueComments(): void {
ipcMain.handle(
IPC_CHANNELS.GITHUB_GET_ISSUE_COMMENTS,
async (_, projectId: string, issueNumber: number): Promise<IPCResult<GitHubAPIComment[]>> => {
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: 'Project not found' };
}
const config = getGitHubConfig(project);
if (!config) {
return { success: false, error: 'No GitHub token or repository configured' };
}
try {
const normalizedRepo = normalizeRepoReference(config.repo);
if (!normalizedRepo) {
return {
success: false,
error: 'Invalid repository format. Use owner/repo or GitHub URL.'
};
}
const comments = await githubFetch(
config.token,
`/repos/${normalizedRepo}/issues/${issueNumber}/comments`
) as GitHubAPIComment[];
return { success: true, data: comments };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to fetch issue comments'
};
}
}
);
}
/**
* Register all issue-related handlers
*/
export function registerIssueHandlers(): void {
registerGetIssues();
registerGetIssue();
registerGetIssueComments();
}
@@ -3,8 +3,8 @@
* Provides a simpler OAuth flow than manual PAT creation
*/
import { ipcMain } from 'electron';
import { execSync, spawn } from 'child_process';
import { ipcMain, shell } from 'electron';
import { execSync, execFileSync, spawn } from 'child_process';
import { IPC_CHANNELS } from '../../../shared/constants';
import type { IPCResult } from '../../../shared/types';
@@ -14,13 +14,83 @@ const DEBUG = process.env.DEBUG === 'true' || process.env.NODE_ENV === 'developm
function debugLog(message: string, data?: unknown): void {
if (DEBUG) {
if (data !== undefined) {
console.log(`[GitHub OAuth] ${message}`, data);
console.warn(`[GitHub OAuth] ${message}`, data);
} else {
console.log(`[GitHub OAuth] ${message}`);
console.warn(`[GitHub OAuth] ${message}`);
}
}
}
// Regex pattern to validate GitHub repository format (owner/repo)
// Allows alphanumeric characters, hyphens, underscores, and periods
const GITHUB_REPO_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
/**
* Validate that a repository string matches the expected owner/repo format
* Prevents command injection by rejecting strings with shell metacharacters
*/
function isValidGitHubRepo(repo: string): boolean {
return GITHUB_REPO_PATTERN.test(repo);
}
// Regex patterns for parsing device code from gh CLI output
// Expected format: "! First copy your one-time code: XXXX-XXXX"
const DEVICE_CODE_PATTERN = /(?:one-time code|code):\s*([A-Z0-9]{4}-[A-Z0-9]{4})/i;
// GitHub device flow URL pattern
const DEVICE_URL_PATTERN = /https:\/\/github\.com\/login\/device/i;
// Default GitHub device flow URL
const GITHUB_DEVICE_URL = 'https://github.com/login/device';
/**
* Parse device code from gh CLI stdout output
* Returns the device code (format: XXXX-XXXX) if found, null otherwise
*/
function parseDeviceCode(output: string): string | null {
const match = output.match(DEVICE_CODE_PATTERN);
if (match && match[1]) {
debugLog('Parsed device code:', match[1]);
return match[1];
}
return null;
}
/**
* Parse device URL from gh CLI output
* Returns the URL if found, or the default GitHub device URL
*/
function parseDeviceUrl(output: string): string {
const match = output.match(DEVICE_URL_PATTERN);
if (match) {
debugLog('Found device URL in output:', match[0]);
return match[0];
}
// Default to standard GitHub device flow URL
return GITHUB_DEVICE_URL;
}
/**
* Result of parsing device flow output from gh CLI
*/
interface DeviceFlowInfo {
deviceCode: string | null;
authUrl: string;
}
/**
* Parse both device code and URL from combined gh CLI output
* Searches through both stdout and stderr as gh may output to either
*/
function parseDeviceFlowOutput(stdout: string, stderr: string): DeviceFlowInfo {
const combinedOutput = `${stdout}\n${stderr}`;
return {
deviceCode: parseDeviceCode(combinedOutput),
authUrl: parseDeviceUrl(combinedOutput)
};
}
/**
* Check if gh CLI is installed
*/
@@ -102,14 +172,31 @@ export function registerCheckGhAuth(): void {
);
}
/**
* Result type for GitHub auth start, including device flow information
*/
interface GitHubAuthStartResult {
success: boolean;
message?: string;
deviceCode?: string;
authUrl?: string;
browserOpened?: boolean;
/**
* Fallback URL provided when browser launch fails.
* The frontend should display this URL so users can manually navigate to complete auth.
*/
fallbackUrl?: string;
}
/**
* Start GitHub OAuth flow using gh CLI
* This will open the browser for device flow authentication
* This will extract the device code from gh CLI output and open the browser
* using Electron's shell.openExternal (bypasses macOS child process restrictions)
*/
export function registerStartGhAuth(): void {
ipcMain.handle(
IPC_CHANNELS.GITHUB_START_AUTH,
async (): Promise<IPCResult<{ success: boolean; message?: string }>> => {
async (): Promise<IPCResult<GitHubAuthStartResult>> => {
debugLog('startGitHubAuth handler called');
return new Promise((resolve) => {
try {
@@ -123,17 +210,60 @@ export function registerStartGhAuth(): void {
let output = '';
let errorOutput = '';
let deviceCodeExtracted = false;
let extractedDeviceCode: string | null = null;
let extractedAuthUrl: string = GITHUB_DEVICE_URL;
let browserOpenedSuccessfully = false;
let extractionInProgress = false;
// Function to attempt device code extraction and browser opening
// Uses mutex pattern to prevent race conditions from concurrent data handlers
const tryExtractAndOpenBrowser = async () => {
if (deviceCodeExtracted || extractionInProgress) return;
extractionInProgress = true;
const deviceFlowInfo = parseDeviceFlowOutput(output, errorOutput);
if (deviceFlowInfo.deviceCode) {
deviceCodeExtracted = true;
extractedDeviceCode = deviceFlowInfo.deviceCode;
extractedAuthUrl = deviceFlowInfo.authUrl;
debugLog('Device code extracted:', extractedDeviceCode);
debugLog('Auth URL:', extractedAuthUrl);
// Open browser using Electron's shell.openExternal
// This bypasses macOS child process restrictions that block gh CLI's browser launch
try {
await shell.openExternal(extractedAuthUrl);
browserOpenedSuccessfully = true;
debugLog('Browser opened successfully via shell.openExternal');
} catch (browserError) {
debugLog('Failed to open browser:', browserError instanceof Error ? browserError.message : browserError);
browserOpenedSuccessfully = false;
// Don't fail here - we'll return the device code so user can manually navigate
}
} else {
// No device code found yet, allow next data chunk to try again
extractionInProgress = false;
}
};
ghProcess.stdout?.on('data', (data) => {
const chunk = data.toString();
output += chunk;
debugLog('gh stdout:', chunk);
// Try to extract device code as data comes in
// Use void to explicitly ignore promise
void tryExtractAndOpenBrowser();
});
ghProcess.stderr?.on('data', (data) => {
const chunk = data.toString();
errorOutput += chunk;
debugLog('gh stderr:', chunk);
// gh often outputs to stderr, so check there too
void tryExtractAndOpenBrowser();
});
ghProcess.on('close', (code) => {
@@ -142,17 +272,39 @@ export function registerStartGhAuth(): void {
debugLog('Full stderr:', errorOutput);
if (code === 0) {
// Success case - include fallbackUrl if browser failed to open
// so the user can manually navigate if needed
resolve({
success: true,
data: {
success: true,
message: 'Successfully authenticated with GitHub'
message: browserOpenedSuccessfully
? 'Successfully authenticated with GitHub'
: 'Authentication successful. Browser could not be opened automatically.',
deviceCode: extractedDeviceCode || undefined,
authUrl: extractedAuthUrl,
browserOpened: browserOpenedSuccessfully,
// Provide fallback URL when browser failed to open
fallbackUrl: !browserOpenedSuccessfully ? extractedAuthUrl : undefined
}
});
} else {
// Even if auth failed, return device code info if we extracted it
// This allows user to retry manually with the fallback URL
const fallbackUrlForManualAuth = extractedDeviceCode ? extractedAuthUrl : GITHUB_DEVICE_URL;
resolve({
success: false,
error: errorOutput || `Authentication failed with exit code ${code}`
error: errorOutput || `Authentication failed with exit code ${code}`,
data: {
success: false,
deviceCode: extractedDeviceCode || undefined,
authUrl: extractedAuthUrl,
browserOpened: browserOpenedSuccessfully,
// Always provide fallback URL on failure for manual recovery
fallbackUrl: fallbackUrlForManualAuth,
message: 'Authentication failed. Please visit the URL manually to complete authentication.'
}
});
}
});
@@ -161,14 +313,28 @@ export function registerStartGhAuth(): void {
debugLog('gh process error:', error.message);
resolve({
success: false,
error: error.message
error: error.message,
data: {
success: false,
browserOpened: false,
// Provide fallback URL so user can attempt manual auth
fallbackUrl: GITHUB_DEVICE_URL,
message: 'Failed to start GitHub CLI. Please visit the URL manually to authenticate.'
}
});
});
} catch (error) {
debugLog('Exception in startGitHubAuth:', error instanceof Error ? error.message : error);
resolve({
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
error: error instanceof Error ? error.message : 'Unknown error',
data: {
success: false,
browserOpened: false,
// Provide fallback URL for manual authentication recovery
fallbackUrl: GITHUB_DEVICE_URL,
message: 'An unexpected error occurred. Please visit the URL manually to authenticate.'
}
});
}
});
@@ -296,6 +462,106 @@ export function registerListUserRepos(): void {
);
}
/**
* Detect GitHub repository from git remote origin
*/
export function registerDetectGitHubRepo(): void {
ipcMain.handle(
IPC_CHANNELS.GITHUB_DETECT_REPO,
async (_event: Electron.IpcMainInvokeEvent, projectPath: string): Promise<IPCResult<string>> => {
debugLog('detectGitHubRepo handler called', { projectPath });
try {
// Get the remote URL
debugLog('Running: git remote get-url origin');
const remoteUrl = execSync('git remote get-url origin', {
encoding: 'utf-8',
cwd: projectPath,
stdio: 'pipe'
}).trim();
debugLog('Remote URL:', remoteUrl);
// Parse GitHub repo from URL
// Formats:
// - https://github.com/owner/repo.git
// - git@github.com:owner/repo.git
// - https://github.com/owner/repo
const match = remoteUrl.match(/github\.com[/:]([^/]+\/[^/]+?)(?:\.git)?$/);
if (match) {
const repo = match[1];
debugLog('Detected repo:', repo);
return {
success: true,
data: repo
};
}
debugLog('Could not parse GitHub repo from URL');
return {
success: false,
error: 'Remote URL is not a GitHub repository'
};
} catch (error) {
debugLog('Failed to detect repo:', error instanceof Error ? error.message : error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to detect GitHub repository'
};
}
}
);
}
/**
* Get branches from GitHub repository
*/
export function registerGetGitHubBranches(): void {
ipcMain.handle(
IPC_CHANNELS.GITHUB_GET_BRANCHES,
async (_event: Electron.IpcMainInvokeEvent, repo: string, _token: string): Promise<IPCResult<string[]>> => {
debugLog('getGitHubBranches handler called', { repo });
// Validate repo format to prevent command injection
if (!isValidGitHubRepo(repo)) {
debugLog('Invalid repo format rejected:', repo);
return {
success: false,
error: 'Invalid repository format. Expected: owner/repo'
};
}
try {
// Use gh CLI to list branches (uses authenticated session)
// Use execFileSync with separate arguments to avoid shell injection
const apiEndpoint = `repos/${repo}/branches`;
debugLog(`Running: gh api ${apiEndpoint} --paginate --jq '.[].name'`);
const output = execFileSync(
'gh',
['api', apiEndpoint, '--paginate', '--jq', '.[].name'],
{
encoding: 'utf-8',
stdio: 'pipe'
}
);
const branches = output.trim().split('\n').filter(b => b.length > 0);
debugLog('Found branches:', branches.length);
return {
success: true,
data: branches
};
} catch (error) {
debugLog('Failed to get branches:', error instanceof Error ? error.message : error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to get branches'
};
}
}
);
}
/**
* Register all GitHub OAuth handlers
*/
@@ -307,5 +573,7 @@ export function registerGithubOAuthHandlers(): void {
registerGetGhToken();
registerGetGhUser();
registerListUserRepos();
registerDetectGitHubRepo();
registerGetGitHubBranches();
debugLog('GitHub OAuth handlers registered');
}
@@ -4,9 +4,12 @@
import { ipcMain } from 'electron';
import { execSync } from 'child_process';
import { existsSync, readFileSync } from 'fs';
import path from 'path';
import { IPC_CHANNELS } from '../../../shared/constants';
import type { IPCResult } from '../../../shared/types';
import type { IPCResult, GitCommit, VersionSuggestion } from '../../../shared/types';
import { projectStore } from '../../project-store';
import { changelogService } from '../../changelog-service';
import type { ReleaseOptions } from './types';
/**
@@ -118,9 +121,146 @@ export function registerCreateRelease(): void {
);
}
/**
* Get the latest git tag in the repository
*/
function getLatestTag(projectPath: string): string | null {
try {
const tag = execSync('git describe --tags --abbrev=0 2>/dev/null || echo ""', {
cwd: projectPath,
encoding: 'utf-8'
}).trim();
return tag || null;
} catch {
return null;
}
}
/**
* Get commits since a specific tag (or all commits if no tag)
*/
function getCommitsSinceTag(projectPath: string, tag: string | null): GitCommit[] {
try {
const range = tag ? `${tag}..HEAD` : 'HEAD';
const format = '%H|%s|%an|%ae|%aI';
const output = execSync(`git log ${range} --pretty=format:"${format}"`, {
cwd: projectPath,
encoding: 'utf-8'
}).trim();
if (!output) return [];
return output.split('\n').map(line => {
const [fullHash, subject, authorName, authorEmail, date] = line.split('|');
return {
hash: fullHash.substring(0, 7),
fullHash,
subject,
author: authorName,
authorEmail,
date
};
});
} catch {
return [];
}
}
/**
* Get current version from package.json
*/
function getCurrentVersion(projectPath: string): string {
try {
const pkgPath = path.join(projectPath, 'package.json');
if (!existsSync(pkgPath)) {
return '0.0.0';
}
const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
return pkg.version || '0.0.0';
} catch {
return '0.0.0';
}
}
/**
* Suggest version for release using AI analysis of commits
*/
export function registerSuggestVersion(): void {
ipcMain.handle(
IPC_CHANNELS.RELEASE_SUGGEST_VERSION,
async (_, projectId: string): Promise<IPCResult<VersionSuggestion>> => {
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: 'Project not found' };
}
try {
// Get current version from package.json
const currentVersion = getCurrentVersion(project.path);
// Get latest tag
const latestTag = getLatestTag(project.path);
// Get commits since last tag
const commits = getCommitsSinceTag(project.path, latestTag);
if (commits.length === 0) {
// No commits since last release, suggest patch bump
const [major, minor, patch] = currentVersion.split('.').map(Number);
return {
success: true,
data: {
suggestedVersion: `${major}.${minor}.${patch + 1}`,
currentVersion,
bumpType: 'patch',
reason: 'No new commits since last release',
commitCount: 0
}
};
}
// Use AI to analyze commits and suggest version
const suggestion = await changelogService.suggestVersionFromCommits(
project.path,
commits,
currentVersion
);
return {
success: true,
data: {
suggestedVersion: suggestion.version,
currentVersion,
bumpType: suggestion.reason.includes('breaking') ? 'major' :
suggestion.reason.includes('feature') || suggestion.reason.includes('minor') ? 'minor' : 'patch',
reason: suggestion.reason,
commitCount: commits.length
}
};
} catch (_error) {
// Fallback to patch bump on error
const currentVersion = getCurrentVersion(project.path);
const [major, minor, patch] = currentVersion.split('.').map(Number);
return {
success: true,
data: {
suggestedVersion: `${major}.${minor}.${patch + 1}`,
currentVersion,
bumpType: 'patch',
reason: 'Fallback suggestion (AI analysis unavailable)',
commitCount: 0
}
};
}
}
);
}
/**
* Register all release-related handlers
*/
export function registerReleaseHandlers(): void {
registerCreateRelease();
registerSuggestVersion();
}
@@ -6,7 +6,7 @@ import { ipcMain } from 'electron';
import { IPC_CHANNELS } from '../../../shared/constants';
import type { IPCResult, GitHubRepository, GitHubSyncStatus } from '../../../shared/types';
import { projectStore } from '../../project-store';
import { getGitHubConfig, githubFetch } from './utils';
import { getGitHubConfig, githubFetch, normalizeRepoReference } from './utils';
import type { GitHubAPIRepository } from './types';
/**
@@ -33,16 +33,28 @@ export function registerCheckConnection(): void {
}
try {
// Normalize repo reference (handles full URLs, git URLs, etc.)
const normalizedRepo = normalizeRepoReference(config.repo);
if (!normalizedRepo) {
return {
success: true,
data: {
connected: false,
error: 'Invalid repository format. Use owner/repo or GitHub URL.'
}
};
}
// Fetch repo info
const repoData = await githubFetch(
config.token,
`/repos/${config.repo}`
`/repos/${normalizedRepo}`
) as { full_name: string; description?: string };
// Count open issues
const issuesData = await githubFetch(
config.token,
`/repos/${config.repo}/issues?state=open&per_page=1`
`/repos/${normalizedRepo}/issues?state=open&per_page=1`
) as unknown[];
const openCount = Array.isArray(issuesData) ? issuesData.length : 0;
@@ -71,7 +83,7 @@ export function registerCheckConnection(): void {
}
/**
* Get list of GitHub repositories
* Get list of GitHub repositories (personal + organization)
*/
export function registerGetRepositories(): void {
ipcMain.handle(
@@ -88,9 +100,11 @@ export function registerGetRepositories(): void {
}
try {
// Fetch user's personal + organization repos
// affiliation parameter includes: owner, collaborator, organization_member
const repos = await githubFetch(
config.token,
'/user/repos?per_page=100&sort=updated'
'/user/repos?per_page=100&sort=updated&affiliation=owner,collaborator,organization_member'
) as GitHubAPIRepository[];
const result: GitHubRepository[] = repos.map(repo => ({
@@ -51,6 +51,58 @@ function slugifyTitle(title: string): string {
.substring(0, 50);
}
/**
* Determine task category based on GitHub issue labels
* Maps to TaskCategory type from shared/types/task.ts
*/
function determineCategoryFromLabels(labels: string[]): 'feature' | 'bug_fix' | 'refactoring' | 'documentation' | 'security' | 'performance' | 'ui_ux' | 'infrastructure' | 'testing' {
const lowerLabels = labels.map(l => l.toLowerCase());
// Check for bug labels
if (lowerLabels.some(l => l.includes('bug') || l.includes('defect') || l.includes('error') || l.includes('fix'))) {
return 'bug_fix';
}
// Check for security labels
if (lowerLabels.some(l => l.includes('security') || l.includes('vulnerability') || l.includes('cve'))) {
return 'security';
}
// Check for performance labels
if (lowerLabels.some(l => l.includes('performance') || l.includes('optimization') || l.includes('speed'))) {
return 'performance';
}
// Check for UI/UX labels
if (lowerLabels.some(l => l.includes('ui') || l.includes('ux') || l.includes('design') || l.includes('styling'))) {
return 'ui_ux';
}
// Check for infrastructure labels
if (lowerLabels.some(l => l.includes('infrastructure') || l.includes('devops') || l.includes('deployment') || l.includes('ci') || l.includes('cd'))) {
return 'infrastructure';
}
// Check for testing labels
if (lowerLabels.some(l => l.includes('test') || l.includes('testing') || l.includes('qa'))) {
return 'testing';
}
// Check for refactoring labels
if (lowerLabels.some(l => l.includes('refactor') || l.includes('cleanup') || l.includes('maintenance') || l.includes('chore') || l.includes('tech-debt') || l.includes('technical debt'))) {
return 'refactoring';
}
// Check for documentation labels
if (lowerLabels.some(l => l.includes('documentation') || l.includes('docs'))) {
return 'documentation';
}
// Check for enhancement/feature labels (default)
// This catches 'enhancement', 'feature', 'improvement', or any unlabeled issues
return 'feature';
}
/**
* Create a new spec directory and initial files
*/
@@ -59,7 +111,8 @@ export function createSpecForIssue(
issueNumber: number,
issueTitle: string,
taskDescription: string,
githubUrl: string
githubUrl: string,
labels: string[] = []
): SpecCreationData {
const specsBaseDir = getSpecsDir(project.autoBuildPath);
const specsDir = path.join(project.path, specsBaseDir);
@@ -104,12 +157,15 @@ export function createSpecForIssue(
JSON.stringify(requirements, null, 2)
);
// Determine category from GitHub issue labels
const category = determineCategoryFromLabels(labels);
// task_metadata.json
const metadata: TaskMetadata = {
sourceType: 'github',
githubIssueNumber: issueNumber,
githubUrl,
category: 'feature'
category
};
writeFileSync(
path.join(specDir, 'task_metadata.json'),
@@ -38,8 +38,11 @@ export interface GitHubAPIRepository {
}
export interface GitHubAPIComment {
id: number;
body: string;
user: { login: string };
user: { login: string; avatar_url?: string };
created_at: string;
updated_at: string;
}
export interface ReleaseOptions {
@@ -54,6 +54,32 @@ export function getGitHubConfig(project: Project): GitHubConfig | null {
}
}
/**
* Normalize a GitHub repository reference to owner/repo format
* Handles:
* - owner/repo (already normalized)
* - https://github.com/owner/repo
* - https://github.com/owner/repo.git
* - git@github.com:owner/repo.git
*/
export function normalizeRepoReference(repo: string): string {
if (!repo) return '';
// Remove trailing .git if present
let normalized = repo.replace(/\.git$/, '');
// Handle full GitHub URLs
if (normalized.startsWith('https://github.com/')) {
normalized = normalized.replace('https://github.com/', '');
} else if (normalized.startsWith('http://github.com/')) {
normalized = normalized.replace('http://github.com/', '');
} else if (normalized.startsWith('git@github.com:')) {
normalized = normalized.replace('git@github.com:', '');
}
return normalized.trim();
}
/**
* Make a request to the GitHub API
*/
@@ -69,7 +95,7 @@ export async function githubFetch(
const response = await fetch(url, {
...options,
headers: {
'Accept': 'application/vnd.github.v3+json',
'Accept': 'application/vnd.github+json',
'Authorization': `Bearer ${token}`,
'User-Agent': 'Auto-Claude-UI',
...options.headers
@@ -7,6 +7,7 @@ import { IPC_CHANNELS } from '../../../shared/constants';
import type { IPCResult, IdeationConfig, IdeationGenerationStatus } from '../../../shared/types';
import { projectStore } from '../../project-store';
import type { AgentManager } from '../../agent';
import { debugLog } from '../../../shared/utils/debug-logger';
/**
* Start ideation generation for a project
@@ -18,10 +19,17 @@ export function startIdeationGeneration(
agentManager: AgentManager,
mainWindow: BrowserWindow | null
): void {
debugLog('[Ideation Handler] Start generation request:', {
projectId,
enabledTypes: config.enabledTypes,
maxIdeasPerType: config.maxIdeasPerType
});
if (!mainWindow) return;
const project = projectStore.getProject(projectId);
if (!project) {
debugLog('[Ideation Handler] Project not found:', projectId);
mainWindow.webContents.send(
IPC_CHANNELS.IDEATION_ERROR,
projectId,
@@ -30,6 +38,11 @@ export function startIdeationGeneration(
return;
}
debugLog('[Ideation Handler] Starting agent manager generation:', {
projectId,
projectPath: project.path
});
// Start ideation generation via agent manager
agentManager.startIdeationGeneration(projectId, project.path, config, false);
@@ -91,9 +104,14 @@ export async function stopIdeationGeneration(
agentManager: AgentManager,
mainWindow: BrowserWindow | null
): Promise<IPCResult> {
debugLog('[Ideation Handler] Stop generation request:', { projectId });
const wasStopped = agentManager.stopIdeation(projectId);
debugLog('[Ideation Handler] Stop result:', { projectId, wasStopped });
if (wasStopped && mainWindow) {
debugLog('[Ideation Handler] Sending stopped event to renderer');
mainWindow.webContents.send(IPC_CHANNELS.IDEATION_STOPPED, projectId);
}
@@ -35,7 +35,7 @@ export async function getIdeationSession(
try {
// Transform snake_case to camelCase for frontend
const enabledTypes = (rawIdeation.config?.enabled_types || rawIdeation.config?.enabledTypes || []) as any[];
const enabledTypes = (rawIdeation.config?.enabled_types || rawIdeation.config?.enabledTypes || []) as unknown[];
const session: IdeationSession = {
id: rawIdeation.id || `ideation-${Date.now()}`,
@@ -160,7 +160,7 @@ function buildTaskMetadata(idea: RawIdea): TaskMetadata {
function createSpecFiles(
specDir: string,
idea: RawIdea,
taskDescription: string
_taskDescription: string
): void {
// Create the spec directory
mkdirSync(specDir, { recursive: true });
@@ -27,6 +27,7 @@ import { registerIdeationHandlers } from './ideation-handlers';
import { registerChangelogHandlers } from './changelog-handlers';
import { registerInsightsHandlers } from './insights-handlers';
import { registerDockerHandlers } from './docker-handlers';
import { registerAppUpdateHandlers } from './app-update-handlers';
import { notificationService } from '../notification-service';
/**
@@ -94,7 +95,10 @@ export function setupIpcHandlers(
// Docker & infrastructure handlers (for Graphiti/FalkorDB)
registerDockerHandlers();
console.log('[IPC] All handler modules registered successfully');
// App auto-update handlers
registerAppUpdateHandlers();
console.warn('[IPC] All handler modules registered successfully');
}
// Re-export all individual registration functions for potential custom usage
@@ -114,5 +118,6 @@ export {
registerIdeationHandlers,
registerChangelogHandlers,
registerInsightsHandlers,
registerDockerHandlers
registerDockerHandlers,
registerAppUpdateHandlers
};
@@ -3,7 +3,7 @@ import type { BrowserWindow } from 'electron';
import path from 'path';
import { existsSync, readdirSync, mkdirSync, writeFileSync } from 'fs';
import { IPC_CHANNELS, getSpecsDir, AUTO_BUILD_PATHS } from '../../shared/constants';
import type { IPCResult, InsightsSession, InsightsSessionSummary, Task, TaskMetadata } from '../../shared/types';
import type { IPCResult, InsightsSession, InsightsSessionSummary, InsightsModelConfig, Task, TaskMetadata } from '../../shared/types';
import { projectStore } from '../project-store';
import { insightsService } from '../insights-service';
@@ -32,7 +32,7 @@ export function registerInsightsHandlers(
ipcMain.on(
IPC_CHANNELS.INSIGHTS_SEND_MESSAGE,
async (_, projectId: string, message: string) => {
async (_, projectId: string, message: string, modelConfig?: InsightsModelConfig) => {
const project = projectStore.getProject(projectId);
if (!project) {
const mainWindow = getMainWindow();
@@ -44,7 +44,7 @@ export function registerInsightsHandlers(
// Note: Python environment initialization should be handled by insightsService
// or added here with proper dependency injection if needed
insightsService.sendMessage(projectId, project.path, message);
insightsService.sendMessage(projectId, project.path, message, modelConfig);
}
);
@@ -241,4 +241,57 @@ export function registerInsightsHandlers(
}
);
// Update model configuration for a session
ipcMain.handle(
IPC_CHANNELS.INSIGHTS_UPDATE_MODEL_CONFIG,
async (_, projectId: string, sessionId: string, modelConfig: InsightsModelConfig): Promise<IPCResult> => {
const project = projectStore.getProject(projectId);
if (!project) {
return { success: false, error: 'Project not found' };
}
const success = insightsService.updateSessionModelConfig(project.path, sessionId, modelConfig);
if (success) {
return { success: true };
}
return { success: false, error: 'Failed to update model configuration' };
}
);
// ============================================
// Insights Event Forwarding (Service -> Renderer)
// ============================================
// Forward streaming chunks to renderer
insightsService.on('stream-chunk', (projectId: string, chunk: unknown) => {
const mainWindow = getMainWindow();
if (mainWindow) {
mainWindow.webContents.send(IPC_CHANNELS.INSIGHTS_STREAM_CHUNK, projectId, chunk);
}
});
// Forward status updates to renderer
insightsService.on('status', (projectId: string, status: unknown) => {
const mainWindow = getMainWindow();
if (mainWindow) {
mainWindow.webContents.send(IPC_CHANNELS.INSIGHTS_STATUS, projectId, status);
}
});
// Forward errors to renderer
insightsService.on('error', (projectId: string, error: string) => {
const mainWindow = getMainWindow();
if (mainWindow) {
mainWindow.webContents.send(IPC_CHANNELS.INSIGHTS_ERROR, projectId, error);
}
});
// Forward SDK rate limit events to renderer
insightsService.on('sdk-rate-limit', (rateLimitInfo: unknown) => {
const mainWindow = getMainWindow();
if (mainWindow) {
mainWindow.webContents.send(IPC_CHANNELS.CLAUDE_SDK_RATE_LIMIT, rateLimitInfo);
}
});
}
@@ -1,10 +1,9 @@
import { ipcMain } from 'electron';
import type { BrowserWindow } from 'electron';
import { IPC_CHANNELS, getSpecsDir, AUTO_BUILD_PATHS } from '../../shared/constants';
import type { IPCResult, LinearIssue, LinearTeam, LinearProject, LinearImportResult, LinearSyncStatus, Project, Task, TaskMetadata } from '../../shared/types';
import type { IPCResult, LinearIssue, LinearTeam, LinearProject, LinearImportResult, LinearSyncStatus, Project, TaskMetadata } from '../../shared/types';
import path from 'path';
import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync } from 'fs';
import { spawn } from 'child_process';
import { projectStore } from '../project-store';
import { parseEnvFile } from './utils';
@@ -16,7 +15,7 @@ import { AgentManager } from '../agent';
*/
export function registerLinearHandlers(
agentManager: AgentManager,
getMainWindow: () => BrowserWindow | null
_getMainWindow: () => BrowserWindow | null
): void {
// ============================================
// Linear Integration Operations
@@ -51,7 +50,7 @@ export function registerLinearHandlers(
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': apiKey
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({ query, variables })
});
@@ -115,7 +114,8 @@ export function registerLinearHandlers(
if (data.teams.nodes.length > 0) {
teamName = data.teams.nodes[0].name;
const countQuery = `
// Note: These queries are kept as documentation for future API reference
const _countQuery = `
query($teamId: String!) {
team(id: $teamId) {
issues {
@@ -125,7 +125,7 @@ export function registerLinearHandlers(
}
`;
// Get approximate count
const issuesQuery = `
const _issuesQuery = `
query($teamId: String!) {
issues(filter: { team: { id: { eq: $teamId } } }, first: 0) {
pageInfo {
@@ -134,6 +134,8 @@ export function registerLinearHandlers(
}
}
`;
void _countQuery;
void _issuesQuery;
// Simple count estimation - get first 250 issues
const countData = await linearGraphQL(apiKey, `
@@ -2,19 +2,23 @@ import { ipcMain, app } from 'electron';
import { existsSync, readFileSync } from 'fs';
import path from 'path';
import { execSync } from 'child_process';
import { is } from '@electron-toolkit/utils';
import { IPC_CHANNELS } from '../../shared/constants';
import type {
Project,
ProjectSettings,
IPCResult,
InitializationResult,
AutoBuildVersionInfo
AutoBuildVersionInfo,
GitStatus
} from '../../shared/types';
import { projectStore } from '../project-store';
import {
initializeProject,
isInitialized,
hasLocalSource
hasLocalSource,
checkGitStatus,
initializeGit
} from '../project-initializer';
import { PythonEnvManager, type PythonEnvStatus } from '../python-env-manager';
import { AgentManager } from '../agent';
@@ -99,29 +103,68 @@ function detectMainBranch(projectPath: string): string | null {
const settingsPath = path.join(app.getPath('userData'), 'settings.json');
/**
* Auto-detect the auto-claude source path relative to the app location
* In dev: auto-claude-ui/../auto-claude
* In prod: Could be bundled or configured
* Auto-detect the auto-claude source path relative to the app location.
* Works across platforms (macOS, Windows, Linux) in both dev and production modes.
*/
const detectAutoBuildSourcePath = (): string | null => {
// Try relative to app directory (works in dev and if repo structure is maintained)
// __dirname in main process points to out/main in dev
const possiblePaths = [
// Dev mode: from out/main -> ../../../auto-claude (sibling to auto-claude-ui)
path.resolve(__dirname, '..', '..', '..', 'auto-claude'),
// Alternative: from app root (useful in some packaged scenarios)
path.resolve(app.getAppPath(), '..', 'auto-claude'),
// If running from repo root
path.resolve(process.cwd(), 'auto-claude'),
// Try one more level up (in case of different build output structure)
path.resolve(__dirname, '..', '..', 'auto-claude')
];
const possiblePaths: string[] = [];
// Development mode paths
if (is.dev) {
// In dev, __dirname is typically auto-claude-ui/out/main
// We need to go up to the project root to find auto-claude/
possiblePaths.push(
path.resolve(__dirname, '..', '..', '..', 'auto-claude'), // From out/main up 3 levels
path.resolve(__dirname, '..', '..', 'auto-claude'), // From out/main up 2 levels
path.resolve(process.cwd(), 'auto-claude'), // From cwd (project root)
path.resolve(process.cwd(), '..', 'auto-claude') // From cwd parent (if running from auto-claude-ui/)
);
} else {
// Production mode paths (packaged app)
// On Windows/Linux/macOS, the app might be installed anywhere
// We check common locations relative to the app bundle
const appPath = app.getAppPath();
possiblePaths.push(
path.resolve(appPath, '..', 'auto-claude'), // Sibling to app
path.resolve(appPath, '..', '..', 'auto-claude'), // Up 2 from app
path.resolve(appPath, '..', '..', '..', 'auto-claude'), // Up 3 from app
path.resolve(process.resourcesPath, '..', 'auto-claude'), // Relative to resources
path.resolve(process.resourcesPath, '..', '..', 'auto-claude')
);
}
// Add process.cwd() as last resort on all platforms
possiblePaths.push(path.resolve(process.cwd(), 'auto-claude'));
// Enable debug logging with AUTO_CLAUDE_DEBUG=1
const debug = process.env.AUTO_CLAUDE_DEBUG === '1' || process.env.AUTO_CLAUDE_DEBUG === 'true';
if (debug) {
console.warn('[project-handlers:detectAutoBuildSourcePath] Platform:', process.platform);
console.warn('[project-handlers:detectAutoBuildSourcePath] Is dev:', is.dev);
console.warn('[project-handlers:detectAutoBuildSourcePath] __dirname:', __dirname);
console.warn('[project-handlers:detectAutoBuildSourcePath] app.getAppPath():', app.getAppPath());
console.warn('[project-handlers:detectAutoBuildSourcePath] process.cwd():', process.cwd());
console.warn('[project-handlers:detectAutoBuildSourcePath] Checking paths:', possiblePaths);
}
for (const p of possiblePaths) {
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
// Use requirements.txt as marker - it always exists in auto-claude source
const markerPath = path.join(p, 'requirements.txt');
const exists = existsSync(p) && existsSync(markerPath);
if (debug) {
console.warn(`[project-handlers:detectAutoBuildSourcePath] Checking ${p}: ${exists ? '✓ FOUND' : '✗ not found'}`);
}
if (exists) {
console.warn(`[project-handlers:detectAutoBuildSourcePath] Auto-detected source path: ${p}`);
return p;
}
}
console.warn('[project-handlers:detectAutoBuildSourcePath] Could not auto-detect Auto Claude source path.');
console.warn('[project-handlers:detectAutoBuildSourcePath] Set AUTO_CLAUDE_DEBUG=1 environment variable for detailed path checking.');
return null;
};
@@ -154,7 +197,7 @@ const configureServicesWithPython = (
autoBuildPath: string,
agentManager: AgentManager
): void => {
console.log('[IPC] Configuring services with Python:', pythonPath);
console.warn('[IPC] Configuring services with Python:', pythonPath);
agentManager.configure(pythonPath, autoBuildPath);
changelogService.configure(pythonPath, autoBuildPath);
insightsService.configure(pythonPath, autoBuildPath);
@@ -170,7 +213,7 @@ const initializePythonEnvironment = async (
): Promise<PythonEnvStatus> => {
const autoBuildSource = getAutoBuildSourcePath();
if (!autoBuildSource) {
console.log('[IPC] Auto-build source not found, skipping Python env init');
console.warn('[IPC] Auto-build source not found, skipping Python env init');
return {
ready: false,
pythonPath: null,
@@ -180,7 +223,7 @@ const initializePythonEnvironment = async (
};
}
console.log('[IPC] Initializing Python environment...');
console.warn('[IPC] Initializing Python environment...');
const status = await pythonEnvManager.initialize(autoBuildSource);
if (status.ready && status.pythonPath) {
@@ -237,11 +280,11 @@ export function registerProjectHandlers(
// If a folder was deleted, reset autoBuildPath so UI prompts for reinitialization
const resetIds = projectStore.validateProjects();
if (resetIds.length > 0) {
console.log('[IPC] PROJECT_LIST: Detected missing .auto-claude folders for', resetIds.length, 'project(s)');
console.warn('[IPC] PROJECT_LIST: Detected missing .auto-claude folders for', resetIds.length, 'project(s)');
}
const projects = projectStore.getProjects();
console.log('[IPC] PROJECT_LIST returning', projects.length, 'projects');
console.warn('[IPC] PROJECT_LIST returning', projects.length, 'projects');
return { success: true, data: projects };
}
);
@@ -289,7 +332,7 @@ export function registerProjectHandlers(
// Initialize Python environment on startup (non-blocking)
initializePythonEnvironment(pythonEnvManager, agentManager).then((status) => {
console.log('[IPC] Python environment initialized:', status);
console.warn('[IPC] Python environment initialized:', status);
});
// IPC handler to get Python environment status
@@ -465,4 +508,42 @@ export function registerProjectHandlers(
}
}
);
// Check git status for a project (is it a repo? has commits?)
ipcMain.handle(
IPC_CHANNELS.GIT_CHECK_STATUS,
async (_, projectPath: string): Promise<IPCResult<GitStatus>> => {
try {
if (!existsSync(projectPath)) {
return { success: false, error: 'Directory does not exist' };
}
const gitStatus = checkGitStatus(projectPath);
return { success: true, data: gitStatus };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
};
}
}
);
// Initialize git in a project (run git init and create initial commit)
ipcMain.handle(
IPC_CHANNELS.GIT_INITIALIZE,
async (_, projectPath: string): Promise<IPCResult<InitializationResult>> => {
try {
if (!existsSync(projectPath)) {
return { success: false, error: 'Directory does not exist' };
}
const result = initializeGit(projectPath);
return { success: result.success, data: result, error: result.error };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
};
}
}
);
}
@@ -5,8 +5,8 @@ import type { IPCResult, Roadmap, RoadmapFeature, RoadmapFeatureStatus, RoadmapG
import path from 'path';
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'fs';
import { projectStore } from '../project-store';
import { fileWatcher } from '../file-watcher';
import { AgentManager } from '../agent';
import { debugLog, debugError } from '../../shared/utils/debug-logger';
/**
@@ -160,14 +160,30 @@ export function registerRoadmapHandlers(
}
);
// Get roadmap generation status - allows frontend to query if generation is running
ipcMain.handle(
IPC_CHANNELS.ROADMAP_GET_STATUS,
async (_, projectId: string): Promise<IPCResult<{ isRunning: boolean }>> => {
const isRunning = agentManager.isRoadmapRunning(projectId);
debugLog('[Roadmap Handler] Get status:', { projectId, isRunning });
return { success: true, data: { isRunning } };
}
);
ipcMain.on(
IPC_CHANNELS.ROADMAP_GENERATE,
(_, projectId: string, enableCompetitorAnalysis?: boolean) => {
debugLog('[Roadmap Handler] Generate request:', {
projectId,
enableCompetitorAnalysis
});
const mainWindow = getMainWindow();
if (!mainWindow) return;
const project = projectStore.getProject(projectId);
if (!project) {
debugError('[Roadmap Handler] Project not found:', projectId);
mainWindow.webContents.send(
IPC_CHANNELS.ROADMAP_ERROR,
projectId,
@@ -176,6 +192,11 @@ export function registerRoadmapHandlers(
return;
}
debugLog('[Roadmap Handler] Starting agent manager generation:', {
projectId,
projectPath: project.path
});
// Start roadmap generation via agent manager
agentManager.startRoadmapGeneration(projectId, project.path, false, enableCompetitorAnalysis ?? false);
@@ -224,6 +245,27 @@ export function registerRoadmapHandlers(
}
);
ipcMain.handle(
IPC_CHANNELS.ROADMAP_STOP,
async (_, projectId: string): Promise<IPCResult> => {
debugLog('[Roadmap Handler] Stop generation request:', { projectId });
const mainWindow = getMainWindow();
// Stop roadmap generation for this project
const wasStopped = agentManager.stopRoadmap(projectId);
debugLog('[Roadmap Handler] Stop result:', { projectId, wasStopped });
if (wasStopped && mainWindow) {
debugLog('[Roadmap Handler] Sending stopped event to renderer');
mainWindow.webContents.send(IPC_CHANNELS.ROADMAP_STOPPED, projectId);
}
return { success: wasStopped };
}
);
// ============================================
// Roadmap Save (full state persistence for drag-and-drop)
// ============================================
@@ -233,7 +275,7 @@ export function registerRoadmapHandlers(
async (
_,
projectId: string,
features: RoadmapFeature[]
roadmapData: Roadmap
): Promise<IPCResult> => {
const project = projectStore.getProject(projectId);
if (!project) {
@@ -252,10 +294,10 @@ export function registerRoadmapHandlers(
try {
const content = readFileSync(roadmapPath, 'utf-8');
const roadmap = JSON.parse(content);
const existingRoadmap = JSON.parse(content);
// Transform camelCase features back to snake_case for JSON file
roadmap.features = features.map((feature) => ({
existingRoadmap.features = roadmapData.features.map((feature) => ({
id: feature.id,
title: feature.title,
description: feature.description,
@@ -273,10 +315,10 @@ export function registerRoadmapHandlers(
}));
// Update metadata timestamp
roadmap.metadata = roadmap.metadata || {};
roadmap.metadata.updated_at = new Date().toISOString();
existingRoadmap.metadata = existingRoadmap.metadata || {};
existingRoadmap.metadata.updated_at = new Date().toISOString();
writeFileSync(roadmapPath, JSON.stringify(roadmap, null, 2));
writeFileSync(roadmapPath, JSON.stringify(existingRoadmap, null, 2));
return { success: true };
} catch (error) {
@@ -2,6 +2,7 @@ import { ipcMain, dialog, app, shell } from 'electron';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
import { execSync } from 'child_process';
import path from 'path';
import { is } from '@electron-toolkit/utils';
import { IPC_CHANNELS, DEFAULT_APP_SETTINGS } from '../../shared/constants';
import type {
AppSettings,
@@ -9,25 +10,73 @@ import type {
} from '../../shared/types';
import { AgentManager } from '../agent';
import type { BrowserWindow } from 'electron';
import { getEffectiveVersion } from '../auto-claude-updater';
const settingsPath = path.join(app.getPath('userData'), 'settings.json');
/**
* Auto-detect the auto-claude source path relative to the app location
* Auto-detect the auto-claude source path relative to the app location.
* Works across platforms (macOS, Windows, Linux) in both dev and production modes.
*/
const detectAutoBuildSourcePath = (): string | null => {
const possiblePaths = [
path.resolve(__dirname, '..', '..', '..', 'auto-claude'),
path.resolve(app.getAppPath(), '..', 'auto-claude'),
path.resolve(process.cwd(), 'auto-claude'),
path.resolve(__dirname, '..', '..', 'auto-claude')
];
const possiblePaths: string[] = [];
// Development mode paths
if (is.dev) {
// In dev, __dirname is typically auto-claude-ui/out/main
// We need to go up to the project root to find auto-claude/
possiblePaths.push(
path.resolve(__dirname, '..', '..', '..', 'auto-claude'), // From out/main up 3 levels
path.resolve(__dirname, '..', '..', 'auto-claude'), // From out/main up 2 levels
path.resolve(process.cwd(), 'auto-claude'), // From cwd (project root)
path.resolve(process.cwd(), '..', 'auto-claude') // From cwd parent (if running from auto-claude-ui/)
);
} else {
// Production mode paths (packaged app)
// On Windows/Linux/macOS, the app might be installed anywhere
// We check common locations relative to the app bundle
const appPath = app.getAppPath();
possiblePaths.push(
path.resolve(appPath, '..', 'auto-claude'), // Sibling to app
path.resolve(appPath, '..', '..', 'auto-claude'), // Up 2 from app
path.resolve(appPath, '..', '..', '..', 'auto-claude'), // Up 3 from app
path.resolve(process.resourcesPath, '..', 'auto-claude'), // Relative to resources
path.resolve(process.resourcesPath, '..', '..', 'auto-claude')
);
}
// Add process.cwd() as last resort on all platforms
possiblePaths.push(path.resolve(process.cwd(), 'auto-claude'));
// Enable debug logging with AUTO_CLAUDE_DEBUG=1
const debug = process.env.AUTO_CLAUDE_DEBUG === '1' || process.env.AUTO_CLAUDE_DEBUG === 'true';
if (debug) {
console.warn('[detectAutoBuildSourcePath] Platform:', process.platform);
console.warn('[detectAutoBuildSourcePath] Is dev:', is.dev);
console.warn('[detectAutoBuildSourcePath] __dirname:', __dirname);
console.warn('[detectAutoBuildSourcePath] app.getAppPath():', app.getAppPath());
console.warn('[detectAutoBuildSourcePath] process.cwd():', process.cwd());
console.warn('[detectAutoBuildSourcePath] Checking paths:', possiblePaths);
}
for (const p of possiblePaths) {
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
// Use requirements.txt as marker - it always exists in auto-claude source
const markerPath = path.join(p, 'requirements.txt');
const exists = existsSync(p) && existsSync(markerPath);
if (debug) {
console.warn(`[detectAutoBuildSourcePath] Checking ${p}: ${exists ? '✓ FOUND' : '✗ not found'}`);
}
if (exists) {
console.warn(`[detectAutoBuildSourcePath] Auto-detected source path: ${p}`);
return p;
}
}
console.warn('[detectAutoBuildSourcePath] Could not auto-detect Auto Claude source path. Please configure manually in settings.');
console.warn('[detectAutoBuildSourcePath] Set AUTO_CLAUDE_DEBUG=1 environment variable for detailed path checking.');
return null;
};
@@ -45,7 +94,8 @@ export function registerSettingsHandlers(
ipcMain.handle(
IPC_CHANNELS.SETTINGS_GET,
async (): Promise<IPCResult<AppSettings>> => {
let settings = { ...DEFAULT_APP_SETTINGS };
let settings: AppSettings = { ...DEFAULT_APP_SETTINGS };
let needsSave = false;
if (existsSync(settingsPath)) {
try {
@@ -56,6 +106,18 @@ export function registerSettingsHandlers(
}
}
// Migration: Set agent profile to 'auto' for users who haven't made a selection (one-time)
// This ensures new users get the optimized 'auto' profile as the default
// while preserving existing user preferences
if (!settings._migratedAgentProfileToAuto) {
// Only set 'auto' if user hasn't made a selection yet
if (!settings.selectedAgentProfile) {
settings.selectedAgentProfile = 'auto';
}
settings._migratedAgentProfileToAuto = true;
needsSave = true;
}
// If no manual autoBuildPath is set, try to auto-detect
if (!settings.autoBuildPath) {
const detectedPath = detectAutoBuildSourcePath();
@@ -64,6 +126,16 @@ export function registerSettingsHandlers(
}
}
// Persist migration changes
if (needsSave) {
try {
writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
} catch (error) {
console.error('[SETTINGS_GET] Failed to persist migration:', error);
// Continue anyway - settings will be migrated in-memory for this session
}
}
return { success: true, data: settings as AppSettings };
}
);
@@ -216,7 +288,10 @@ export function registerSettingsHandlers(
// ============================================
ipcMain.handle(IPC_CHANNELS.APP_VERSION, async (): Promise<string> => {
return app.getVersion();
// Use effective version which accounts for source updates
const version = getEffectiveVersion();
console.log('[settings-handlers] APP_VERSION returning:', version);
return version;
});
// ============================================
@@ -18,12 +18,12 @@ export function registerTaskArchiveHandlers(): void {
taskIds: string[],
version?: string
): Promise<IPCResult<boolean>> => {
console.log('[IPC] TASK_ARCHIVE called with projectId:', projectId, 'taskIds:', taskIds);
console.warn('[IPC] TASK_ARCHIVE called with projectId:', projectId, 'taskIds:', taskIds);
const result = projectStore.archiveTasks(projectId, taskIds, version);
if (result) {
console.log('[IPC] TASK_ARCHIVE success');
console.warn('[IPC] TASK_ARCHIVE success');
return { success: true, data: true };
} else {
console.error('[IPC] TASK_ARCHIVE failed');
@@ -38,12 +38,12 @@ export function registerTaskArchiveHandlers(): void {
ipcMain.handle(
IPC_CHANNELS.TASK_UNARCHIVE,
async (_, projectId: string, taskIds: string[]): Promise<IPCResult<boolean>> => {
console.log('[IPC] TASK_UNARCHIVE called with projectId:', projectId, 'taskIds:', taskIds);
console.warn('[IPC] TASK_UNARCHIVE called with projectId:', projectId, 'taskIds:', taskIds);
const result = projectStore.unarchiveTasks(projectId, taskIds);
if (result) {
console.log('[IPC] TASK_UNARCHIVE success');
console.warn('[IPC] TASK_UNARCHIVE success');
return { success: true, data: true };
} else {
console.error('[IPC] TASK_UNARCHIVE failed');
@@ -1,6 +1,6 @@
import { ipcMain } from 'electron';
import { IPC_CHANNELS, AUTO_BUILD_PATHS, getSpecsDir } from '../../../shared/constants';
import type { IPCResult, Task, TaskMetadata, Project } from '../../../shared/types';
import type { IPCResult, Task, TaskMetadata } from '../../../shared/types';
import path from 'path';
import { existsSync, readFileSync, writeFileSync, readdirSync, mkdirSync } from 'fs';
import { projectStore } from '../../project-store';
@@ -18,9 +18,9 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
ipcMain.handle(
IPC_CHANNELS.TASK_LIST,
async (_, projectId: string): Promise<IPCResult<Task[]>> => {
console.log('[IPC] TASK_LIST called with projectId:', projectId);
console.warn('[IPC] TASK_LIST called with projectId:', projectId);
const tasks = projectStore.getTasks(projectId);
console.log('[IPC] TASK_LIST returning', tasks.length, 'tasks');
console.warn('[IPC] TASK_LIST returning', tasks.length, 'tasks');
return { success: true, data: tasks };
}
);
@@ -45,17 +45,17 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
// Auto-generate title if empty using Claude AI
let finalTitle = title;
if (!title || !title.trim()) {
console.log('[TASK_CREATE] Title is empty, generating with Claude AI...');
console.warn('[TASK_CREATE] Title is empty, generating with Claude AI...');
try {
const generatedTitle = await titleGenerator.generateTitle(description);
if (generatedTitle) {
finalTitle = generatedTitle;
console.log('[TASK_CREATE] Generated title:', finalTitle);
console.warn('[TASK_CREATE] Generated title:', finalTitle);
} else {
// Fallback: create title from first line of description
finalTitle = description.split('\n')[0].substring(0, 60);
if (finalTitle.length === 60) finalTitle += '...';
console.log('[TASK_CREATE] AI generation failed, using fallback:', finalTitle);
console.warn('[TASK_CREATE] AI generation failed, using fallback:', finalTitle);
}
} catch (err) {
console.error('[TASK_CREATE] Title generation error:', err);
@@ -226,7 +226,7 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
try {
if (existsSync(specDir)) {
await rm(specDir, { recursive: true, force: true });
console.log(`[TASK_DELETE] Deleted spec directory: ${specDir}`);
console.warn(`[TASK_DELETE] Deleted spec directory: ${specDir}`);
}
return { success: true };
} catch (error) {
@@ -269,17 +269,17 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
if (updates.title !== undefined && !updates.title.trim()) {
// Get description to use for title generation
const descriptionToUse = updates.description ?? task.description;
console.log('[TASK_UPDATE] Title is empty, generating with Claude AI...');
console.warn('[TASK_UPDATE] Title is empty, generating with Claude AI...');
try {
const generatedTitle = await titleGenerator.generateTitle(descriptionToUse);
if (generatedTitle) {
finalTitle = generatedTitle;
console.log('[TASK_UPDATE] Generated title:', finalTitle);
console.warn('[TASK_UPDATE] Generated title:', finalTitle);
} else {
// Fallback: create title from first line of description
finalTitle = descriptionToUse.split('\n')[0].substring(0, 60);
if (finalTitle.length === 60) finalTitle += '...';
console.log('[TASK_UPDATE] AI generation failed, using fallback:', finalTitle);
console.warn('[TASK_UPDATE] AI generation failed, using fallback:', finalTitle);
}
} catch (err) {
console.error('[TASK_UPDATE] Title generation error:', err);
@@ -1,11 +1,14 @@
import { ipcMain, BrowserWindow } from 'electron';
import { IPC_CHANNELS, AUTO_BUILD_PATHS, getSpecsDir } from '../../../shared/constants';
import type { IPCResult, Task, TaskStartOptions, TaskStatus } from '../../../shared/types';
import type { IPCResult, TaskStartOptions, TaskStatus } from '../../../shared/types';
import path from 'path';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
import { spawnSync } from 'child_process';
import { AgentManager } from '../../agent';
import { fileWatcher } from '../../file-watcher';
import { findTaskAndProject } from './shared';
import { checkGitStatus } from '../../project-initializer';
import { getClaudeProfileManager } from '../../claude-profile-manager';
/**
* Register task execution handlers (start, stop, review, status management, recovery)
@@ -19,11 +22,11 @@ export function registerTaskExecutionHandlers(
*/
ipcMain.on(
IPC_CHANNELS.TASK_START,
(_, taskId: string, options?: TaskStartOptions) => {
console.log('[TASK_START] Received request for taskId:', taskId);
(_, taskId: string, _options?: TaskStartOptions) => {
console.warn('[TASK_START] Received request for taskId:', taskId);
const mainWindow = getMainWindow();
if (!mainWindow) {
console.log('[TASK_START] No main window found');
console.warn('[TASK_START] No main window found');
return;
}
@@ -31,7 +34,7 @@ export function registerTaskExecutionHandlers(
const { task, project } = findTaskAndProject(taskId);
if (!task || !project) {
console.log('[TASK_START] Task or project not found for taskId:', taskId);
console.warn('[TASK_START] Task or project not found for taskId:', taskId);
mainWindow.webContents.send(
IPC_CHANNELS.TASK_ERROR,
taskId,
@@ -40,7 +43,40 @@ export function registerTaskExecutionHandlers(
return;
}
console.log('[TASK_START] Found task:', task.specId, 'status:', task.status, 'subtasks:', task.subtasks.length);
// Check git status - Auto Claude requires git for worktree-based builds
const gitStatus = checkGitStatus(project.path);
if (!gitStatus.isGitRepo) {
console.warn('[TASK_START] Project is not a git repository:', project.path);
mainWindow.webContents.send(
IPC_CHANNELS.TASK_ERROR,
taskId,
'Git repository required. Please run "git init" in your project directory. Auto Claude uses git worktrees for isolated builds.'
);
return;
}
if (!gitStatus.hasCommits) {
console.warn('[TASK_START] Git repository has no commits:', project.path);
mainWindow.webContents.send(
IPC_CHANNELS.TASK_ERROR,
taskId,
'Git repository has no commits. Please make an initial commit first (git add . && git commit -m "Initial commit").'
);
return;
}
// Check authentication - Claude requires valid auth to run tasks
const profileManager = getClaudeProfileManager();
if (!profileManager.hasValidAuth()) {
console.warn('[TASK_START] No valid authentication for active profile');
mainWindow.webContents.send(
IPC_CHANNELS.TASK_ERROR,
taskId,
'Claude authentication required. Please go to Settings > Claude Profiles and authenticate your account, or set an OAuth token.'
);
return;
}
console.warn('[TASK_START] Found task:', task.specId, 'status:', task.status, 'subtasks:', task.subtasks.length);
// Start file watcher for this task
const specsBaseDir = getSpecsDir(project.autoBuildPath);
@@ -60,7 +96,7 @@ export function registerTaskExecutionHandlers(
const needsSpecCreation = !hasSpec;
const needsImplementation = hasSpec && task.subtasks.length === 0;
console.log('[TASK_START] hasSpec:', hasSpec, 'needsSpecCreation:', needsSpecCreation, 'needsImplementation:', needsImplementation);
console.warn('[TASK_START] hasSpec:', hasSpec, 'needsSpecCreation:', needsSpecCreation, 'needsImplementation:', needsImplementation);
// Get base branch from project settings for worktree creation
const baseBranch = project.settings?.mainBranch;
@@ -68,7 +104,7 @@ export function registerTaskExecutionHandlers(
if (needsSpecCreation) {
// No spec file - need to run spec_runner.py to create the spec
const taskDescription = task.description || task.title;
console.log('[TASK_START] Starting spec creation for:', task.specId, 'in:', specDir);
console.warn('[TASK_START] Starting spec creation for:', task.specId, 'in:', specDir);
// Start spec creation process - pass the existing spec directory
// so spec_runner uses it instead of creating a new one
@@ -76,14 +112,14 @@ export function registerTaskExecutionHandlers(
} else if (needsImplementation) {
// Spec exists but no subtasks - run run.py to create implementation plan and execute
// Read the spec.md to get the task description
let taskDescription = task.description || task.title;
const _taskDescription = task.description || task.title;
try {
taskDescription = readFileSync(specFilePath, 'utf-8');
readFileSync(specFilePath, 'utf-8');
} catch {
// Use default description
}
console.log('[TASK_START] Starting task execution (no subtasks) for:', task.specId);
console.warn('[TASK_START] Starting task execution (no subtasks) for:', task.specId);
// Start task execution which will create the implementation plan
// Note: No parallel mode for planning phase - parallel only makes sense with multiple subtasks
agentManager.startTaskExecution(
@@ -99,7 +135,7 @@ export function registerTaskExecutionHandlers(
} else {
// Task has subtasks, start normal execution
// Note: Parallel execution is handled internally by the agent, not via CLI flags
console.log('[TASK_START] Starting task execution (has subtasks) for:', task.specId);
console.warn('[TASK_START] Starting task execution (has subtasks) for:', task.specId);
agentManager.startTaskExecution(
taskId,
@@ -165,6 +201,11 @@ export function registerTaskExecutionHandlers(
task.specId
);
// Check if worktree exists - QA needs to run in the worktree where the build happened
const worktreePath = path.join(project.path, '.worktrees', task.specId);
const worktreeSpecDir = path.join(worktreePath, specsBaseDir, task.specId);
const hasWorktree = existsSync(worktreePath);
if (approved) {
// Write approval to QA report
const qaReportPath = path.join(specDir, AUTO_BUILD_PATHS.QA_REPORT);
@@ -182,15 +223,60 @@ export function registerTaskExecutionHandlers(
);
}
} else {
// Write feedback for QA fixer
const fixRequestPath = path.join(specDir, 'QA_FIX_REQUEST.md');
// Reset and discard all changes from worktree merge in main
// The worktree still has all changes, so nothing is lost
if (hasWorktree) {
// Step 1: Unstage all changes
const resetResult = spawnSync('git', ['reset', 'HEAD'], {
cwd: project.path,
encoding: 'utf-8',
stdio: 'pipe'
});
if (resetResult.status === 0) {
console.log('[TASK_REVIEW] Unstaged changes in main');
}
// Step 2: Discard all working tree changes (restore to pre-merge state)
const checkoutResult = spawnSync('git', ['checkout', '--', '.'], {
cwd: project.path,
encoding: 'utf-8',
stdio: 'pipe'
});
if (checkoutResult.status === 0) {
console.log('[TASK_REVIEW] Discarded working tree changes in main');
}
// Step 3: Clean untracked files that came from the merge
const cleanResult = spawnSync('git', ['clean', '-fd'], {
cwd: project.path,
encoding: 'utf-8',
stdio: 'pipe'
});
if (cleanResult.status === 0) {
console.log('[TASK_REVIEW] Cleaned untracked files in main');
}
console.log('[TASK_REVIEW] Main branch restored to pre-merge state');
}
// Write feedback for QA fixer - write to WORKTREE spec dir if it exists
// The QA process runs in the worktree where the build and implementation_plan.json are
const targetSpecDir = hasWorktree ? worktreeSpecDir : specDir;
const fixRequestPath = path.join(targetSpecDir, 'QA_FIX_REQUEST.md');
console.warn('[TASK_REVIEW] Writing QA fix request to:', fixRequestPath);
console.warn('[TASK_REVIEW] hasWorktree:', hasWorktree, 'worktreePath:', worktreePath);
writeFileSync(
fixRequestPath,
`# QA Fix Request\n\nStatus: REJECTED\n\n## Feedback\n\n${feedback || 'No feedback provided'}\n\nCreated at: ${new Date().toISOString()}\n`
);
// Restart QA process with dev mode
agentManager.startQAProcess(taskId, project.path, task.specId);
// Restart QA process - use worktree path if it exists, otherwise main project
// The QA process needs to run where the implementation_plan.json with completed subtasks is
const qaProjectPath = hasWorktree ? worktreePath : project.path;
console.warn('[TASK_REVIEW] Starting QA process with projectPath:', qaProjectPath);
agentManager.startQAProcess(taskId, qaProjectPath, task.specId);
const mainWindow = getMainWindow();
if (mainWindow) {
@@ -216,13 +302,64 @@ export function registerTaskExecutionHandlers(
taskId: string,
status: TaskStatus
): Promise<IPCResult> => {
// Find task and project
// Find task and project first (needed for worktree check)
const { task, project } = findTaskAndProject(taskId);
if (!task || !project) {
return { success: false, error: 'Task not found' };
}
// Validate status transition - 'done' can only be set through merge handler
// UNLESS there's no worktree (limbo state - already merged/discarded or failed)
if (status === 'done') {
// Check if worktree exists
const worktreePath = path.join(project.path, '.worktrees', taskId);
const hasWorktree = existsSync(worktreePath);
if (hasWorktree) {
// Worktree exists - must use merge workflow
console.warn(`[TASK_UPDATE_STATUS] Blocked attempt to set status 'done' directly for task ${taskId}. Use merge workflow instead.`);
return {
success: false,
error: "Cannot set status to 'done' directly. Complete the human review and merge the worktree changes instead."
};
} else {
// No worktree - allow marking as done (limbo state recovery)
console.log(`[TASK_UPDATE_STATUS] Allowing status 'done' for task ${taskId} (no worktree found - limbo state)`);
}
}
// Validate status transition - 'human_review' requires actual work to have been done
// This prevents tasks from being incorrectly marked as ready for review when execution failed
if (status === 'human_review') {
const specsBaseDirForValidation = getSpecsDir(project.autoBuildPath);
const specDirForValidation = path.join(
project.path,
specsBaseDirForValidation,
task.specId
);
const specFilePath = path.join(specDirForValidation, AUTO_BUILD_PATHS.SPEC_FILE);
// Check if spec.md exists and has meaningful content (at least 100 chars)
const MIN_SPEC_CONTENT_LENGTH = 100;
let specContent = '';
try {
if (existsSync(specFilePath)) {
specContent = readFileSync(specFilePath, 'utf-8');
}
} catch {
// Ignore read errors - treat as empty spec
}
if (!specContent || specContent.length < MIN_SPEC_CONTENT_LENGTH) {
console.warn(`[TASK_UPDATE_STATUS] Blocked attempt to set status 'human_review' for task ${taskId}. No spec has been created yet.`);
return {
success: false,
error: "Cannot move to human review - no spec has been created yet. The task must complete processing before review."
};
}
}
// Get the spec directory
const specsBaseDir = getSpecsDir(project.autoBuildPath);
const specDir = path.join(
@@ -242,10 +379,10 @@ export function registerTaskExecutionHandlers(
// Store the exact UI status - project-store.ts will map it back
plan.status = status;
// Also store mapped version for Python compatibility
plan.planStatus = status === 'done' ? 'completed'
: status === 'in_progress' ? 'in_progress'
plan.planStatus = status === 'in_progress' ? 'in_progress'
: status === 'ai_review' ? 'review'
: status === 'human_review' ? 'review'
: status === 'done' ? 'completed'
: 'pending';
plan.updated_at = new Date().toISOString();
@@ -258,10 +395,10 @@ export function registerTaskExecutionHandlers(
created_at: task.createdAt.toISOString(),
updated_at: new Date().toISOString(),
status: status, // Store exact UI status for persistence
planStatus: status === 'done' ? 'completed'
: status === 'in_progress' ? 'in_progress'
planStatus: status === 'in_progress' ? 'in_progress'
: status === 'ai_review' ? 'review'
: status === 'human_review' ? 'review'
: status === 'done' ? 'completed'
: 'pending',
phases: []
};
@@ -277,7 +414,36 @@ export function registerTaskExecutionHandlers(
// Auto-start task when status changes to 'in_progress' and no process is running
if (status === 'in_progress' && !agentManager.isRunning(taskId)) {
const mainWindow = getMainWindow();
console.log('[TASK_UPDATE_STATUS] Auto-starting task:', taskId);
// Check git status before auto-starting
const gitStatusCheck = checkGitStatus(project.path);
if (!gitStatusCheck.isGitRepo || !gitStatusCheck.hasCommits) {
console.warn('[TASK_UPDATE_STATUS] Git check failed, cannot auto-start task');
if (mainWindow) {
mainWindow.webContents.send(
IPC_CHANNELS.TASK_ERROR,
taskId,
gitStatusCheck.error || 'Git repository with commits required to run tasks.'
);
}
return { success: false, error: gitStatusCheck.error || 'Git repository required' };
}
// Check authentication before auto-starting
const profileManager = getClaudeProfileManager();
if (!profileManager.hasValidAuth()) {
console.warn('[TASK_UPDATE_STATUS] No valid authentication for active profile');
if (mainWindow) {
mainWindow.webContents.send(
IPC_CHANNELS.TASK_ERROR,
taskId,
'Claude authentication required. Please go to Settings > Claude Profiles and authenticate your account, or set an OAuth token.'
);
}
return { success: false, error: 'Claude authentication required' };
}
console.warn('[TASK_UPDATE_STATUS] Auto-starting task:', taskId);
// Start file watcher for this task
fileWatcher.watch(taskId, specDir);
@@ -288,16 +454,16 @@ export function registerTaskExecutionHandlers(
const needsSpecCreation = !hasSpec;
const needsImplementation = hasSpec && task.subtasks.length === 0;
console.log('[TASK_UPDATE_STATUS] hasSpec:', hasSpec, 'needsSpecCreation:', needsSpecCreation, 'needsImplementation:', needsImplementation);
console.warn('[TASK_UPDATE_STATUS] hasSpec:', hasSpec, 'needsSpecCreation:', needsSpecCreation, 'needsImplementation:', needsImplementation);
if (needsSpecCreation) {
// No spec file - need to run spec_runner.py to create the spec
const taskDescription = task.description || task.title;
console.log('[TASK_UPDATE_STATUS] Starting spec creation for:', task.specId);
console.warn('[TASK_UPDATE_STATUS] Starting spec creation for:', task.specId);
agentManager.startSpecCreation(task.specId, project.path, taskDescription, specDir, task.metadata);
} else if (needsImplementation) {
// Spec exists but no subtasks - run run.py to create implementation plan and execute
console.log('[TASK_UPDATE_STATUS] Starting task execution (no subtasks) for:', task.specId);
console.warn('[TASK_UPDATE_STATUS] Starting task execution (no subtasks) for:', task.specId);
agentManager.startTaskExecution(
taskId,
project.path,
@@ -310,7 +476,7 @@ export function registerTaskExecutionHandlers(
} else {
// Task has subtasks, start normal execution
// Note: Parallel execution is handled internally by the agent
console.log('[TASK_UPDATE_STATUS] Starting task execution (has subtasks) for:', task.specId);
console.warn('[TASK_UPDATE_STATUS] Starting task execution (has subtasks) for:', task.specId);
agentManager.startTaskExecution(
taskId,
project.path,
@@ -488,6 +654,40 @@ export function registerTaskExecutionHandlers(
// Auto-restart the task if requested
let autoRestarted = false;
if (autoRestart && project) {
// Check git status before auto-restarting
const gitStatusForRestart = checkGitStatus(project.path);
if (!gitStatusForRestart.isGitRepo || !gitStatusForRestart.hasCommits) {
console.warn('[Recovery] Git check failed, cannot auto-restart task');
// Recovery succeeded but we can't restart without git
return {
success: true,
data: {
taskId,
recovered: true,
newStatus,
message: `Task recovered but cannot restart: ${gitStatusForRestart.error || 'Git repository with commits required.'}`,
autoRestarted: false
}
};
}
// Check authentication before auto-restarting
const profileManager = getClaudeProfileManager();
if (!profileManager.hasValidAuth()) {
console.warn('[Recovery] Auth check failed, cannot auto-restart task');
// Recovery succeeded but we can't restart without auth
return {
success: true,
data: {
taskId,
recovered: true,
newStatus,
message: 'Task recovered but cannot restart: Claude authentication required. Please go to Settings > Claude Profiles and authenticate your account.',
autoRestarted: false
}
};
}
try {
// Set status to in_progress for the restart
newStatus = 'in_progress';
@@ -505,19 +705,32 @@ export function registerTaskExecutionHandlers(
const specDirForWatcher = path.join(project.path, specsBaseDir, task.specId);
fileWatcher.watch(taskId, specDirForWatcher);
// Note: Parallel execution is handled internally by the agent
agentManager.startTaskExecution(
taskId,
project.path,
task.specId,
{
parallel: false,
workers: 1
}
);
// Check if spec.md exists to determine whether to run spec creation or task execution
const specFilePath = path.join(specDirForWatcher, AUTO_BUILD_PATHS.SPEC_FILE);
const hasSpec = existsSync(specFilePath);
const needsSpecCreation = !hasSpec;
if (needsSpecCreation) {
// No spec file - need to run spec_runner.py to create the spec
const taskDescription = task.description || task.title;
console.warn(`[Recovery] Starting spec creation for: ${task.specId}`);
agentManager.startSpecCreation(task.specId, project.path, taskDescription, specDirForWatcher, task.metadata);
} else {
// Spec exists - run task execution
console.warn(`[Recovery] Starting task execution for: ${task.specId}`);
agentManager.startTaskExecution(
taskId,
project.path,
task.specId,
{
parallel: false,
workers: 1
}
);
}
autoRestarted = true;
console.log(`[Recovery] Auto-restarted task ${taskId}`);
console.warn(`[Recovery] Auto-restarted task ${taskId}`);
} catch (restartError) {
console.error('Failed to auto-restart task after recovery:', restartError);
// Recovery succeeded but restart failed - still report success
@@ -1,14 +1,15 @@
import { ipcMain, BrowserWindow } from 'electron';
import { IPC_CHANNELS, AUTO_BUILD_PATHS, getSpecsDir } from '../../../shared/constants';
import { IPC_CHANNELS, AUTO_BUILD_PATHS } from '../../../shared/constants';
import type { IPCResult, WorktreeStatus, WorktreeDiff, WorktreeDiffFile, WorktreeMergeResult, WorktreeDiscardResult, WorktreeListResult, WorktreeListItem } from '../../../shared/types';
import path from 'path';
import { existsSync, readdirSync, statSync } from 'fs';
import { execSync, spawn } from 'child_process';
import { execSync, spawn, spawnSync } from 'child_process';
import { projectStore } from '../../project-store';
import { PythonEnvManager } from '../../python-env-manager';
import { getEffectiveSourcePath } from '../../auto-claude-updater';
import { getProfileEnv } from '../../rate-limit-detector';
import { findTaskAndProject } from './shared';
import { findPythonCommand, parsePythonCommand } from '../../python-detector';
/**
* Register worktree management handlers
@@ -48,14 +49,14 @@ export function registerWorktreeHandlers(
encoding: 'utf-8'
}).trim();
// Get base branch (usually main or master)
// Get base branch - the current branch in the main project (where changes will be merged)
// This matches the Python merge logic which merges into the user's current branch
let baseBranch = 'main';
try {
// Try to get the default branch
baseBranch = execSync('git rev-parse --abbrev-ref origin/HEAD 2>/dev/null || echo main', {
baseBranch = execSync('git rev-parse --abbrev-ref HEAD', {
cwd: project.path,
encoding: 'utf-8'
}).trim().replace('origin/', '');
}).trim();
} catch {
baseBranch = 'main';
}
@@ -144,13 +145,13 @@ export function registerWorktreeHandlers(
return { success: false, error: 'No worktree found for this task' };
}
// Get base branch
// Get base branch - the current branch in the main project (where changes will be merged)
let baseBranch = 'main';
try {
baseBranch = execSync('git rev-parse --abbrev-ref origin/HEAD 2>/dev/null || echo main', {
baseBranch = execSync('git rev-parse --abbrev-ref HEAD', {
cwd: project.path,
encoding: 'utf-8'
}).trim().replace('origin/', '');
}).trim();
} catch {
baseBranch = 'main';
}
@@ -226,11 +227,11 @@ export function registerWorktreeHandlers(
async (_, taskId: string, options?: { noCommit?: boolean }): Promise<IPCResult<WorktreeMergeResult>> => {
// Always log merge operations for debugging
const debug = (...args: unknown[]) => {
console.log('[MERGE DEBUG]', ...args);
console.warn('[MERGE DEBUG]', ...args);
};
try {
console.log('[MERGE] Handler called with taskId:', taskId, 'options:', options);
console.warn('[MERGE] Handler called with taskId:', taskId, 'options:', options);
debug('Starting merge for taskId:', taskId, 'options:', options);
// Ensure Python environment is ready
@@ -272,6 +273,31 @@ export function registerWorktreeHandlers(
const worktreePath = path.join(project.path, '.worktrees', task.specId);
debug('Worktree path:', worktreePath, 'exists:', existsSync(worktreePath));
// Check if changes are already staged (for stage-only mode)
if (options?.noCommit) {
const stagedResult = spawnSync('git', ['diff', '--staged', '--name-only'], {
cwd: project.path,
encoding: 'utf-8'
});
if (stagedResult.status === 0 && stagedResult.stdout?.trim()) {
const stagedFiles = stagedResult.stdout.trim().split('\n');
debug('Changes already staged:', stagedFiles.length, 'files');
// Return success - changes are already staged
return {
success: true,
data: {
success: true,
merged: false,
message: `Changes already staged (${stagedFiles.length} files). Review with git diff --staged.`,
staged: true,
alreadyStaged: true,
projectPath: project.path
}
};
}
}
// Get git status before merge
try {
const gitStatusBefore = execSync('git status --short', { cwd: project.path, encoding: 'utf-8' });
@@ -294,7 +320,7 @@ export function registerWorktreeHandlers(
args.push('--no-commit');
}
const pythonPath = pythonEnvManager.getPythonPath() || 'python3';
const pythonPath = pythonEnvManager.getPythonPath() || findPythonCommand() || 'python';
debug('Running command:', pythonPath, args.join(' '));
debug('Working directory:', sourcePath);
@@ -310,12 +336,16 @@ export function registerWorktreeHandlers(
let timeoutId: NodeJS.Timeout | null = null;
let resolved = false;
const mergeProcess = spawn(pythonPath, args, {
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(pythonPath);
const mergeProcess = spawn(pythonCommand, [...pythonBaseArgs, ...args], {
cwd: sourcePath,
env: {
...process.env,
...profileEnv, // Include active Claude profile OAuth token
PYTHONUNBUFFERED: '1'
PYTHONUNBUFFERED: '1',
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
},
stdio: ['ignore', 'pipe', 'pipe'] // Don't connect stdin to avoid blocking
});
@@ -400,12 +430,90 @@ export function registerWorktreeHandlers(
if (code === 0) {
const isStageOnly = options?.noCommit === true;
// For stage-only: keep in human_review so user commits manually
// For full merge: mark as done
const newStatus = isStageOnly ? 'human_review' : 'done';
const planStatus = isStageOnly ? 'review' : 'completed';
// Verify changes were actually staged when stage-only mode is requested
// This prevents false positives when merge was already committed previously
let hasActualStagedChanges = false;
let mergeAlreadyCommitted = false;
debug('Merge successful. isStageOnly:', isStageOnly, 'newStatus:', newStatus);
if (isStageOnly) {
try {
const gitDiffStaged = execSync('git diff --staged --stat', { cwd: project.path, encoding: 'utf-8' });
hasActualStagedChanges = gitDiffStaged.trim().length > 0;
debug('Stage-only verification: hasActualStagedChanges:', hasActualStagedChanges);
if (!hasActualStagedChanges) {
// Check if worktree branch was already merged (merge commit exists)
const specBranch = `auto-claude/${task.specId}`;
try {
// Check if current branch contains all commits from spec branch
const mergeBaseResult = execSync(
`git merge-base --is-ancestor ${specBranch} HEAD 2>/dev/null && echo "merged" || echo "not-merged"`,
{ cwd: project.path, encoding: 'utf-8' }
).trim();
mergeAlreadyCommitted = mergeBaseResult === 'merged';
debug('Merge already committed check:', mergeAlreadyCommitted);
} catch {
// Branch may not exist or other error - assume not merged
debug('Could not check merge status, assuming not merged');
}
}
} catch (e) {
debug('Failed to verify staged changes:', e);
}
}
// Determine actual status based on verification
let newStatus: string;
let planStatus: string;
let message: string;
let staged: boolean;
if (isStageOnly && !hasActualStagedChanges && mergeAlreadyCommitted) {
// Stage-only was requested but merge was already committed previously
// Mark as done since changes are already in the branch
newStatus = 'done';
planStatus = 'completed';
message = 'Changes were already merged and committed. Task marked as done.';
staged = false;
debug('Stage-only requested but merge already committed. Marking as done.');
} else if (isStageOnly && !hasActualStagedChanges) {
// Stage-only was requested but no changes to stage (and not committed)
// This could mean nothing to merge or an error - keep in human_review for investigation
newStatus = 'human_review';
planStatus = 'review';
message = 'No changes to stage. The worktree may have no differences from the current branch.';
staged = false;
debug('Stage-only requested but no changes to stage.');
} else if (isStageOnly) {
// Stage-only with actual staged changes - expected success case
newStatus = 'human_review';
planStatus = 'review';
message = 'Changes staged in main project. Review with git status and commit when ready.';
staged = true;
} else {
// Full merge (not stage-only)
newStatus = 'done';
planStatus = 'completed';
message = 'Changes merged successfully';
staged = false;
}
debug('Merge result. isStageOnly:', isStageOnly, 'newStatus:', newStatus, 'staged:', staged);
// Read suggested commit message if staging succeeded
let suggestedCommitMessage: string | undefined;
if (staged) {
const commitMsgPath = path.join(specDir, 'suggested_commit_message.txt');
try {
if (existsSync(commitMsgPath)) {
const { readFileSync } = require('fs');
suggestedCommitMessage = readFileSync(commitMsgPath, 'utf-8').trim();
debug('Read suggested commit message:', suggestedCommitMessage?.substring(0, 100));
}
} catch (e) {
debug('Failed to read suggested commit message:', e);
}
}
// Persist the status change to implementation_plan.json
const planPath = path.join(specDir, AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN);
@@ -417,7 +525,7 @@ export function registerWorktreeHandlers(
plan.status = newStatus;
plan.planStatus = planStatus;
plan.updated_at = new Date().toISOString();
if (isStageOnly) {
if (staged) {
plan.stagedAt = new Date().toISOString();
plan.stagedInMainProject = true;
}
@@ -432,17 +540,14 @@ export function registerWorktreeHandlers(
mainWindow.webContents.send(IPC_CHANNELS.TASK_STATUS_CHANGE, taskId, newStatus);
}
const message = isStageOnly
? 'Changes staged in main project. Review with git status and commit when ready.'
: 'Changes merged successfully';
resolve({
success: true,
data: {
success: true,
message,
staged: isStageOnly,
projectPath: isStageOnly ? project.path : undefined
staged,
projectPath: staged ? project.path : undefined,
suggestedCommitMessage
}
});
} else {
@@ -499,11 +604,11 @@ export function registerWorktreeHandlers(
ipcMain.handle(
IPC_CHANNELS.TASK_WORKTREE_MERGE_PREVIEW,
async (_, taskId: string): Promise<IPCResult<WorktreeMergeResult>> => {
console.log('[IPC] TASK_WORKTREE_MERGE_PREVIEW called with taskId:', taskId);
console.warn('[IPC] TASK_WORKTREE_MERGE_PREVIEW called with taskId:', taskId);
try {
// Ensure Python environment is ready
if (!pythonEnvManager.isEnvReady()) {
console.log('[IPC] Python environment not ready, initializing...');
console.warn('[IPC] Python environment not ready, initializing...');
const autoBuildSource = getEffectiveSourcePath();
if (autoBuildSource) {
const status = await pythonEnvManager.initialize(autoBuildSource);
@@ -522,7 +627,7 @@ export function registerWorktreeHandlers(
console.error('[IPC] Task not found:', taskId);
return { success: false, error: 'Task not found' };
}
console.log('[IPC] Found task:', task.specId, 'project:', project.name);
console.warn('[IPC] Found task:', task.specId, 'project:', project.name);
// Check for uncommitted changes in the main project
let hasUncommittedChanges = false;
@@ -531,15 +636,17 @@ export function registerWorktreeHandlers(
const gitStatus = execSync('git status --porcelain', {
cwd: project.path,
encoding: 'utf-8'
}).trim();
});
if (gitStatus) {
if (gitStatus && gitStatus.trim()) {
// Parse the status output to get file names
uncommittedFiles = gitStatus.split('\n')
// Format: XY filename (where X and Y are status chars, then space, then filename)
uncommittedFiles = gitStatus
.split('\n')
.filter(line => line.trim())
.map(line => line.substring(3).trim()); // Remove status prefix (e.g., "M ", " M ", "?? ")
.map(line => line.substring(3).trim()); // Skip 2 status chars + 1 space, trim any trailing whitespace
hasUncommittedChanges = uncommittedFiles.length > 0;
console.log('[IPC] Uncommitted changes detected:', uncommittedFiles.length, 'files');
}
} catch (e) {
console.error('[IPC] Failed to check git status:', e);
@@ -559,16 +666,18 @@ export function registerWorktreeHandlers(
'--merge-preview'
];
const pythonPath = pythonEnvManager.getPythonPath() || 'python3';
console.log('[IPC] Running merge preview:', pythonPath, args.join(' '));
const pythonPath = pythonEnvManager.getPythonPath() || findPythonCommand() || 'python';
console.warn('[IPC] Running merge preview:', pythonPath, args.join(' '));
// Get profile environment for consistency
const previewProfileEnv = getProfileEnv();
return new Promise((resolve) => {
const previewProcess = spawn(pythonPath, args, {
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(pythonPath);
const previewProcess = spawn(pythonCommand, [...pythonBaseArgs, ...args], {
cwd: sourcePath,
env: { ...process.env, ...previewProfileEnv, PYTHONUNBUFFERED: '1', DEBUG: 'true' }
env: { ...process.env, ...previewProfileEnv, PYTHONUNBUFFERED: '1', PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1', DEBUG: 'true' }
});
let stdout = '';
@@ -577,22 +686,22 @@ export function registerWorktreeHandlers(
previewProcess.stdout.on('data', (data: Buffer) => {
const chunk = data.toString();
stdout += chunk;
console.log('[IPC] merge-preview stdout:', chunk);
console.warn('[IPC] merge-preview stdout:', chunk);
});
previewProcess.stderr.on('data', (data: Buffer) => {
const chunk = data.toString();
stderr += chunk;
console.log('[IPC] merge-preview stderr:', chunk);
console.warn('[IPC] merge-preview stderr:', chunk);
});
previewProcess.on('close', (code: number) => {
console.log('[IPC] merge-preview process exited with code:', code);
console.warn('[IPC] merge-preview process exited with code:', code);
if (code === 0) {
try {
// Parse JSON output from Python
const result = JSON.parse(stdout.trim());
console.log('[IPC] merge-preview result:', JSON.stringify(result, null, 2));
console.warn('[IPC] merge-preview result:', JSON.stringify(result, null, 2));
resolve({
success: true,
data: {
@@ -772,13 +881,13 @@ export function registerWorktreeHandlers(
encoding: 'utf-8'
}).trim();
// Get base branch
// Get base branch - the current branch in the main project (where changes will be merged)
let baseBranch = 'main';
try {
baseBranch = execSync('git rev-parse --abbrev-ref origin/HEAD 2>/dev/null || echo main', {
baseBranch = execSync('git rev-parse --abbrev-ref HEAD', {
cwd: project.path,
encoding: 'utf-8'
}).trim().replace('origin/', '');
}).trim();
} catch {
baseBranch = 'main';
}
@@ -7,6 +7,8 @@ import { getUsageMonitor } from '../claude-profile/usage-monitor';
import { TerminalManager } from '../terminal-manager';
import { projectStore } from '../project-store';
import { terminalNameGenerator } from '../terminal-name-generator';
import { debugLog, debugError } from '../../shared/utils/debug-logger';
import { escapeShellArg, escapeShellArgWindows } from '../../shared/utils/shell-escape';
/**
@@ -162,14 +164,108 @@ export function registerTerminalHandlers(
ipcMain.handle(
IPC_CHANNELS.CLAUDE_PROFILE_SET_ACTIVE,
async (_, profileId: string): Promise<IPCResult> => {
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] ========== PROFILE SWITCH START ==========');
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Requested profile ID:', profileId);
try {
const profileManager = getClaudeProfileManager();
const previousProfile = profileManager.getActiveProfile();
const previousProfileId = previousProfile.id;
const newProfile = profileManager.getProfile(profileId);
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Previous profile:', {
id: previousProfile.id,
name: previousProfile.name,
hasOAuthToken: !!previousProfile.oauthToken,
isDefault: previousProfile.isDefault
});
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] New profile:', newProfile ? {
id: newProfile.id,
name: newProfile.name,
hasOAuthToken: !!newProfile.oauthToken,
isDefault: newProfile.isDefault
} : 'NOT FOUND');
const success = profileManager.setActiveProfile(profileId);
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] setActiveProfile result:', success);
if (!success) {
debugError('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Profile not found, aborting');
return { success: false, error: 'Profile not found' };
}
// If the profile actually changed, restart Claude in active terminals
// This ensures existing Claude sessions use the new profile's OAuth token
const profileChanged = previousProfileId !== profileId;
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Profile changed:', profileChanged, {
previousProfileId,
newProfileId: profileId
});
if (profileChanged) {
const activeTerminalIds = terminalManager.getActiveTerminalIds();
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Active terminal IDs:', activeTerminalIds);
const switchPromises: Promise<void>[] = [];
const terminalsInClaudeMode: string[] = [];
const terminalsNotInClaudeMode: string[] = [];
for (const terminalId of activeTerminalIds) {
const isClaudeMode = terminalManager.isClaudeMode(terminalId);
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Terminal check:', {
terminalId,
isClaudeMode
});
if (isClaudeMode) {
terminalsInClaudeMode.push(terminalId);
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Queuing terminal for profile switch:', terminalId);
switchPromises.push(
terminalManager.switchClaudeProfile(terminalId, profileId)
.then(() => {
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Terminal profile switch SUCCESS:', terminalId);
})
.catch((err) => {
debugError('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Terminal profile switch FAILED:', terminalId, err);
throw err; // Re-throw so Promise.allSettled correctly reports rejections
})
);
} else {
terminalsNotInClaudeMode.push(terminalId);
}
}
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Terminal summary:', {
total: activeTerminalIds.length,
inClaudeMode: terminalsInClaudeMode.length,
notInClaudeMode: terminalsNotInClaudeMode.length,
terminalsToSwitch: terminalsInClaudeMode,
terminalsSkipped: terminalsNotInClaudeMode
});
// Wait for all switches to complete (but don't fail the main operation if some fail)
if (switchPromises.length > 0) {
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Waiting for', switchPromises.length, 'terminal switches...');
const results = await Promise.allSettled(switchPromises);
const fulfilled = results.filter(r => r.status === 'fulfilled').length;
const rejected = results.filter(r => r.status === 'rejected').length;
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Switch results:', {
total: results.length,
fulfilled,
rejected
});
} else {
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] No terminals in Claude mode to switch');
}
} else {
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] Same profile selected, no terminal switches needed');
}
debugLog('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] ========== PROFILE SWITCH COMPLETE ==========');
return { success: true };
} catch (error) {
debugError('[terminal-handlers:CLAUDE_PROFILE_SET_ACTIVE] EXCEPTION:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to set active Claude profile'
@@ -208,7 +304,7 @@ export function registerTerminalHandlers(
const { mkdirSync, existsSync } = await import('fs');
if (!existsSync(profile.configDir)) {
mkdirSync(profile.configDir, { recursive: true });
console.log('[IPC] Created config directory:', profile.configDir);
debugLog('[IPC] Created config directory:', profile.configDir);
}
}
@@ -217,7 +313,7 @@ export function registerTerminalHandlers(
const terminalId = `claude-login-${profileId}-${Date.now()}`;
const homeDir = process.env.HOME || process.env.USERPROFILE || '/tmp';
console.log('[IPC] Initializing Claude profile:', {
debugLog('[IPC] Initializing Claude profile:', {
profileId,
profileName: profile.name,
configDir: profile.configDir,
@@ -231,16 +327,25 @@ export function registerTerminalHandlers(
await new Promise(resolve => setTimeout(resolve, 500));
// Build the login command with the profile's config dir
// Use export to ensure the variable persists, then run setup-token
// Use platform-specific syntax and escaping for environment variables
let loginCommand: string;
if (!profile.isDefault && profile.configDir) {
// Use export and run in subshell to ensure CLAUDE_CONFIG_DIR is properly set
loginCommand = `export CLAUDE_CONFIG_DIR="${profile.configDir}" && echo "Config dir: $CLAUDE_CONFIG_DIR" && claude setup-token`;
if (process.platform === 'win32') {
// SECURITY: Use Windows-specific escaping for cmd.exe
const escapedConfigDir = escapeShellArgWindows(profile.configDir);
// Windows cmd.exe syntax: set "VAR=value" with %VAR% for expansion
loginCommand = `set "CLAUDE_CONFIG_DIR=${escapedConfigDir}" && echo Config dir: %CLAUDE_CONFIG_DIR% && claude setup-token`;
} else {
// SECURITY: Use POSIX escaping for bash/zsh
const escapedConfigDir = escapeShellArg(profile.configDir);
// Unix/Mac bash/zsh syntax: export VAR=value with $VAR for expansion
loginCommand = `export CLAUDE_CONFIG_DIR=${escapedConfigDir} && echo "Config dir: $CLAUDE_CONFIG_DIR" && claude setup-token`;
}
} else {
loginCommand = 'claude setup-token';
}
console.log('[IPC] Sending login command to terminal:', loginCommand);
debugLog('[IPC] Sending login command to terminal:', loginCommand);
// Write the login command to the terminal
terminalManager.write(terminalId, `${loginCommand}\r`);
@@ -255,15 +360,15 @@ export function registerTerminalHandlers(
});
}
return {
success: true,
data: {
return {
success: true,
data: {
terminalId,
message: `A terminal has been opened to authenticate "${profile.name}". Complete the OAuth flow in your browser, then copy the token shown in the terminal.`
}
}
};
} catch (error) {
console.error('[IPC] Failed to initialize Claude profile:', error);
debugError('[IPC] Failed to initialize Claude profile:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to initialize Claude profile'
@@ -284,7 +389,7 @@ export function registerTerminalHandlers(
}
return { success: true };
} catch (error) {
console.error('[IPC] Failed to set OAuth token:', error);
debugError('[IPC] Failed to set OAuth token:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to set OAuth token'
@@ -569,5 +674,5 @@ export function initializeUsageMonitorForwarding(mainWindow: BrowserWindow): voi
mainWindow.webContents.send(IPC_CHANNELS.PROACTIVE_SWAP_NOTIFICATION, notification);
});
console.log('[terminal-handlers] Usage monitor event forwarding initialized');
debugLog('[terminal-handlers] Usage monitor event forwarding initialized');
}
+16 -17
View File
@@ -17,7 +17,7 @@ export interface LogEntry {
/**
* Service for persisting and retrieving task execution logs
*
*
* Log files are stored in {specDir}/logs/ with format:
* - session-{ISO-timestamp}.log - Raw log output per execution session
* - latest.log - Copy of most recent session's logs
@@ -26,7 +26,7 @@ export class LogService {
private activeSessions: Map<string, { sessionId: string; logPath: string; startedAt: Date }> = new Map();
private logBuffers: Map<string, string[]> = new Map();
private flushIntervals: Map<string, NodeJS.Timeout> = new Map();
// Flush logs to disk every 2 seconds to balance performance vs data safety
private readonly FLUSH_INTERVAL_MS = 2000;
// Maximum log file size before rotation (10MB)
@@ -39,7 +39,7 @@ export class LogService {
*/
startSession(taskId: string, specDir: string): string {
const logsDir = path.join(specDir, 'logs');
// Ensure logs directory exists
if (!existsSync(logsDir)) {
mkdirSync(logsDir, { recursive: true });
@@ -60,7 +60,7 @@ export class LogService {
'='.repeat(80),
''
].join('\n');
writeFileSync(logFile, header);
// Track active session
@@ -82,7 +82,7 @@ export class LogService {
// Clean up old sessions
this.cleanupOldSessions(logsDir);
console.log(`[LogService] Started session ${sessionId} for task ${taskId}`);
console.warn(`[LogService] Started session ${sessionId} for task ${taskId}`);
return sessionId;
}
@@ -120,7 +120,7 @@ export class LogService {
private flushBuffer(taskId: string): void {
const session = this.activeSessions.get(taskId);
const buffer = this.logBuffers.get(taskId);
if (!session || !buffer || buffer.length === 0) {
return;
}
@@ -150,7 +150,7 @@ export class LogService {
const now = new Date();
const duration = now.getTime() - session.startedAt.getTime();
const durationStr = this.formatDuration(duration);
const footer = [
'',
'='.repeat(80),
@@ -181,7 +181,7 @@ export class LogService {
this.activeSessions.delete(taskId);
this.logBuffers.delete(taskId);
console.log(`[LogService] Ended session for task ${taskId}, exit code: ${exitCode}`);
console.warn(`[LogService] Ended session for task ${taskId}, exit code: ${exitCode}`);
}
/**
@@ -189,7 +189,7 @@ export class LogService {
*/
getSessions(specDir: string): LogSession[] {
const logsDir = path.join(specDir, 'logs');
if (!existsSync(logsDir)) {
return [];
}
@@ -203,7 +203,7 @@ export class LogService {
const filePath = path.join(logsDir, file);
const stats = statSync(filePath);
const sessionId = file.replace('session-', '').replace('.log', '');
// Parse session ID back to date
const dateStr = sessionId.replace(/-/g, (match, offset) => {
// Replace first 2 dashes with actual dashes, rest with colons
@@ -211,7 +211,7 @@ export class LogService {
if (offset === 10) return 'T';
return ':';
}).replace(/-(\d{3})Z$/, '.$1Z');
const startedAt = new Date(dateStr);
// Count lines (approximate)
@@ -233,7 +233,7 @@ export class LogService {
*/
loadSessionLogs(specDir: string, sessionId?: string): string {
const logsDir = path.join(specDir, 'logs');
if (!existsSync(logsDir)) {
return '';
}
@@ -289,17 +289,17 @@ export class LogService {
// Keep MAX_SESSIONS_TO_KEEP, delete the rest
const toDelete = files.slice(this.MAX_SESSIONS_TO_KEEP);
for (const file of toDelete) {
const filePath = path.join(logsDir, file);
try {
require('fs').unlinkSync(filePath);
console.log(`[LogService] Deleted old log session: ${file}`);
} catch (e) {
console.warn(`[LogService] Deleted old log session: ${file}`);
} catch (_e) {
// Ignore deletion errors
}
}
} catch (error) {
} catch (_error) {
// Ignore cleanup errors
}
}
@@ -339,4 +339,3 @@ export class LogService {
// Singleton instance
export const logService = new LogService();
+151 -4
View File
@@ -1,5 +1,6 @@
import { existsSync, mkdirSync, writeFileSync, readFileSync, appendFileSync } from 'fs';
import path from 'path';
import { execSync } from 'child_process';
/**
* Debug logging - only logs when AUTO_CLAUDE_DEBUG env var is set
@@ -9,13 +10,144 @@ const DEBUG = process.env.AUTO_CLAUDE_DEBUG === 'true' || process.env.AUTO_CLAUD
function debug(message: string, data?: Record<string, unknown>): void {
if (DEBUG) {
if (data) {
console.log(`[ProjectInitializer] ${message}`, JSON.stringify(data, null, 2));
console.warn(`[ProjectInitializer] ${message}`, JSON.stringify(data, null, 2));
} else {
console.log(`[ProjectInitializer] ${message}`);
console.warn(`[ProjectInitializer] ${message}`);
}
}
}
/**
* Git status information for a project
*/
export interface GitStatus {
isGitRepo: boolean;
hasCommits: boolean;
currentBranch: string | null;
error?: string;
}
/**
* Check if a directory is a git repository and has at least one commit
*/
export function checkGitStatus(projectPath: string): GitStatus {
try {
// Check if it's a git repository
execSync('git rev-parse --git-dir', {
cwd: projectPath,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe']
});
} catch {
return {
isGitRepo: false,
hasCommits: false,
currentBranch: null,
error: 'Not a git repository. Please run "git init" to initialize git.'
};
}
// Check if there are any commits
let hasCommits = false;
try {
execSync('git rev-parse HEAD', {
cwd: projectPath,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe']
});
hasCommits = true;
} catch {
// No commits yet
hasCommits = false;
}
// Get current branch
let currentBranch: string | null = null;
try {
currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {
cwd: projectPath,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe']
}).trim();
} catch {
// Branch detection failed
}
if (!hasCommits) {
return {
isGitRepo: true,
hasCommits: false,
currentBranch,
error: 'Git repository has no commits. Please make an initial commit first.'
};
}
return {
isGitRepo: true,
hasCommits: true,
currentBranch
};
}
/**
* Initialize git in a project directory and create an initial commit.
* This is a user-friendly way to set up git for non-technical users.
*/
export function initializeGit(projectPath: string): InitializationResult {
debug('initializeGit called', { projectPath });
// Check current git status
const status = checkGitStatus(projectPath);
try {
// Step 1: Initialize git if needed
if (!status.isGitRepo) {
debug('Initializing git repository');
execSync('git init', {
cwd: projectPath,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe']
});
}
// Step 2: Check if there are files to commit
const statusOutput = execSync('git status --porcelain', {
cwd: projectPath,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe']
}).trim();
// Step 3: If there are untracked/modified files, add and commit them
if (statusOutput || !status.hasCommits) {
debug('Adding files and creating initial commit');
// Add all files
execSync('git add -A', {
cwd: projectPath,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe']
});
// Create initial commit
execSync('git commit -m "Initial commit" --allow-empty', {
cwd: projectPath,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe']
});
}
debug('Git initialization complete');
return { success: true };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error during git initialization';
debug('Git initialization failed', { error: errorMessage });
return {
success: false,
error: errorMessage
};
}
}
/**
* Entries to add to .gitignore when initializing a project
*/
@@ -101,8 +233,9 @@ export interface InitializationResult {
*/
export function hasLocalSource(projectPath: string): boolean {
const localSourcePath = path.join(projectPath, 'auto-claude');
const versionFile = path.join(localSourcePath, 'VERSION');
return existsSync(localSourcePath) && existsSync(versionFile);
// Use requirements.txt as marker - it always exists in auto-claude source
const markerFile = path.join(localSourcePath, 'requirements.txt');
return existsSync(localSourcePath) && existsSync(markerFile);
}
/**
@@ -129,6 +262,10 @@ export function isInitialized(projectPath: string): boolean {
*
* Creates .auto-claude/ with data directories (specs, ideation, insights, roadmap).
* The framework code runs from the source repo - only data is stored here.
*
* Requires:
* - Project directory must exist
* - Project must be a git repository with at least one commit
*/
export function initializeProject(projectPath: string): InitializationResult {
debug('initializeProject called', { projectPath });
@@ -142,6 +279,16 @@ export function initializeProject(projectPath: string): InitializationResult {
};
}
// Check git status - Auto Claude requires git for worktree-based builds
const gitStatus = checkGitStatus(projectPath);
if (!gitStatus.isGitRepo || !gitStatus.hasCommits) {
debug('Git check failed', { gitStatus });
return {
success: false,
error: gitStatus.error || 'Git repository required. Auto Claude uses git worktrees for isolated builds.'
};
}
// Check if already initialized
const dotAutoBuildPath = path.join(projectPath, '.auto-claude');
+66 -11
View File
@@ -145,13 +145,13 @@ export class ProjectStore {
// Check if the project path still exists
if (!existsSync(project.path)) {
console.log(`[ProjectStore] Project path no longer exists: ${project.path}`);
console.warn(`[ProjectStore] Project path no longer exists: ${project.path}`);
continue; // Don't reset - let user handle this case
}
// Check if .auto-claude folder still exists
if (!isInitialized(project.path)) {
console.log(`[ProjectStore] .auto-claude folder missing for project "${project.name}" at ${project.path}`);
console.warn(`[ProjectStore] .auto-claude folder missing for project "${project.name}" at ${project.path}`);
project.autoBuildPath = '';
project.updatedAt = new Date();
resetProjectIds.push(project.id);
@@ -161,7 +161,7 @@ export class ProjectStore {
if (hasChanges) {
this.save();
console.log(`[ProjectStore] Reset ${resetProjectIds.length} project(s) due to missing .auto-claude folder`);
console.warn(`[ProjectStore] Reset ${resetProjectIds.length} project(s) due to missing .auto-claude folder`);
}
return resetProjectIds;
@@ -194,18 +194,18 @@ export class ProjectStore {
* Get tasks for a project by scanning specs directory
*/
getTasks(projectId: string): Task[] {
console.log('[ProjectStore] getTasks called with projectId:', projectId);
console.warn('[ProjectStore] getTasks called with projectId:', projectId);
const project = this.getProject(projectId);
if (!project) {
console.log('[ProjectStore] Project not found for id:', projectId);
console.warn('[ProjectStore] Project not found for id:', projectId);
return [];
}
console.log('[ProjectStore] Found project:', project.name, 'autoBuildPath:', project.autoBuildPath);
console.warn('[ProjectStore] Found project:', project.name, 'autoBuildPath:', project.autoBuildPath);
// Get specs directory path
const specsBaseDir = getSpecsDir(project.autoBuildPath);
const specsDir = path.join(project.path, specsBaseDir);
console.log('[ProjectStore] specsDir:', specsDir, 'exists:', existsSync(specsDir));
console.warn('[ProjectStore] specsDir:', specsDir, 'exists:', existsSync(specsDir));
if (!existsSync(specsDir)) return [];
const tasks: Task[] = [];
@@ -243,8 +243,8 @@ export class ProjectStore {
if (existsSync(specFilePath)) {
try {
const content = readFileSync(specFilePath, 'utf-8');
// Extract first paragraph after "## Overview"
const overviewMatch = content.match(/## Overview\s*\n\n([^\n#]+)/);
// Extract first paragraph after "## Overview" - handle both with and without blank line
const overviewMatch = content.match(/## Overview\s*\n+([^\n#]+)/);
if (overviewMatch) {
description = overviewMatch[1].trim();
}
@@ -258,6 +258,42 @@ export class ProjectStore {
description = plan.description;
}
// Fallback: read description from requirements.json if still not found
if (!description) {
const requirementsPath = path.join(specPath, AUTO_BUILD_PATHS.REQUIREMENTS);
if (existsSync(requirementsPath)) {
try {
const reqContent = readFileSync(requirementsPath, 'utf-8');
const requirements = JSON.parse(reqContent);
if (requirements.task_description) {
// Extract a clean summary from task_description (first line or first ~200 chars)
const taskDesc = requirements.task_description;
const firstLine = taskDesc.split('\n')[0].trim();
// If the first line is a title like "Investigate GitHub Issue #36", use the next meaningful line
if (firstLine.toLowerCase().startsWith('investigate') && taskDesc.includes('\n\n')) {
const sections = taskDesc.split('\n\n');
// Find the first paragraph that's not a title
for (const section of sections) {
const trimmed = section.trim();
// Skip headers and short lines
if (trimmed.startsWith('#') || trimmed.length < 20) continue;
// Skip the "Please analyze" instruction at the end
if (trimmed.startsWith('Please analyze')) continue;
description = trimmed.substring(0, 200).split('\n')[0];
break;
}
}
// If still no description, use a shortened version of task_description
if (!description) {
description = firstLine.substring(0, 150);
}
}
} catch {
// Ignore parse errors
}
}
}
// Try to read task metadata
const metadataPath = path.join(specPath, 'task_metadata.json');
let metadata: TaskMetadata | undefined;
@@ -290,11 +326,30 @@ export class ProjectStore {
const stagedInMainProject = planWithStaged?.stagedInMainProject;
const stagedAt = planWithStaged?.stagedAt;
// Determine title - check if feature looks like a spec ID (e.g., "054-something-something")
let title = plan?.feature || plan?.title || dir.name;
const looksLikeSpecId = /^\d{3}-/.test(title);
if (looksLikeSpecId && existsSync(specFilePath)) {
try {
const specContent = readFileSync(specFilePath, 'utf-8');
// Extract title from first # line, handling patterns like:
// "# Quick Spec: Title" -> "Title"
// "# Specification: Title" -> "Title"
// "# Title" -> "Title"
const titleMatch = specContent.match(/^#\s+(?:Quick Spec:|Specification:)?\s*(.+)$/m);
if (titleMatch && titleMatch[1]) {
title = titleMatch[1].trim();
}
} catch {
// Keep the original title on error
}
}
tasks.push({
id: dir.name, // Use spec directory name as ID
specId: dir.name,
projectId,
title: plan?.feature || dir.name,
title,
description,
status,
reviewReason,
@@ -312,7 +367,7 @@ export class ProjectStore {
}
}
console.log('[ProjectStore] Returning', tasks.length, 'tasks out of', specDirs.filter(d => d.isDirectory() && d.name !== '.gitkeep').length, 'spec directories');
console.warn('[ProjectStore] Returning', tasks.length, 'tasks out of', specDirs.filter(d => d.isDirectory() && d.name !== '.gitkeep').length, 'spec directories');
return tasks;
}
@@ -0,0 +1,61 @@
import { execSync } from 'child_process';
/**
* Detect and return the best available Python command.
* Tries multiple candidates and returns the first one that works with Python 3.
*
* @returns The Python command to use, or null if none found
*/
export function findPythonCommand(): string | null {
const isWindows = process.platform === 'win32';
// On Windows, try py launcher first (most reliable), then python, then python3
// On Unix, try python3 first, then python
const candidates = isWindows
? ['py -3', 'python', 'python3', 'py']
: ['python3', 'python'];
for (const cmd of candidates) {
try {
const version = execSync(`${cmd} --version`, {
stdio: 'pipe',
timeout: 5000,
windowsHide: true
}).toString();
if (version.includes('Python 3')) {
return cmd;
}
} catch {
// Command not found or errored, try next
continue;
}
}
// Fallback to platform-specific default
return isWindows ? 'python' : 'python3';
}
/**
* Get the default Python command for the current platform.
* This is a synchronous fallback that doesn't test if Python actually exists.
*
* @returns The default Python command for this platform
*/
export function getDefaultPythonCommand(): string {
return process.platform === 'win32' ? 'python' : 'python3';
}
/**
* Parse a Python command string into command and base arguments.
* Handles space-separated commands like "py -3".
*
* @param pythonPath - The Python command string (e.g., "python3", "py -3")
* @returns Tuple of [command, baseArgs] ready for use with spawn()
*/
export function parsePythonCommand(pythonPath: string): [string, string[]] {
const parts = pythonPath.split(' ');
const command = parts[0];
const baseArgs = parts.slice(1);
return [command, baseArgs];
}
+61 -25
View File
@@ -1,5 +1,5 @@
import { spawn, execSync } from 'child_process';
import { existsSync, readFileSync } from 'fs';
import { existsSync } from 'fs';
import path from 'path';
import { EventEmitter } from 'events';
@@ -37,16 +37,11 @@ export class PythonEnvManager extends EventEmitter {
/**
* Get the path to pip in the venv
* Returns null - we use python -m pip instead for better compatibility
* @deprecated Use getVenvPythonPath() with -m pip instead
*/
private getVenvPipPath(): string | null {
if (!this.autoBuildSourcePath) return null;
const venvPip =
process.platform === 'win32'
? path.join(this.autoBuildSourcePath, '.venv', 'Scripts', 'pip.exe')
: path.join(this.autoBuildSourcePath, '.venv', 'bin', 'pip');
return venvPip;
return null; // Not used - we use python -m pip
}
/**
@@ -147,7 +142,7 @@ export class PythonEnvManager extends EventEmitter {
}
this.emit('status', 'Creating Python virtual environment...');
console.log('[PythonEnvManager] Creating venv with:', systemPython);
console.warn('[PythonEnvManager] Creating venv with:', systemPython);
return new Promise((resolve) => {
const venvPath = path.join(this.autoBuildSourcePath!, '.venv');
@@ -163,7 +158,7 @@ export class PythonEnvManager extends EventEmitter {
proc.on('close', (code) => {
if (code === 0) {
console.log('[PythonEnvManager] Venv created successfully');
console.warn('[PythonEnvManager] Venv created successfully');
resolve(true);
} else {
console.error('[PythonEnvManager] Failed to create venv:', stderr);
@@ -181,16 +176,54 @@ export class PythonEnvManager extends EventEmitter {
}
/**
* Install dependencies from requirements.txt
* Bootstrap pip in the venv using ensurepip
*/
private async bootstrapPip(): Promise<boolean> {
const venvPython = this.getVenvPythonPath();
if (!venvPython || !existsSync(venvPython)) {
return false;
}
console.warn('[PythonEnvManager] Bootstrapping pip...');
return new Promise((resolve) => {
const proc = spawn(venvPython, ['-m', 'ensurepip'], {
cwd: this.autoBuildSourcePath!,
stdio: 'pipe'
});
let stderr = '';
proc.stderr?.on('data', (data) => {
stderr += data.toString();
});
proc.on('close', (code) => {
if (code === 0) {
console.warn('[PythonEnvManager] Pip bootstrapped successfully');
resolve(true);
} else {
console.error('[PythonEnvManager] Failed to bootstrap pip:', stderr);
resolve(false);
}
});
proc.on('error', (err) => {
console.error('[PythonEnvManager] Error bootstrapping pip:', err);
resolve(false);
});
});
}
/**
* Install dependencies from requirements.txt using python -m pip
*/
private async installDeps(): Promise<boolean> {
if (!this.autoBuildSourcePath) return false;
const venvPip = this.getVenvPipPath();
const venvPython = this.getVenvPythonPath();
const requirementsPath = path.join(this.autoBuildSourcePath, 'requirements.txt');
if (!venvPip || !existsSync(venvPip)) {
this.emit('error', 'Pip not found in virtual environment');
if (!venvPython || !existsSync(venvPython)) {
this.emit('error', 'Python not found in virtual environment');
return false;
}
@@ -199,11 +232,15 @@ export class PythonEnvManager extends EventEmitter {
return false;
}
// Bootstrap pip first if needed
await this.bootstrapPip();
this.emit('status', 'Installing Python dependencies (this may take a minute)...');
console.log('[PythonEnvManager] Installing dependencies from:', requirementsPath);
console.warn('[PythonEnvManager] Installing dependencies from:', requirementsPath);
return new Promise((resolve) => {
const proc = spawn(venvPip, ['install', '-r', requirementsPath], {
// Use python -m pip for better compatibility across Python versions
const proc = spawn(venvPython, ['-m', 'pip', 'install', '-r', requirementsPath], {
cwd: this.autoBuildSourcePath!,
stdio: 'pipe'
});
@@ -228,7 +265,7 @@ export class PythonEnvManager extends EventEmitter {
proc.on('close', (code) => {
if (code === 0) {
console.log('[PythonEnvManager] Dependencies installed successfully');
console.warn('[PythonEnvManager] Dependencies installed successfully');
this.emit('status', 'Dependencies installed successfully');
resolve(true);
} else {
@@ -264,12 +301,12 @@ export class PythonEnvManager extends EventEmitter {
this.isInitializing = true;
this.autoBuildSourcePath = autoBuildSourcePath;
console.log('[PythonEnvManager] Initializing with path:', autoBuildSourcePath);
console.warn('[PythonEnvManager] Initializing with path:', autoBuildSourcePath);
try {
// Check if venv exists
if (!this.venvExists()) {
console.log('[PythonEnvManager] Venv not found, creating...');
console.warn('[PythonEnvManager] Venv not found, creating...');
const created = await this.createVenv();
if (!created) {
this.isInitializing = false;
@@ -282,13 +319,13 @@ export class PythonEnvManager extends EventEmitter {
};
}
} else {
console.log('[PythonEnvManager] Venv already exists');
console.warn('[PythonEnvManager] Venv already exists');
}
// Check if deps are installed
const depsInstalled = await this.checkDepsInstalled();
if (!depsInstalled) {
console.log('[PythonEnvManager] Dependencies not installed, installing...');
console.warn('[PythonEnvManager] Dependencies not installed, installing...');
const installed = await this.installDeps();
if (!installed) {
this.isInitializing = false;
@@ -301,7 +338,7 @@ export class PythonEnvManager extends EventEmitter {
};
}
} else {
console.log('[PythonEnvManager] Dependencies already installed');
console.warn('[PythonEnvManager] Dependencies already installed');
}
this.pythonPath = this.getVenvPythonPath();
@@ -309,7 +346,7 @@ export class PythonEnvManager extends EventEmitter {
this.isInitializing = false;
this.emit('ready', this.pythonPath);
console.log('[PythonEnvManager] Ready with Python path:', this.pythonPath);
console.warn('[PythonEnvManager] Ready with Python path:', this.pythonPath);
return {
ready: true,
@@ -362,4 +399,3 @@ export class PythonEnvManager extends EventEmitter {
// Singleton instance
export const pythonEnvManager = new PythonEnvManager();
+118 -8
View File
@@ -22,6 +22,26 @@ const RATE_LIMIT_INDICATORS = [
/too\s*many\s*requests/i
];
/**
* Patterns that indicate authentication failures
* These patterns detect when Claude CLI/SDK fails due to missing or invalid auth
*/
const AUTH_FAILURE_PATTERNS = [
/authentication\s*(is\s*)?required/i,
/not\s*(yet\s*)?authenticated/i,
/login\s*(is\s*)?required/i,
/oauth\s*token\s*(is\s*)?(invalid|expired|missing)/i,
/unauthorized/i,
/please\s*(log\s*in|login|authenticate)/i,
/invalid\s*(credentials|token|api\s*key)/i,
/auth(entication)?\s*(failed|error|failure)/i,
/session\s*(expired|invalid)/i,
/access\s*denied/i,
/permission\s*denied/i,
/401\s*unauthorized/i,
/credentials\s*(are\s*)?(missing|invalid|expired)/i
];
/**
* Result of rate limit detection
*/
@@ -43,6 +63,22 @@ export interface RateLimitDetectionResult {
originalError?: string;
}
/**
* Result of authentication failure detection
*/
export interface AuthFailureDetectionResult {
/** Whether an authentication failure was detected */
isAuthFailure: boolean;
/** The profile ID that failed to authenticate (if known) */
profileId?: string;
/** The type of auth failure detected */
failureType?: 'missing' | 'invalid' | 'expired' | 'unknown';
/** User-friendly message describing the failure */
message?: string;
/** Original error message from the process output */
originalError?: string;
}
/**
* Classify rate limit type based on reset time string
*/
@@ -132,6 +168,80 @@ export function extractResetTime(output: string): string | null {
return match ? match[1].trim() : null;
}
/**
* Classify the type of authentication failure based on the error message
*/
function classifyAuthFailureType(output: string): 'missing' | 'invalid' | 'expired' | 'unknown' {
const lowerOutput = output.toLowerCase();
if (/missing|not\s*(yet\s*)?authenticated|required/.test(lowerOutput)) {
return 'missing';
}
if (/expired|session\s*expired/.test(lowerOutput)) {
return 'expired';
}
if (/invalid|unauthorized|denied/.test(lowerOutput)) {
return 'invalid';
}
return 'unknown';
}
/**
* Get a user-friendly message for the authentication failure
*/
function getAuthFailureMessage(failureType: 'missing' | 'invalid' | 'expired' | 'unknown'): string {
switch (failureType) {
case 'missing':
return 'Claude authentication required. Please go to Settings > Claude Profiles and authenticate your account.';
case 'expired':
return 'Your Claude session has expired. Please re-authenticate in Settings > Claude Profiles.';
case 'invalid':
return 'Invalid Claude credentials. Please check your OAuth token or re-authenticate in Settings > Claude Profiles.';
case 'unknown':
default:
return 'Claude authentication failed. Please verify your authentication in Settings > Claude Profiles.';
}
}
/**
* Detect authentication failure from output (stdout + stderr combined)
*/
export function detectAuthFailure(
output: string,
profileId?: string
): AuthFailureDetectionResult {
// First, make sure this isn't a rate limit error (those should be handled separately)
if (detectRateLimit(output).isRateLimited) {
return { isAuthFailure: false };
}
// Check for authentication failure patterns
for (const pattern of AUTH_FAILURE_PATTERNS) {
if (pattern.test(output)) {
const profileManager = getClaudeProfileManager();
const effectiveProfileId = profileId || profileManager.getActiveProfile().id;
const failureType = classifyAuthFailureType(output);
return {
isAuthFailure: true,
profileId: effectiveProfileId,
failureType,
message: getAuthFailureMessage(failureType),
originalError: output
};
}
}
return { isAuthFailure: false };
}
/**
* Check if output contains authentication failure error
*/
export function isAuthFailureError(output: string): boolean {
return detectAuthFailure(output).isAuthFailure;
}
/**
* Get environment variables for a specific Claude profile.
* Uses OAuth token (CLAUDE_CODE_OAUTH_TOKEN) if available, otherwise falls back to CLAUDE_CONFIG_DIR.
@@ -144,7 +254,7 @@ export function getProfileEnv(profileId?: string): Record<string, string> {
? profileManager.getProfile(profileId)
: profileManager.getActiveProfile();
console.log('[getProfileEnv] Active profile:', {
console.warn('[getProfileEnv] Active profile:', {
profileId: profile?.id,
profileName: profile?.name,
email: profile?.email,
@@ -154,19 +264,19 @@ export function getProfileEnv(profileId?: string): Record<string, string> {
});
if (!profile) {
console.log('[getProfileEnv] No profile found, using defaults');
console.warn('[getProfileEnv] No profile found, using defaults');
return {};
}
// Prefer OAuth token (instant switching, no browser auth needed)
// Use profile manager to get decrypted token
if (profile.oauthToken) {
const decryptedToken = profileId
const decryptedToken = profileId
? profileManager.getProfileToken(profileId)
: profileManager.getActiveProfileToken();
if (decryptedToken) {
console.log('[getProfileEnv] Using OAuth token for profile:', profile.name);
console.warn('[getProfileEnv] Using OAuth token for profile:', profile.name);
return {
CLAUDE_CODE_OAUTH_TOKEN: decryptedToken
};
@@ -177,20 +287,20 @@ export function getProfileEnv(profileId?: string): Record<string, string> {
// Fallback: If default profile, no env vars needed
if (profile.isDefault) {
console.log('[getProfileEnv] Using default profile (no env vars)');
console.warn('[getProfileEnv] Using default profile (no env vars)');
return {};
}
// Fallback: Use configDir for profiles without OAuth token (legacy)
if (profile.configDir) {
console.log('[getProfileEnv] Using configDir fallback for profile:', profile.name);
console.warn('[getProfileEnv] Using configDir fallback for profile:', profile.name);
console.warn('[getProfileEnv] WARNING: Profile has no OAuth token. Run "claude setup-token" and save the token to enable instant switching.');
return {
CLAUDE_CONFIG_DIR: profile.configDir
};
}
console.log('[getProfileEnv] Profile has no auth method configured');
console.warn('[getProfileEnv] Profile has no auth method configured');
return {};
}
+211 -28
View File
@@ -1,6 +1,6 @@
import { EventEmitter } from 'events';
import path from 'path';
import { existsSync, readFileSync, readdirSync } from 'fs';
import { existsSync, readFileSync, readdirSync, writeFileSync } from 'fs';
import { execSync, spawn } from 'child_process';
import type {
ReleaseableVersion,
@@ -17,7 +17,7 @@ import { DEFAULT_CHANGELOG_PATH } from '../shared/constants';
/**
* Service for creating GitHub releases with worktree-aware pre-flight checks.
*
*
* Key feature: Worktree checks are SCOPED to tasks in the release version.
* If a worktree exists for a task NOT in this release, it won't block the release.
*/
@@ -32,7 +32,7 @@ export class ReleaseService extends EventEmitter {
*/
parseChangelogVersions(projectPath: string): ReleaseableVersion[] {
const changelogPath = path.join(projectPath, DEFAULT_CHANGELOG_PATH);
if (!existsSync(changelogPath)) {
return [];
}
@@ -49,7 +49,7 @@ export class ReleaseService extends EventEmitter {
const version = match[1];
const date = match[2] || '';
const startIndex = match.index! + match[0].length;
// Content is until next version header or end of file
const endIndex = i < matches.length - 1 ? matches[i + 1].index! : content.length;
const versionContent = content.slice(startIndex, endIndex).trim();
@@ -98,17 +98,17 @@ export class ReleaseService extends EventEmitter {
tasks: Task[]
): Promise<ReleaseableVersion[]> {
const versions = this.parseChangelogVersions(projectPath);
// Populate task spec IDs for each version
for (const version of versions) {
const { specIds } = this.getTasksForVersion(projectPath, version.version, tasks);
version.taskSpecIds = specIds;
// Check if already released on GitHub
try {
const tagExists = this.checkTagExists(projectPath, version.tagName);
version.isReleased = tagExists;
if (tagExists) {
// Try to get release URL
version.releaseUrl = this.getGitHubReleaseUrl(projectPath, version.tagName);
@@ -129,11 +129,11 @@ export class ReleaseService extends EventEmitter {
try {
// Check local tags
execSync(`git tag -l "${tagName}"`, { cwd: projectPath, encoding: 'utf-8' });
const localTags = execSync(`git tag -l "${tagName}"`, {
cwd: projectPath,
encoding: 'utf-8'
const localTags = execSync(`git tag -l "${tagName}"`, {
cwd: projectPath,
encoding: 'utf-8'
}).trim();
if (localTags) return true;
// Check remote tags
@@ -147,7 +147,7 @@ export class ReleaseService extends EventEmitter {
cwd: projectPath,
encoding: 'utf-8'
}).trim();
return !!remoteTags;
} catch {
return false;
@@ -166,7 +166,7 @@ export class ReleaseService extends EventEmitter {
cwd: projectPath,
encoding: 'utf-8'
}).trim();
return result || undefined;
} catch {
return undefined;
@@ -175,7 +175,7 @@ export class ReleaseService extends EventEmitter {
/**
* Run pre-flight checks for a specific version.
*
*
* IMPORTANT: Worktree checks are scoped to tasks in this version only.
* Worktrees for other tasks (future releases) won't block this release.
*/
@@ -186,7 +186,7 @@ export class ReleaseService extends EventEmitter {
): Promise<ReleasePreflightStatus> {
const tagName = `v${version}`;
const { specIds } = this.getTasksForVersion(projectPath, version, tasks);
const status: ReleasePreflightStatus = {
canRelease: false,
checks: {
@@ -303,7 +303,7 @@ export class ReleaseService extends EventEmitter {
if (unmergedWorktrees.length === 0) {
status.checks.worktreesMerged = {
passed: true,
message: specIds.length > 0
message: specIds.length > 0
? `All ${specIds.length} feature(s) in this release are merged`
: 'No features to check (version may have been manually added)',
unmergedWorktrees: []
@@ -314,7 +314,7 @@ export class ReleaseService extends EventEmitter {
message: `${unmergedWorktrees.length} feature(s) have unmerged worktrees`,
unmergedWorktrees
};
for (const wt of unmergedWorktrees) {
status.blockers.push(
`Feature "${wt.taskTitle}" (${wt.specId}) has unmerged changes in worktree`
@@ -330,7 +330,7 @@ export class ReleaseService extends EventEmitter {
/**
* Check worktrees ONLY for tasks that are part of this release version.
*
*
* This is the key function that scopes worktree checks to the release:
* - If a task is in the release AND has an unmerged worktree BLOCK
* - If a task is NOT in the release but has a worktree IGNORE (it's for a future release)
@@ -344,7 +344,7 @@ export class ReleaseService extends EventEmitter {
// Get worktrees directory
const worktreesDir = path.join(projectPath, '.worktrees', 'auto-claude');
if (!existsSync(worktreesDir)) {
// No worktrees exist at all - all clear
return [];
@@ -364,7 +364,7 @@ export class ReleaseService extends EventEmitter {
for (const specId of releaseSpecIds) {
// Find the worktree folder for this spec
// Spec IDs are like "001-feature-name", worktree folders match
const worktreeFolder = worktreeFolders.find(folder =>
const worktreeFolder = worktreeFolders.find(folder =>
folder === specId || folder.startsWith(`${specId}-`)
);
@@ -374,7 +374,7 @@ export class ReleaseService extends EventEmitter {
}
const worktreePath = path.join(worktreesDir, worktreeFolder);
// Get the task info for better error messages
const task = tasks.find(t => t.specId === specId);
const taskTitle = task?.title || specId;
@@ -442,7 +442,7 @@ export class ReleaseService extends EventEmitter {
cwd: worktreePath,
encoding: 'utf-8'
}).trim();
return !hasChanges;
}
@@ -454,7 +454,167 @@ export class ReleaseService extends EventEmitter {
}
/**
* Create a GitHub release.
* Bump version in package.json with safe git workflow.
* Preserves user's current work by stashing, switching to main, then restoring.
*/
async bumpVersion(
projectPath: string,
version: string,
mainBranch: string,
projectId: string
): Promise<{ success: boolean; error?: string }> {
// Save current state
let originalBranch: string;
let hadChanges = false;
let stashCreated = false;
try {
originalBranch = execSync('git rev-parse --abbrev-ref HEAD', {
cwd: projectPath,
encoding: 'utf-8'
}).trim();
} catch {
return { success: false, error: 'Failed to get current git branch' };
}
// Check for uncommitted changes
const gitStatus = execSync('git status --porcelain', {
cwd: projectPath,
encoding: 'utf-8'
}).trim();
hadChanges = !!gitStatus;
try {
// Stash any changes (staged or unstaged)
if (hadChanges) {
this.emitProgress(projectId, {
stage: 'bumping_version',
progress: 5,
message: 'Stashing current changes...'
});
execSync('git stash push -m "auto-claude-release-temp"', {
cwd: projectPath,
encoding: 'utf-8'
});
stashCreated = true;
}
// Checkout main branch
this.emitProgress(projectId, {
stage: 'bumping_version',
progress: 10,
message: `Switching to ${mainBranch}...`
});
if (originalBranch !== mainBranch) {
execSync(`git checkout "${mainBranch}"`, {
cwd: projectPath,
encoding: 'utf-8'
});
}
// Pull latest from origin
this.emitProgress(projectId, {
stage: 'bumping_version',
progress: 15,
message: `Pulling latest from origin/${mainBranch}...`
});
try {
execSync(`git pull origin "${mainBranch}"`, {
cwd: projectPath,
encoding: 'utf-8'
});
} catch {
// Pull might fail if no upstream, continue anyway
}
// Update package.json
this.emitProgress(projectId, {
stage: 'bumping_version',
progress: 20,
message: `Updating package.json to ${version}...`
});
const pkgPath = path.join(projectPath, 'package.json');
if (!existsSync(pkgPath)) {
throw new Error('package.json not found in project root');
}
const pkgContent = readFileSync(pkgPath, 'utf-8');
const pkg = JSON.parse(pkgContent);
pkg.version = version;
// Preserve formatting (detect indent)
const indent = pkgContent.match(/^(\s+)/m)?.[1] || ' ';
writeFileSync(pkgPath, JSON.stringify(pkg, null, indent) + '\n');
// Stage and commit only package.json
this.emitProgress(projectId, {
stage: 'bumping_version',
progress: 25,
message: 'Committing version bump...'
});
execSync('git add package.json', {
cwd: projectPath,
encoding: 'utf-8'
});
execSync(`git commit -m "chore: release v${version}"`, {
cwd: projectPath,
encoding: 'utf-8'
});
// Push to origin
this.emitProgress(projectId, {
stage: 'bumping_version',
progress: 30,
message: `Pushing to origin/${mainBranch}...`
});
execSync(`git push origin "${mainBranch}"`, {
cwd: projectPath,
encoding: 'utf-8'
});
return { success: true };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
return { success: false, error: errorMessage };
} finally {
// Always restore user's original state
try {
if (originalBranch !== mainBranch) {
execSync(`git checkout "${originalBranch}"`, {
cwd: projectPath,
encoding: 'utf-8'
});
}
} catch {
// Log but don't fail - user might need to manually switch back
console.warn('[ReleaseService] Failed to restore original branch');
}
if (stashCreated) {
try {
execSync('git stash pop', {
cwd: projectPath,
encoding: 'utf-8'
});
} catch {
// Stash conflict - warn user
console.warn('[ReleaseService] Failed to pop stash - user may need to run "git stash pop" manually');
}
}
}
}
/**
* Create a GitHub release with optional version bump.
*/
async createRelease(
projectPath: string,
@@ -462,12 +622,36 @@ export class ReleaseService extends EventEmitter {
): Promise<CreateReleaseResult> {
const tagName = `v${request.version}`;
const title = request.title || tagName;
const shouldBumpVersion = request.bumpVersion !== false; // Default to true
try {
// Stage 0: Bump version in package.json (if enabled)
if (shouldBumpVersion && request.mainBranch) {
const bumpResult = await this.bumpVersion(
projectPath,
request.version,
request.mainBranch,
request.projectId
);
if (!bumpResult.success) {
this.emitProgress(request.projectId, {
stage: 'error',
progress: 0,
message: `Version bump failed: ${bumpResult.error}`,
error: bumpResult.error
});
return {
success: false,
error: `Version bump failed: ${bumpResult.error}`
};
}
}
// Stage 1: Create local tag
this.emitProgress(request.projectId, {
stage: 'tagging',
progress: 25,
progress: 40,
message: `Creating tag ${tagName}...`
});
@@ -479,7 +663,7 @@ export class ReleaseService extends EventEmitter {
// Stage 2: Push tag to remote
this.emitProgress(request.projectId, {
stage: 'pushing',
progress: 50,
progress: 60,
message: `Pushing tag ${tagName} to origin...`
});
@@ -491,7 +675,7 @@ export class ReleaseService extends EventEmitter {
// Stage 3: Create GitHub release
this.emitProgress(request.projectId, {
stage: 'creating_release',
progress: 75,
progress: 80,
message: 'Creating GitHub release...'
});
@@ -567,7 +751,7 @@ export class ReleaseService extends EventEmitter {
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
// Try to clean up the tag if it was created but release failed
try {
execSync(`git tag -d "${tagName}" 2>/dev/null || true`, {
@@ -602,4 +786,3 @@ export class ReleaseService extends EventEmitter {
// Export singleton instance
export const releaseService = new ReleaseService();
+16 -7
View File
@@ -1,5 +1,5 @@
import path from 'path';
import { existsSync, readFileSync, watchFile, unwatchFile, FSWatcher } from 'fs';
import { existsSync, readFileSync, watchFile } from 'fs';
import { EventEmitter } from 'events';
import type { TaskLogs, TaskLogPhase, TaskLogStreamChunk, TaskPhaseLog } from '../shared/types';
@@ -32,6 +32,7 @@ export class TaskLogService extends EventEmitter {
/**
* Load task logs from a single spec directory
* Returns cached logs if the file is corrupted (e.g., mid-write by Python backend)
*/
loadLogsFromPath(specDir: string): TaskLogs | null {
const logFile = path.join(specDir, 'task_logs.json');
@@ -43,8 +44,16 @@ export class TaskLogService extends EventEmitter {
try {
const content = readFileSync(logFile, 'utf-8');
const logs = JSON.parse(content) as TaskLogs;
this.logCache.set(specDir, logs);
return logs;
} catch (error) {
// JSON parse error - file may be mid-write, return cached version if available
const cached = this.logCache.get(specDir);
if (cached) {
// Silently return cached version - this is expected during concurrent access
return cached;
}
// Only log if we have no cached fallback
console.error(`[TaskLogService] Failed to load logs from ${logFile}:`, error);
return null;
}
@@ -189,7 +198,7 @@ export class TaskLogService extends EventEmitter {
if (existsSync(mainLogFile)) {
try {
lastMainContent = readFileSync(mainLogFile, 'utf-8');
} catch (e) {
} catch (_e) {
// Ignore parse errors on initial load
}
}
@@ -200,7 +209,7 @@ export class TaskLogService extends EventEmitter {
if (existsSync(worktreeLogFile)) {
try {
lastWorktreeContent = readFileSync(worktreeLogFile, 'utf-8');
} catch (e) {
} catch (_e) {
// Ignore parse errors on initial load
}
}
@@ -225,7 +234,7 @@ export class TaskLogService extends EventEmitter {
lastMainContent = currentContent;
mainChanged = true;
}
} catch (error) {
} catch (_error) {
// Ignore read/parse errors
}
}
@@ -240,7 +249,7 @@ export class TaskLogService extends EventEmitter {
lastWorktreeContent = currentContent;
worktreeChanged = true;
}
} catch (error) {
} catch (_error) {
// Ignore read/parse errors
}
}
@@ -262,7 +271,7 @@ export class TaskLogService extends EventEmitter {
}, this.POLL_INTERVAL_MS);
this.pollIntervals.set(specId, pollInterval);
console.log(`[TaskLogService] Started watching ${specId} (main: ${specDir}${worktreeSpecDir ? `, worktree: ${worktreeSpecDir}` : ''})`);
console.warn(`[TaskLogService] Started watching ${specId} (main: ${specDir}${worktreeSpecDir ? `, worktree: ${worktreeSpecDir}` : ''})`);
}
/**
@@ -274,7 +283,7 @@ export class TaskLogService extends EventEmitter {
clearInterval(interval);
this.pollIntervals.delete(specId);
this.watchedPaths.delete(specId);
console.log(`[TaskLogService] Stopped watching ${specId}`);
console.warn(`[TaskLogService] Stopped watching ${specId}`);
}
}
@@ -4,6 +4,7 @@ import { spawn } from 'child_process';
import { app } from 'electron';
import { EventEmitter } from 'events';
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from './rate-limit-detector';
import { findPythonCommand, parsePythonCommand } from './python-detector';
/**
* Debug logging - only logs when AUTO_CLAUDE_DEBUG env var is set
@@ -12,7 +13,7 @@ const DEBUG = process.env.AUTO_CLAUDE_DEBUG === 'true' || process.env.AUTO_CLAUD
function debug(...args: unknown[]): void {
if (DEBUG) {
console.log('[TerminalNameGenerator]', ...args);
console.warn('[TerminalNameGenerator]', ...args);
}
}
@@ -20,7 +21,8 @@ function debug(...args: unknown[]): void {
* Service for generating terminal names from commands using Claude AI
*/
export class TerminalNameGenerator extends EventEmitter {
private pythonPath: string = 'python3';
// Auto-detect Python command on initialization
private pythonPath: string = findPythonCommand() || 'python';
private autoBuildSourcePath: string = '';
constructor() {
@@ -55,7 +57,8 @@ export class TerminalNameGenerator extends EventEmitter {
];
for (const p of possiblePaths) {
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
// Use requirements.txt as marker - it always exists in auto-claude source
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
return p;
}
}
@@ -129,13 +132,17 @@ export class TerminalNameGenerator extends EventEmitter {
const profileEnv = getProfileEnv();
return new Promise((resolve) => {
const childProcess = spawn(this.pythonPath, ['-c', script], {
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.pythonPath);
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, '-c', script], {
cwd: autoBuildSource,
env: {
...process.env,
...autoBuildEnv,
...profileEnv, // Include active Claude profile config
PYTHONUNBUFFERED: '1'
PYTHONUNBUFFERED: '1',
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
}
});
@@ -100,7 +100,7 @@ export class TerminalSessionStore {
// Migrate from v1 to v2 structure
if (data.version === 1 && data.sessions) {
console.log('[TerminalSessionStore] Migrating from v1 to v2 structure');
console.warn('[TerminalSessionStore] Migrating from v1 to v2 structure');
const today = getDateString();
const migratedData: SessionData = {
version: STORE_VERSION,
@@ -115,7 +115,7 @@ export class TerminalSessionStore {
return data as SessionData;
}
console.log('[TerminalSessionStore] Version mismatch, resetting sessions');
console.warn('[TerminalSessionStore] Version mismatch, resetting sessions');
return { version: STORE_VERSION, sessionsByDate: {} };
}
} catch (error) {
@@ -155,7 +155,7 @@ export class TerminalSessionStore {
}
if (removedCount > 0) {
console.log(`[TerminalSessionStore] Cleaned up sessions from ${removedCount} old dates`);
console.warn(`[TerminalSessionStore] Cleaned up sessions from ${removedCount} old dates`);
this.save();
}
}
@@ -225,7 +225,7 @@ export class TerminalSessionStore {
if (dates.length > 0) {
const mostRecentDate = dates[0];
console.log(`[TerminalSessionStore] No sessions today, using sessions from ${mostRecentDate}`);
console.warn(`[TerminalSessionStore] No sessions today, using sessions from ${mostRecentDate}`);
return this.data.sessionsByDate[mostRecentDate][projectPath] || [];
}
@@ -361,7 +361,7 @@ export class TerminalSessionStore {
session.claudeSessionId = claudeSessionId;
session.isClaudeMode = true;
this.save();
console.log('[TerminalSessionStore] Saved Claude session ID:', claudeSessionId, 'for terminal:', terminalId);
console.warn('[TerminalSessionStore] Saved Claude session ID:', claudeSessionId, 'for terminal:', terminalId);
}
}
@@ -6,11 +6,12 @@
import * as os from 'os';
import * as fs from 'fs';
import * as path from 'path';
import type { BrowserWindow } from 'electron';
import { IPC_CHANNELS } from '../../shared/constants';
import { getClaudeProfileManager } from '../claude-profile-manager';
import * as OutputParser from './output-parser';
import * as SessionHandler from './session-handler';
import { debugLog, debugError } from '../../shared/utils/debug-logger';
import { escapeShellArg, buildCdCommand } from '../../shared/utils/shell-escape';
import type {
TerminalProcess,
WindowGetter,
@@ -39,14 +40,14 @@ export function handleRateLimit(
}
lastNotifiedRateLimitReset.set(terminal.id, resetTime);
console.log('[ClaudeIntegration] Rate limit detected, reset:', resetTime);
console.warn('[ClaudeIntegration] Rate limit detected, reset:', resetTime);
const profileManager = getClaudeProfileManager();
const currentProfileId = terminal.claudeProfileId || 'default';
try {
const rateLimitEvent = profileManager.recordRateLimitEvent(currentProfileId, resetTime);
console.log('[ClaudeIntegration] Recorded rate limit event:', rateLimitEvent.type);
console.warn('[ClaudeIntegration] Recorded rate limit event:', rateLimitEvent.type);
} catch (err) {
console.error('[ClaudeIntegration] Failed to record rate limit event:', err);
}
@@ -68,9 +69,9 @@ export function handleRateLimit(
}
if (autoSwitchSettings.enabled && autoSwitchSettings.autoSwitchOnRateLimit && bestProfile) {
console.log('[ClaudeIntegration] Auto-switching to profile:', bestProfile.name);
switchProfileCallback(terminal.id, bestProfile.id).then(result => {
console.log('[ClaudeIntegration] Auto-switch completed');
console.warn('[ClaudeIntegration] Auto-switching to profile:', bestProfile.name);
switchProfileCallback(terminal.id, bestProfile.id).then(_result => {
console.warn('[ClaudeIntegration] Auto-switch completed');
}).catch(err => {
console.error('[ClaudeIntegration] Auto-switch failed:', err);
});
@@ -90,18 +91,20 @@ export function handleOAuthToken(
return;
}
console.log('[ClaudeIntegration] OAuth token detected, length:', token.length);
console.warn('[ClaudeIntegration] OAuth token detected, length:', token.length);
const email = OutputParser.extractEmail(terminal.outputBuffer);
const profileIdMatch = terminal.id.match(/claude-login-(profile-\d+)-/);
// Match both custom profiles (profile-123456) and the default profile
const profileIdMatch = terminal.id.match(/claude-login-(profile-\d+|default)-/);
if (profileIdMatch) {
// Save to specific profile (profile login terminal)
const profileId = profileIdMatch[1];
const profileManager = getClaudeProfileManager();
const success = profileManager.setProfileToken(profileId, token, email || undefined);
if (success) {
console.log('[ClaudeIntegration] OAuth token auto-saved to profile:', profileId);
console.warn('[ClaudeIntegration] OAuth token auto-saved to profile:', profileId);
const win = getWindow();
if (win) {
@@ -117,16 +120,56 @@ export function handleOAuthToken(
console.error('[ClaudeIntegration] Failed to save OAuth token to profile:', profileId);
}
} else {
console.log('[ClaudeIntegration] OAuth token detected but not in a profile login terminal');
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
email,
success: false,
message: 'Token detected but no profile associated with this terminal',
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
// No profile-specific terminal, save to active profile (GitHub OAuth flow, etc.)
console.warn('[ClaudeIntegration] OAuth token detected in non-profile terminal, saving to active profile');
const profileManager = getClaudeProfileManager();
const activeProfile = profileManager.getActiveProfile();
// Defensive null check for active profile
if (!activeProfile) {
console.error('[ClaudeIntegration] Failed to save OAuth token: no active profile found');
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;
}
const success = profileManager.setProfileToken(activeProfile.id, token, email || undefined);
if (success) {
console.warn('[ClaudeIntegration] OAuth token auto-saved to active profile:', activeProfile.name);
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);
}
} else {
console.error('[ClaudeIntegration] Failed to save OAuth token to active profile:', activeProfile.name);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
terminalId: terminal.id,
profileId: activeProfile?.id,
email,
success: false,
message: 'Failed to save token to active profile',
detectedAt: new Date().toISOString()
} as OAuthTokenEvent);
}
}
}
}
@@ -140,7 +183,7 @@ export function handleClaudeSessionId(
getWindow: WindowGetter
): void {
terminal.claudeSessionId = sessionId;
console.log('[ClaudeIntegration] Captured Claude session ID:', sessionId);
console.warn('[ClaudeIntegration] Captured Claude session ID:', sessionId);
if (terminal.projectPath) {
SessionHandler.updateClaudeSessionId(terminal.projectPath, terminal.id, sessionId);
@@ -162,6 +205,11 @@ export function invokeClaude(
getWindow: WindowGetter,
onSessionCapture: (terminalId: string, projectPath: string, startTime: number) => void
): void {
debugLog('[ClaudeIntegration:invokeClaude] ========== INVOKE CLAUDE START ==========');
debugLog('[ClaudeIntegration:invokeClaude] Terminal ID:', terminal.id);
debugLog('[ClaudeIntegration:invokeClaude] Requested profile ID:', profileId);
debugLog('[ClaudeIntegration:invokeClaude] CWD:', cwd);
terminal.isClaudeMode = true;
terminal.claudeSessionId = undefined;
@@ -176,31 +224,70 @@ export function invokeClaude(
const previousProfileId = terminal.claudeProfileId;
terminal.claudeProfileId = activeProfile?.id;
const cwdCommand = cwd ? `cd "${cwd}" && ` : '';
debugLog('[ClaudeIntegration:invokeClaude] Profile resolution:', {
previousProfileId,
newProfileId: activeProfile?.id,
profileName: activeProfile?.name,
hasOAuthToken: !!activeProfile?.oauthToken,
isDefault: activeProfile?.isDefault
});
// Use safe shell escaping to prevent command injection
const cwdCommand = buildCdCommand(cwd);
const needsEnvOverride = profileId && profileId !== previousProfileId;
debugLog('[ClaudeIntegration:invokeClaude] Environment override check:', {
profileIdProvided: !!profileId,
previousProfileId,
needsEnvOverride
});
if (needsEnvOverride && activeProfile && !activeProfile.isDefault) {
const token = profileManager.getProfileToken(activeProfile.id);
debugLog('[ClaudeIntegration:invokeClaude] Token retrieval:', {
hasToken: !!token,
tokenLength: token?.length
});
if (token) {
const tempFile = path.join(os.tmpdir(), `.claude-token-${Date.now()}`);
debugLog('[ClaudeIntegration:invokeClaude] Writing token to temp file:', tempFile);
fs.writeFileSync(tempFile, `export CLAUDE_CODE_OAUTH_TOKEN="${token}"\n`, { mode: 0o600 });
terminal.pty.write(`${cwdCommand}source "${tempFile}" && rm -f "${tempFile}" && claude\r`);
console.log('[ClaudeIntegration] Switching to Claude profile:', activeProfile.name, '(via secure temp file)');
// Clear terminal and run command without adding to shell history:
// - HISTFILE= disables history file writing for the current command
// - HISTCONTROL=ignorespace causes commands starting with space to be ignored
// - Leading space ensures the command is ignored even if HISTCONTROL was already set
// - Uses subshell (...) to isolate environment changes
// This prevents temp file paths from appearing in shell history
const command = `clear && ${cwdCommand} HISTFILE= HISTCONTROL=ignorespace bash -c 'source "${tempFile}" && rm -f "${tempFile}" && exec claude'\r`;
debugLog('[ClaudeIntegration:invokeClaude] Executing command (temp file method, history-safe)');
terminal.pty.write(command);
debugLog('[ClaudeIntegration:invokeClaude] ========== INVOKE CLAUDE COMPLETE (temp file) ==========');
return;
} else if (activeProfile.configDir) {
terminal.pty.write(`${cwdCommand}CLAUDE_CONFIG_DIR="${activeProfile.configDir}" claude\r`);
console.log('[ClaudeIntegration] Using Claude profile:', activeProfile.name, 'config:', activeProfile.configDir);
// Clear terminal and run command without adding to shell history:
// Same history-disabling technique as temp file method above
// SECURITY: Use escapeShellArg for configDir to prevent command injection
// Set CLAUDE_CONFIG_DIR as env var before bash -c to avoid embedding user input in the command string
const escapedConfigDir = escapeShellArg(activeProfile.configDir);
const command = `clear && ${cwdCommand}HISTFILE= HISTCONTROL=ignorespace CLAUDE_CONFIG_DIR=${escapedConfigDir} bash -c 'exec claude'\r`;
debugLog('[ClaudeIntegration:invokeClaude] Executing command (configDir method, history-safe)');
terminal.pty.write(command);
debugLog('[ClaudeIntegration:invokeClaude] ========== INVOKE CLAUDE COMPLETE (configDir) ==========');
return;
} else {
debugLog('[ClaudeIntegration:invokeClaude] WARNING: No token or configDir available for non-default profile');
}
}
if (activeProfile && !activeProfile.isDefault) {
console.log('[ClaudeIntegration] Using Claude profile:', activeProfile.name, '(from terminal environment)');
debugLog('[ClaudeIntegration:invokeClaude] Using terminal environment for non-default profile:', activeProfile.name);
}
terminal.pty.write(`${cwdCommand}claude\r`);
const command = `${cwdCommand}claude\r`;
debugLog('[ClaudeIntegration:invokeClaude] Executing command (default method):', command);
terminal.pty.write(command);
if (activeProfile) {
profileManager.markProfileUsed(activeProfile.id);
@@ -221,6 +308,8 @@ export function invokeClaude(
if (projectPath) {
onSessionCapture(terminal.id, projectPath, startTime);
}
debugLog('[ClaudeIntegration:invokeClaude] ========== INVOKE CLAUDE COMPLETE (default) ==========');
}
/**
@@ -235,7 +324,8 @@ export function resumeClaude(
let command: string;
if (sessionId) {
command = `claude --resume "${sessionId}"`;
// SECURITY: Escape sessionId to prevent command injection
command = `claude --resume ${escapeShellArg(sessionId)}`;
terminal.claudeSessionId = sessionId;
} else {
command = 'claude --continue';
@@ -249,6 +339,103 @@ export function resumeClaude(
}
}
/**
* Configuration for waiting for Claude to exit
*/
interface WaitForExitConfig {
/** Maximum time to wait for Claude to exit (ms) */
timeout?: number;
/** Interval between checks (ms) */
pollInterval?: number;
}
/**
* Result of waiting for Claude to exit
*/
interface WaitForExitResult {
/** Whether Claude exited successfully */
success: boolean;
/** Error message if failed */
error?: string;
/** Whether the operation timed out */
timedOut?: boolean;
}
/**
* Shell prompt patterns that indicate Claude has exited and shell is ready
* These patterns match common shell prompts across bash, zsh, fish, etc.
*/
const SHELL_PROMPT_PATTERNS = [
/[$%#>]\s*$/m, // Common prompt endings: $, %, #, >,
/\w+@[\w.-]+[:\s]/, // user@hostname: format
/^\s*\S+\s*[$%#>]\s*$/m, // hostname/path followed by prompt char
/\(.*\)\s*[$%#>]\s*$/m, // (venv) or (branch) followed by prompt
];
/**
* Wait for Claude to exit by monitoring terminal output for shell prompt
*
* Instead of using fixed delays, this monitors the terminal's outputBuffer
* for patterns indicating that Claude has exited and the shell prompt is visible.
*/
async function waitForClaudeExit(
terminal: TerminalProcess,
config: WaitForExitConfig = {}
): Promise<WaitForExitResult> {
const { timeout = 5000, pollInterval = 100 } = config;
debugLog('[ClaudeIntegration:waitForClaudeExit] Waiting for Claude to exit...');
debugLog('[ClaudeIntegration:waitForClaudeExit] Config:', { timeout, pollInterval });
// Capture current buffer length to detect new output
const initialBufferLength = terminal.outputBuffer.length;
const startTime = Date.now();
return new Promise((resolve) => {
const checkForPrompt = () => {
const elapsed = Date.now() - startTime;
// Check for timeout
if (elapsed >= timeout) {
console.warn('[ClaudeIntegration:waitForClaudeExit] Timeout waiting for Claude to exit after', timeout, 'ms');
debugLog('[ClaudeIntegration:waitForClaudeExit] Timeout reached, Claude may not have exited cleanly');
resolve({
success: false,
error: `Timeout waiting for Claude to exit after ${timeout}ms`,
timedOut: true
});
return;
}
// Get new output since we started waiting
const newOutput = terminal.outputBuffer.slice(initialBufferLength);
// Check if we can see a shell prompt in the new output
for (const pattern of SHELL_PROMPT_PATTERNS) {
if (pattern.test(newOutput)) {
debugLog('[ClaudeIntegration:waitForClaudeExit] Shell prompt detected after', elapsed, 'ms');
debugLog('[ClaudeIntegration:waitForClaudeExit] Matched pattern:', pattern.toString());
resolve({ success: true });
return;
}
}
// Also check if isClaudeMode was cleared (set by other handlers)
if (!terminal.isClaudeMode) {
debugLog('[ClaudeIntegration:waitForClaudeExit] isClaudeMode flag cleared after', elapsed, 'ms');
resolve({ success: true });
return;
}
// Continue polling
setTimeout(checkForPrompt, pollInterval);
};
// Start checking
checkForPrompt();
});
}
/**
* Switch terminal to a different Claude profile
*/
@@ -259,27 +446,95 @@ export async function switchClaudeProfile(
invokeClaudeCallback: (terminalId: string, cwd: string | undefined, profileId: string) => void,
clearRateLimitCallback: (terminalId: string) => void
): Promise<{ success: boolean; error?: string }> {
// Always-on tracing
console.warn('[ClaudeIntegration:switchClaudeProfile] Called for terminal:', terminal.id, '| profileId:', profileId);
console.warn('[ClaudeIntegration:switchClaudeProfile] Terminal state: isClaudeMode=', terminal.isClaudeMode);
debugLog('[ClaudeIntegration:switchClaudeProfile] ========== SWITCH PROFILE START ==========');
debugLog('[ClaudeIntegration:switchClaudeProfile] Terminal ID:', terminal.id);
debugLog('[ClaudeIntegration:switchClaudeProfile] Target profile ID:', profileId);
debugLog('[ClaudeIntegration:switchClaudeProfile] Terminal state:', {
isClaudeMode: terminal.isClaudeMode,
currentProfileId: terminal.claudeProfileId,
claudeSessionId: terminal.claudeSessionId,
projectPath: terminal.projectPath,
cwd: terminal.cwd
});
const profileManager = getClaudeProfileManager();
const profile = profileManager.getProfile(profileId);
console.warn('[ClaudeIntegration:switchClaudeProfile] Profile found:', profile?.name || 'NOT FOUND');
debugLog('[ClaudeIntegration:switchClaudeProfile] Target profile:', profile ? {
id: profile.id,
name: profile.name,
hasOAuthToken: !!profile.oauthToken,
isDefault: profile.isDefault
} : 'NOT FOUND');
if (!profile) {
console.error('[ClaudeIntegration:switchClaudeProfile] Profile not found, aborting');
debugError('[ClaudeIntegration:switchClaudeProfile] Profile not found, aborting');
return { success: false, error: 'Profile not found' };
}
console.log('[ClaudeIntegration] Switching to Claude profile:', profile.name);
console.warn('[ClaudeIntegration:switchClaudeProfile] Switching to profile:', profile.name);
debugLog('[ClaudeIntegration:switchClaudeProfile] Switching to Claude profile:', profile.name);
if (terminal.isClaudeMode) {
console.warn('[ClaudeIntegration:switchClaudeProfile] Sending exit commands (Ctrl+C, /exit)');
debugLog('[ClaudeIntegration:switchClaudeProfile] Terminal is in Claude mode, sending exit commands');
// Send Ctrl+C to interrupt any ongoing operation
debugLog('[ClaudeIntegration:switchClaudeProfile] Sending Ctrl+C (\\x03)');
terminal.pty.write('\x03');
await new Promise(resolve => setTimeout(resolve, 500));
// Wait briefly for Ctrl+C to take effect before sending /exit
await new Promise(resolve => setTimeout(resolve, 100));
// Send /exit command
debugLog('[ClaudeIntegration:switchClaudeProfile] Sending /exit command');
terminal.pty.write('/exit\r');
await new Promise(resolve => setTimeout(resolve, 500));
// Wait for Claude to actually exit by monitoring for shell prompt
const exitResult = await waitForClaudeExit(terminal, { timeout: 5000, pollInterval: 100 });
if (exitResult.timedOut) {
console.warn('[ClaudeIntegration:switchClaudeProfile] Timed out waiting for Claude to exit, proceeding with caution');
debugLog('[ClaudeIntegration:switchClaudeProfile] Exit timeout - terminal may be in inconsistent state');
// Even on timeout, we'll try to proceed but log the warning
// The alternative would be to abort, but that could leave users stuck
// If this becomes a problem, we could add retry logic or abort option
} else if (!exitResult.success) {
console.error('[ClaudeIntegration:switchClaudeProfile] Failed to exit Claude:', exitResult.error);
debugError('[ClaudeIntegration:switchClaudeProfile] Exit failed:', exitResult.error);
// Continue anyway - the /exit command was sent
} else {
console.warn('[ClaudeIntegration:switchClaudeProfile] Claude exited successfully');
debugLog('[ClaudeIntegration:switchClaudeProfile] Claude exited, ready to switch profile');
}
} else {
console.warn('[ClaudeIntegration:switchClaudeProfile] NOT in Claude mode, skipping exit commands');
debugLog('[ClaudeIntegration:switchClaudeProfile] Terminal NOT in Claude mode, skipping exit commands');
}
debugLog('[ClaudeIntegration:switchClaudeProfile] Clearing rate limit state for terminal');
clearRateLimitCallback(terminal.id);
const projectPath = terminal.projectPath || terminal.cwd;
console.warn('[ClaudeIntegration:switchClaudeProfile] Invoking Claude with profile:', profileId, '| cwd:', projectPath);
debugLog('[ClaudeIntegration:switchClaudeProfile] Invoking Claude with new profile:', {
terminalId: terminal.id,
projectPath,
profileId
});
invokeClaudeCallback(terminal.id, projectPath, profileId);
debugLog('[ClaudeIntegration:switchClaudeProfile] Setting active profile in profile manager');
profileManager.setActiveProfile(profileId);
console.warn('[ClaudeIntegration:switchClaudeProfile] COMPLETE');
debugLog('[ClaudeIntegration:switchClaudeProfile] ========== SWITCH PROFILE COMPLETE ==========');
return { success: true };
}
@@ -0,0 +1,413 @@
/**
* PTY Daemon Client
*
* Communicates with the PTY daemon process via Unix socket/named pipe.
* Handles connection management, automatic reconnection, and message routing.
*/
import * as net from 'net';
import * as path from 'path';
import { spawn, ChildProcess } from 'child_process';
import { app } from 'electron';
const SOCKET_PATH =
process.platform === 'win32'
? `\\\\.\\pipe\\auto-claude-pty-${process.getuid?.() || 'default'}`
: `/tmp/auto-claude-pty-${process.getuid?.() || 'default'}.sock`;
interface DaemonResponseData {
exitCode?: number;
signal?: number;
}
interface DaemonResponse {
requestId?: string;
type: string;
id?: string;
data?: string | DaemonResponseData;
error?: string;
}
type ResponseHandler = (response: DaemonResponse) => void;
interface PtyConfig {
shell: string;
shellArgs: string[];
cwd: string;
env: Record<string, string>;
rows: number;
cols: number;
}
interface PtyInfo {
id: string;
config: PtyConfig;
createdAt: number;
lastDataAt: number;
isDead: boolean;
bufferSize: number;
}
class PtyDaemonClient {
private socket: net.Socket | null = null;
private daemonProcess: ChildProcess | null = null;
private pendingRequests = new Map<string, ResponseHandler>();
private dataHandlers = new Map<string, (data: string) => void>();
private exitHandlers = new Map<string, (exitCode: number, signal?: number) => void>();
private reconnectAttempts = 0;
private maxReconnectAttempts = 5;
private isConnecting = false;
private buffer = '';
private isShuttingDown = false;
/**
* Connect to daemon, spawning if necessary
*/
async connect(): Promise<void> {
if (this.isShuttingDown) {
throw new Error('Client is shutting down');
}
if (this.socket || this.isConnecting) return;
this.isConnecting = true;
try {
// Try to connect to existing daemon
await this.tryConnect();
console.warn('[PtyDaemonClient] Connected to existing daemon');
} catch {
// Spawn daemon and connect
console.warn('[PtyDaemonClient] Spawning new daemon...');
await this.spawnDaemon();
await this.tryConnect();
console.warn('[PtyDaemonClient] Connected to new daemon');
} finally {
this.isConnecting = false;
this.reconnectAttempts = 0;
}
}
/**
* Try to connect to existing daemon
*/
private tryConnect(): Promise<void> {
return new Promise((resolve, reject) => {
const socket = net.connect(SOCKET_PATH);
const timeout = setTimeout(() => {
socket.destroy();
reject(new Error('Connection timeout'));
}, 3000);
socket.on('connect', () => {
clearTimeout(timeout);
this.socket = socket;
this.setupSocketHandlers();
resolve();
});
socket.on('error', (err) => {
clearTimeout(timeout);
reject(err);
});
});
}
/**
* Spawn a new daemon process
*/
private async spawnDaemon(): Promise<void> {
// In production, the daemon file is in the same directory
const daemonPath = path.join(__dirname, 'pty-daemon.js');
try {
// Spawn detached process that survives parent
this.daemonProcess = spawn(process.execPath, [daemonPath], {
detached: true,
stdio: 'ignore', // Don't pipe stdout/stderr
env: { ...process.env },
});
// Unref so parent can exit independently
this.daemonProcess.unref();
console.warn(`[PtyDaemonClient] Spawned daemon process (PID: ${this.daemonProcess.pid})`);
// Wait for daemon to start listening
await new Promise((resolve) => setTimeout(resolve, 1000));
} catch (error) {
console.error('[PtyDaemonClient] Failed to spawn daemon:', error);
throw error;
}
}
/**
* Setup socket event handlers
*/
private setupSocketHandlers(): void {
if (!this.socket) return;
this.socket.on('data', (chunk) => {
this.buffer += chunk.toString();
// Handle newline-delimited JSON
const lines = this.buffer.split('\n');
this.buffer = lines.pop() || '';
for (const line of lines) {
if (!line.trim()) continue;
try {
const response = JSON.parse(line);
this.handleResponse(response);
} catch (e) {
console.error('[PtyDaemonClient] Invalid response:', e);
}
}
});
this.socket.on('close', () => {
console.warn('[PtyDaemonClient] Disconnected from daemon');
this.socket = null;
if (!this.isShuttingDown) {
this.attemptReconnect();
}
});
this.socket.on('error', (err) => {
console.error('[PtyDaemonClient] Socket error:', err);
});
}
/**
* Handle response from daemon
*/
private handleResponse(response: DaemonResponse): void {
// Handle request-response pattern
if (response.requestId) {
const handler = this.pendingRequests.get(response.requestId);
if (handler) {
this.pendingRequests.delete(response.requestId);
handler(response);
}
return;
}
// Handle streaming data
if (response.type === 'data' && response.id) {
const handler = this.dataHandlers.get(response.id);
if (handler && typeof response.data === 'string') {
handler(response.data);
}
return;
}
// Handle exit events
if (response.type === 'exit' && response.id) {
const handler = this.exitHandlers.get(response.id);
if (handler && typeof response.data === 'object' && response.data !== null) {
const exitData = response.data as DaemonResponseData;
handler(exitData.exitCode ?? 0, exitData.signal);
}
return;
}
}
/**
* Attempt to reconnect with exponential backoff
*/
private attemptReconnect(): void {
if (this.isShuttingDown) return;
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.error('[PtyDaemonClient] Max reconnect attempts reached');
return;
}
this.reconnectAttempts++;
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 10000);
console.warn(
`[PtyDaemonClient] Reconnect attempt ${this.reconnectAttempts} in ${delay}ms...`
);
setTimeout(() => {
this.connect().catch((error) => {
console.error('[PtyDaemonClient] Reconnect failed:', error);
});
}, delay);
}
/**
* Send a request and wait for response
*/
private async request<T>(msg: Record<string, unknown>): Promise<T> {
await this.connect();
if (!this.socket) {
throw new Error('Not connected to daemon');
}
const requestId = `req-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
this.pendingRequests.delete(requestId);
reject(new Error('Request timeout'));
}, 10000);
this.pendingRequests.set(requestId, (response) => {
clearTimeout(timeout);
if (response.type === 'error') {
reject(new Error(response.error || 'Unknown error'));
} else {
resolve(response as T);
}
});
this.socket!.write(JSON.stringify({ ...msg, requestId }) + '\n');
});
}
/**
* Send a message without expecting a response
*/
private send(msg: Record<string, unknown>): void {
if (!this.socket) {
console.warn('[PtyDaemonClient] Cannot send - not connected');
return;
}
this.socket.write(JSON.stringify(msg) + '\n');
}
// ===== Public API =====
/**
* Create a new PTY in the daemon
*/
async createPty(config: PtyConfig): Promise<string> {
const response = await this.request<{ type: 'created'; id: string }>({
type: 'create',
data: config,
});
return response.id;
}
/**
* Write data to a PTY
*/
write(id: string, data: string): void {
this.send({ type: 'write', id, data });
}
/**
* Resize a PTY
*/
resize(id: string, cols: number, rows: number): void {
this.send({ type: 'resize', id, data: { cols, rows } });
}
/**
* Kill a PTY
*/
kill(id: string): void {
this.send({ type: 'kill', id });
this.dataHandlers.delete(id);
this.exitHandlers.delete(id);
}
/**
* List all PTYs in the daemon
*/
async list(): Promise<PtyInfo[]> {
const response = await this.request<{ type: 'list'; data: PtyInfo[] }>({
type: 'list',
});
return response.data;
}
/**
* Subscribe to PTY output and exit events
*/
subscribe(
id: string,
onData: (data: string) => void,
onExit: (code: number, signal?: number) => void
): void {
this.dataHandlers.set(id, onData);
this.exitHandlers.set(id, onExit);
this.send({ type: 'subscribe', id });
}
/**
* Unsubscribe from PTY events
*/
unsubscribe(id: string): void {
this.dataHandlers.delete(id);
this.exitHandlers.delete(id);
this.send({ type: 'unsubscribe', id });
}
/**
* Get buffered output from a PTY
*/
async getBuffer(id: string): Promise<{ buffer: string; isDead: boolean }> {
const response = await this.request<{
type: 'buffer';
data: { buffer: string; isDead: boolean };
}>({
type: 'get-buffer',
id,
});
return response.data;
}
/**
* Check if daemon is alive
*/
async ping(): Promise<boolean> {
try {
await this.request<{ type: 'pong' }>({ type: 'ping' });
return true;
} catch {
return false;
}
}
/**
* Check if connected
*/
isConnected(): boolean {
return this.socket !== null;
}
/**
* Disconnect from daemon (does not kill daemon)
*/
disconnect(): void {
if (this.socket) {
this.isShuttingDown = true;
this.socket.end();
this.socket = null;
}
}
/**
* Cleanup on app shutdown
*/
shutdown(): void {
this.isShuttingDown = true;
this.disconnect();
this.pendingRequests.clear();
this.dataHandlers.clear();
this.exitHandlers.clear();
}
}
// Singleton instance
export const ptyDaemonClient = new PtyDaemonClient();
// Cleanup on app quit
app.on('before-quit', () => {
ptyDaemonClient.shutdown();
});
@@ -0,0 +1,499 @@
#!/usr/bin/env node
/**
* PTY Daemon Process
*
* Runs as a separate detached process that owns all PTY instances.
* Survives main Electron process restarts, providing session continuity.
*
* Communication: Unix socket (Linux/macOS) or Named Pipe (Windows)
*/
import * as net from 'net';
import * as fs from 'fs';
import * as pty from '@lydell/node-pty';
const SOCKET_PATH =
process.platform === 'win32'
? `\\\\.\\pipe\\auto-claude-pty-${process.getuid?.() || 'default'}`
: `/tmp/auto-claude-pty-${process.getuid?.() || 'default'}.sock`;
// Maximum buffer size per PTY (100KB)
const MAX_BUFFER_SIZE = 100_000;
// Ring buffer to prevent memory growth
const RING_BUFFER_MAX_CHUNKS = 1000;
interface ManagedPty {
id: string;
process: pty.IPty;
config: PtyConfig;
buffer: string[];
bufferSize: number;
clients: Set<net.Socket>;
createdAt: number;
lastDataAt: number;
isDead: boolean;
}
interface PtyConfig {
shell: string;
shellArgs: string[];
cwd: string;
env: Record<string, string>;
rows: number;
cols: number;
}
interface DaemonMessage {
type:
| 'create'
| 'write'
| 'resize'
| 'kill'
| 'list'
| 'subscribe'
| 'unsubscribe'
| 'get-buffer'
| 'ping';
id?: string;
data?: unknown;
requestId?: string;
}
interface DaemonResponse {
type: 'created' | 'list' | 'buffer' | 'data' | 'exit' | 'error' | 'pong';
id?: string;
data?: unknown;
requestId?: string;
error?: string;
}
class PtyDaemon {
private ptys = new Map<string, ManagedPty>();
private server: net.Server | null = null;
constructor() {
console.error('[PTY Daemon] Starting...');
this.cleanup();
this.startServer();
this.setupSignalHandlers();
}
/**
* Remove stale socket/pipe
*/
private cleanup(): void {
if (process.platform !== 'win32' && fs.existsSync(SOCKET_PATH)) {
try {
fs.unlinkSync(SOCKET_PATH);
console.error('[PTY Daemon] Cleaned up stale socket');
} catch (error) {
console.error('[PTY Daemon] Failed to clean up socket:', error);
}
}
}
/**
* Start the IPC server
*/
private startServer(): void {
this.server = net.createServer((socket) => {
console.error('[PTY Daemon] Client connected');
this.handleConnection(socket);
});
this.server.on('error', (err: NodeJS.ErrnoException) => {
console.error('[PTY Daemon] Server error:', err);
if (err.code === 'EADDRINUSE') {
console.error('[PTY Daemon] Address in use - another daemon may be running');
process.exit(1);
}
});
this.server.listen(SOCKET_PATH, () => {
console.error(`[PTY Daemon] Listening on ${SOCKET_PATH}`);
// Set permissions on Unix
if (process.platform !== 'win32') {
try {
fs.chmodSync(SOCKET_PATH, 0o600);
} catch (error) {
console.error('[PTY Daemon] Failed to set socket permissions:', error);
}
}
});
}
/**
* Handle a client connection
*/
private handleConnection(socket: net.Socket): void {
let buffer = '';
socket.on('data', (chunk) => {
buffer += chunk.toString();
// Handle newline-delimited JSON messages
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.trim()) continue;
try {
const msg: DaemonMessage = JSON.parse(line);
this.handleMessage(socket, msg);
} catch (e) {
console.error('[PTY Daemon] Invalid message:', e);
this.sendError(socket, 'Invalid JSON message');
}
}
});
socket.on('close', () => {
console.error('[PTY Daemon] Client disconnected');
// Unsubscribe from all PTYs
this.ptys.forEach((pty) => {
pty.clients.delete(socket);
});
});
socket.on('error', (err) => {
console.error('[PTY Daemon] Socket error:', err);
});
}
/**
* Handle incoming message from client
*/
private handleMessage(socket: net.Socket, msg: DaemonMessage): void {
try {
switch (msg.type) {
case 'ping':
this.send(socket, { type: 'pong', requestId: msg.requestId });
break;
case 'create': {
const id = this.createPty(msg.data as PtyConfig);
this.send(socket, { type: 'created', id, requestId: msg.requestId });
break;
}
case 'write':
if (!msg.id) throw new Error('Missing PTY id');
this.writeToPty(msg.id, msg.data as string);
break;
case 'resize': {
if (!msg.id) throw new Error('Missing PTY id');
const resizeData = msg.data as { cols: number; rows: number };
this.resizePty(msg.id, resizeData.cols, resizeData.rows);
break;
}
case 'kill':
if (!msg.id) throw new Error('Missing PTY id');
this.killPty(msg.id);
break;
case 'list': {
const list = this.listPtys();
this.send(socket, { type: 'list', data: list, requestId: msg.requestId });
break;
}
case 'subscribe':
if (!msg.id) throw new Error('Missing PTY id');
this.subscribeToPty(socket, msg.id);
break;
case 'unsubscribe':
if (!msg.id) throw new Error('Missing PTY id');
this.unsubscribeFromPty(socket, msg.id);
break;
case 'get-buffer': {
if (!msg.id) throw new Error('Missing PTY id');
const bufferData = this.getBuffer(msg.id);
this.send(socket, {
type: 'buffer',
id: msg.id,
data: bufferData,
requestId: msg.requestId,
});
break;
}
default:
throw new Error(`Unknown message type: ${(msg as DaemonMessage).type}`);
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
console.error('[PTY Daemon] Error handling message:', errorMsg);
this.sendError(socket, errorMsg, msg.requestId);
}
}
/**
* Create a new PTY
*/
private createPty(config: PtyConfig): string {
const id = `pty-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
try {
const ptyProcess = pty.spawn(config.shell, config.shellArgs, {
name: 'xterm-256color',
cols: config.cols,
rows: config.rows,
cwd: config.cwd,
env: config.env,
});
const managed: ManagedPty = {
id,
process: ptyProcess,
config,
buffer: [],
bufferSize: 0,
clients: new Set(),
createdAt: Date.now(),
lastDataAt: Date.now(),
isDead: false,
};
// Capture all output
ptyProcess.onData((data) => {
managed.lastDataAt = Date.now();
// Add to ring buffer
managed.buffer.push(data);
managed.bufferSize += data.length;
// Enforce buffer size limit
while (managed.bufferSize > MAX_BUFFER_SIZE && managed.buffer.length > 1) {
const removed = managed.buffer.shift();
if (removed) {
managed.bufferSize -= removed.length;
}
}
// Also enforce chunk count limit (ring buffer behavior)
while (managed.buffer.length > RING_BUFFER_MAX_CHUNKS) {
const removed = managed.buffer.shift();
if (removed) {
managed.bufferSize -= removed.length;
}
}
// Broadcast to all subscribers
managed.clients.forEach((client) => {
this.send(client, { type: 'data', id, data });
});
});
ptyProcess.onExit(({ exitCode, signal }) => {
console.error(`[PTY Daemon] PTY ${id} exited: code=${exitCode}, signal=${signal}`);
managed.isDead = true;
// Notify all subscribers
managed.clients.forEach((client) => {
this.send(client, { type: 'exit', id, data: { exitCode, signal } });
});
// Keep in map for buffer retrieval, will be cleaned up on explicit kill
});
this.ptys.set(id, managed);
console.error(`[PTY Daemon] Created PTY ${id} (${config.shell})`);
return id;
} catch (error) {
console.error('[PTY Daemon] Failed to create PTY:', error);
throw error;
}
}
/**
* Write data to a PTY
*/
private writeToPty(id: string, data: string): void {
const managed = this.ptys.get(id);
if (!managed) {
throw new Error(`PTY ${id} not found`);
}
if (managed.isDead) {
throw new Error(`PTY ${id} is dead`);
}
managed.process.write(data);
}
/**
* Resize a PTY
*/
private resizePty(id: string, cols: number, rows: number): void {
const managed = this.ptys.get(id);
if (!managed) {
throw new Error(`PTY ${id} not found`);
}
if (managed.isDead) {
console.warn(`[PTY Daemon] Cannot resize dead PTY ${id}`);
return;
}
managed.process.resize(cols, rows);
managed.config.cols = cols;
managed.config.rows = rows;
}
/**
* Kill a PTY and remove it
*/
private killPty(id: string): void {
const managed = this.ptys.get(id);
if (!managed) {
console.warn(`[PTY Daemon] PTY ${id} not found for kill`);
return;
}
if (!managed.isDead) {
try {
managed.process.kill();
} catch (error) {
console.error(`[PTY Daemon] Error killing PTY ${id}:`, error);
}
}
this.ptys.delete(id);
console.error(`[PTY Daemon] Removed PTY ${id}`);
}
/**
* List all PTYs
*/
private listPtys(): Array<{
id: string;
config: PtyConfig;
createdAt: number;
lastDataAt: number;
isDead: boolean;
bufferSize: number;
}> {
return Array.from(this.ptys.values()).map((m) => ({
id: m.id,
config: m.config,
createdAt: m.createdAt,
lastDataAt: m.lastDataAt,
isDead: m.isDead,
bufferSize: m.bufferSize,
}));
}
/**
* Subscribe a client to PTY output
*/
private subscribeToPty(socket: net.Socket, id: string): void {
const managed = this.ptys.get(id);
if (!managed) {
throw new Error(`PTY ${id} not found`);
}
managed.clients.add(socket);
console.error(`[PTY Daemon] Client subscribed to PTY ${id}`);
}
/**
* Unsubscribe a client from PTY output
*/
private unsubscribeFromPty(socket: net.Socket, id: string): void {
const managed = this.ptys.get(id);
if (managed) {
managed.clients.delete(socket);
console.error(`[PTY Daemon] Client unsubscribed from PTY ${id}`);
}
}
/**
* Get the buffered output for a PTY
*/
private getBuffer(id: string): { buffer: string; isDead: boolean } {
const managed = this.ptys.get(id);
if (!managed) {
throw new Error(`PTY ${id} not found`);
}
return {
buffer: managed.buffer.join(''),
isDead: managed.isDead,
};
}
/**
* Send a response to a client
*/
private send(socket: net.Socket, response: DaemonResponse): void {
try {
socket.write(JSON.stringify(response) + '\n');
} catch {
// Socket may be closed, ignore
console.warn('[PTY Daemon] Failed to send response (socket closed?)');
}
}
/**
* Send an error response
*/
private sendError(socket: net.Socket, error: string, requestId?: string): void {
this.send(socket, { type: 'error', error, requestId });
}
/**
* Setup signal handlers for graceful shutdown
*/
private setupSignalHandlers(): void {
const shutdown = (signal: string) => {
console.error(`[PTY Daemon] Received ${signal}, shutting down...`);
// Kill all PTYs
this.ptys.forEach((managed) => {
if (!managed.isDead) {
try {
managed.process.kill();
} catch (error) {
console.error(`[PTY Daemon] Error killing PTY ${managed.id}:`, error);
}
}
});
// Close server
this.server?.close();
// Remove socket
this.cleanup();
console.error('[PTY Daemon] Shutdown complete');
process.exit(0);
};
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
// Handle uncaught errors
process.on('uncaughtException', (error) => {
console.error('[PTY Daemon] Uncaught exception:', error);
// Don't exit - daemon should be resilient
});
process.on('unhandledRejection', (reason) => {
console.error('[PTY Daemon] Unhandled rejection:', reason);
// Don't exit - daemon should be resilient
});
}
}
// Start daemon if this file is run directly
if (require.main === module) {
try {
new PtyDaemon();
console.error('[PTY Daemon] Running - PID:', process.pid);
} catch (error) {
console.error('[PTY Daemon] Fatal error:', error);
process.exit(1);
}
}
export { PtyDaemon };
@@ -3,9 +3,9 @@
* Handles low-level PTY process creation and lifecycle
*/
import * as pty from 'node-pty';
import * as pty from '@lydell/node-pty';
import * as os from 'os';
import type { TerminalProcess, WindowGetter, TerminalOperationResult } from './types';
import type { TerminalProcess, WindowGetter } from './types';
import { IPC_CHANNELS } from '../../shared/constants';
import { getClaudeProfileManager } from '../claude-profile-manager';
@@ -24,7 +24,7 @@ export function spawnPtyProcess(
const shellArgs = process.platform === 'win32' ? [] : ['-l'];
console.log('[PtyManager] Spawning shell:', shell, shellArgs);
console.warn('[PtyManager] Spawning shell:', shell, shellArgs);
return pty.spawn(shell, shellArgs, {
name: 'xterm-256color',
@@ -69,7 +69,7 @@ export function setupPtyHandlers(
// Handle terminal exit
ptyProcess.onExit(({ exitCode }) => {
console.log('[PtyManager] Terminal exited:', id, 'code:', exitCode);
console.warn('[PtyManager] Terminal exited:', id, 'code:', exitCode);
const win = getWindow();
if (win) {
@@ -6,9 +6,10 @@
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import type { TerminalProcess, WindowGetter, SessionCaptureResult } from './types';
import type { TerminalProcess, WindowGetter } from './types';
import { getTerminalSessionStore, type TerminalSession } from '../terminal-session-store';
import { IPC_CHANNELS } from '../../shared/constants';
import { debugLog, debugError } from '../../shared/utils/debug-logger';
/**
* Get the Claude project slug from a project path.
@@ -27,7 +28,7 @@ export function findMostRecentClaudeSession(projectPath: string): string | null
try {
if (!fs.existsSync(claudeProjectDir)) {
console.log('[SessionHandler] Claude project directory not found:', claudeProjectDir);
debugLog('[SessionHandler] Claude project directory not found:', claudeProjectDir);
return null;
}
@@ -41,15 +42,15 @@ export function findMostRecentClaudeSession(projectPath: string): string | null
.sort((a, b) => b.mtime - a.mtime);
if (files.length === 0) {
console.log('[SessionHandler] No Claude session files found in:', claudeProjectDir);
debugLog('[SessionHandler] No Claude session files found in:', claudeProjectDir);
return null;
}
const sessionId = files[0].name.replace('.jsonl', '');
console.log('[SessionHandler] Found most recent Claude session:', sessionId);
debugLog('[SessionHandler] Found most recent Claude session:', sessionId);
return sessionId;
} catch (error) {
console.error('[SessionHandler] Error finding Claude session:', error);
debugError('[SessionHandler] Error finding Claude session:', error);
return null;
}
}
@@ -82,7 +83,7 @@ export function findClaudeSessionAfter(projectPath: string, afterTimestamp: numb
return files[0].name.replace('.jsonl', '');
} catch (error) {
console.error('[SessionHandler] Error finding Claude session:', error);
debugError('[SessionHandler] Error finding Claude session:', error);
return null;
}
}
@@ -114,7 +115,7 @@ export function persistSession(terminal: TerminalProcess): void {
* Persist all active sessions
*/
export function persistAllSessions(terminals: Map<string, TerminalProcess>): void {
const store = getTerminalSessionStore();
const _store = getTerminalSessionStore();
terminals.forEach((terminal) => {
if (terminal.projectPath) {
@@ -210,7 +211,7 @@ export function captureClaudeSessionId(
if (sessionId) {
terminal.claudeSessionId = sessionId;
console.log('[SessionHandler] Captured Claude session ID from directory:', sessionId);
debugLog('[SessionHandler] Captured Claude session ID from directory:', sessionId);
if (terminal.projectPath) {
updateClaudeSessionId(terminal.projectPath, terminalId, sessionId);
@@ -223,7 +224,7 @@ export function captureClaudeSessionId(
} else if (attempts < maxAttempts) {
setTimeout(checkForSession, 1000);
} else {
console.log('[SessionHandler] Could not capture Claude session ID after', maxAttempts, 'attempts');
debugLog('[SessionHandler] Could not capture Claude session ID after', maxAttempts, 'attempts');
}
};
@@ -0,0 +1,325 @@
/**
* Terminal Session Persistence
*
* Handles saving and loading terminal session state to disk.
* This is the fallback recovery layer when the PTY daemon is not available.
*/
import { app } from 'electron';
import * as fs from 'fs';
import * as path from 'path';
import type {
TerminalSessionState,
TerminalSessionsFile,
TerminalRecoveryInfo,
} from '../../shared/types/terminal-session';
const SESSIONS_FILE = path.join(app.getPath('userData'), 'terminal-sessions.json');
const BUFFERS_DIR = path.join(app.getPath('userData'), 'terminal-buffers');
// Session age limit: 7 days
const MAX_SESSION_AGE_MS = 7 * 24 * 60 * 60 * 1000;
class SessionPersistence {
private sessions: Map<string, TerminalSessionState> = new Map();
private saveTimeout: NodeJS.Timeout | null = null;
private isInitialized = false;
constructor() {
this.ensureDirectories();
}
/**
* Ensure required directories exist
*/
private ensureDirectories(): void {
if (!fs.existsSync(BUFFERS_DIR)) {
fs.mkdirSync(BUFFERS_DIR, { recursive: true });
}
}
/**
* Initialize and load sessions on app start
*/
initialize(): TerminalRecoveryInfo {
if (this.isInitialized) {
return this.getRecoveryInfo();
}
const sessions = this.loadSessions();
this.isInitialized = true;
console.warn(`[SessionPersistence] Initialized with ${sessions.length} sessions`);
return this.getRecoveryInfo();
}
/**
* Load sessions from disk
*/
loadSessions(): TerminalSessionState[] {
if (!fs.existsSync(SESSIONS_FILE)) {
return [];
}
try {
const data: TerminalSessionsFile = JSON.parse(
fs.readFileSync(SESSIONS_FILE, 'utf8')
);
// Validate version
if (data.version !== 2) {
console.warn('[SessionPersistence] Incompatible version, starting fresh');
return [];
}
// Filter out stale sessions (older than 7 days)
const now = Date.now();
const validSessions = data.sessions.filter(
(s) => now - s.lastActiveAt < MAX_SESSION_AGE_MS
);
// Clean up buffers for stale sessions
const staleSessions = data.sessions.filter(
(s) => now - s.lastActiveAt >= MAX_SESSION_AGE_MS
);
staleSessions.forEach((s) => {
if (s.bufferFile) {
this.deleteBufferFile(s.bufferFile);
}
});
validSessions.forEach((s) => this.sessions.set(s.id, s));
console.warn(
`[SessionPersistence] Loaded ${validSessions.length} valid sessions, cleaned ${staleSessions.length} stale sessions`
);
return validSessions;
} catch (error) {
console.error('[SessionPersistence] Failed to load sessions:', error);
return [];
}
}
/**
* Get recovery information for UI
*/
getRecoveryInfo(): TerminalRecoveryInfo {
const sessions = Array.from(this.sessions.values());
return {
totalSessions: sessions.length,
recoverableSessions: sessions.filter((s) => s.bufferFile || s.daemonPtyId).length,
recoveryMethod: sessions.some((s) => s.daemonPtyId) ? 'daemon' : 'state',
sessions: sessions.map((s) => ({
id: s.id,
title: s.title,
isClaudeMode: s.isClaudeMode,
lastActiveAt: s.lastActiveAt,
hasBuffer: !!s.bufferFile,
hasDaemonPty: !!s.daemonPtyId,
})),
};
}
/**
* Save a session (debounced)
*/
saveSession(session: TerminalSessionState): void {
session.lastActiveAt = Date.now();
this.sessions.set(session.id, session);
this.scheduleSave();
}
/**
* Update session metadata without triggering full save
*/
updateSessionMetadata(
id: string,
updates: Partial<Pick<TerminalSessionState, 'title' | 'isClaudeMode' | 'claudeSessionId' | 'daemonPtyId'>>
): void {
const session = this.sessions.get(id);
if (!session) return;
Object.assign(session, updates);
session.lastActiveAt = Date.now();
this.scheduleSave();
}
/**
* Get a session by ID
*/
getSession(id: string): TerminalSessionState | undefined {
return this.sessions.get(id);
}
/**
* Get all sessions
*/
getAllSessions(): TerminalSessionState[] {
return Array.from(this.sessions.values());
}
/**
* Remove a session
*/
removeSession(id: string): void {
const session = this.sessions.get(id);
if (session?.bufferFile) {
this.deleteBufferFile(session.bufferFile);
}
this.sessions.delete(id);
this.scheduleSave();
}
/**
* Save buffer content to disk
*/
saveBuffer(sessionId: string, serializedBuffer: string): void {
const session = this.sessions.get(sessionId);
if (!session) {
console.warn(`[SessionPersistence] Cannot save buffer - session ${sessionId} not found`);
return;
}
const bufferFile = `buffer-${sessionId}.txt`;
const bufferPath = path.join(BUFFERS_DIR, bufferFile);
try {
fs.writeFileSync(bufferPath, serializedBuffer, 'utf8');
session.bufferFile = bufferFile;
this.saveSession(session);
console.warn(`[SessionPersistence] Saved buffer for session ${sessionId} (${serializedBuffer.length} bytes)`);
} catch (error) {
console.error(`[SessionPersistence] Failed to save buffer for ${sessionId}:`, error);
}
}
/**
* Load buffer content from disk
*/
loadBuffer(sessionId: string): string | null {
const session = this.sessions.get(sessionId);
if (!session?.bufferFile) return null;
const bufferPath = path.join(BUFFERS_DIR, session.bufferFile);
if (!fs.existsSync(bufferPath)) {
console.warn(`[SessionPersistence] Buffer file missing: ${session.bufferFile}`);
return null;
}
try {
return fs.readFileSync(bufferPath, 'utf8');
} catch (error) {
console.error(`[SessionPersistence] Failed to load buffer for ${sessionId}:`, error);
return null;
}
}
/**
* Delete a buffer file
*/
private deleteBufferFile(bufferFile: string): void {
const bufferPath = path.join(BUFFERS_DIR, bufferFile);
if (fs.existsSync(bufferPath)) {
try {
fs.unlinkSync(bufferPath);
console.warn(`[SessionPersistence] Deleted buffer file: ${bufferFile}`);
} catch (error) {
console.error(`[SessionPersistence] Failed to delete buffer file ${bufferFile}:`, error);
}
}
}
/**
* Debounced save to prevent excessive disk I/O
*/
private scheduleSave(): void {
if (this.saveTimeout) {
clearTimeout(this.saveTimeout);
}
this.saveTimeout = setTimeout(() => {
this.saveToDisk();
}, 1000); // 1 second debounce
}
/**
* Immediate save (call before app quit)
*/
saveNow(): void {
if (this.saveTimeout) {
clearTimeout(this.saveTimeout);
this.saveTimeout = null;
}
this.saveToDisk();
}
/**
* Perform the actual disk write
*/
private saveToDisk(): void {
const data: TerminalSessionsFile = {
version: 2,
savedAt: Date.now(),
sessions: Array.from(this.sessions.values()),
};
try {
fs.writeFileSync(SESSIONS_FILE, JSON.stringify(data, null, 2), 'utf8');
console.warn(`[SessionPersistence] Saved ${data.sessions.length} sessions to disk`);
} catch (error) {
console.error('[SessionPersistence] Failed to save sessions:', error);
}
}
/**
* Clean up old buffer files not referenced by any session
*/
cleanupOrphanedBuffers(): void {
if (!fs.existsSync(BUFFERS_DIR)) return;
try {
const bufferFiles = fs.readdirSync(BUFFERS_DIR);
const referencedBuffers = new Set(
Array.from(this.sessions.values())
.map((s) => s.bufferFile)
.filter((f): f is string => !!f)
);
let cleanedCount = 0;
for (const file of bufferFiles) {
if (!referencedBuffers.has(file)) {
const filePath = path.join(BUFFERS_DIR, file);
fs.unlinkSync(filePath);
cleanedCount++;
}
}
if (cleanedCount > 0) {
console.warn(`[SessionPersistence] Cleaned up ${cleanedCount} orphaned buffer files`);
}
} catch (error) {
console.error('[SessionPersistence] Failed to cleanup orphaned buffers:', error);
}
}
}
// Singleton instance
export const sessionPersistence = new SessionPersistence();
// Hook into app lifecycle
app.on('before-quit', () => {
console.warn('[SessionPersistence] App quitting, saving sessions...');
sessionPersistence.saveNow();
});
app.on('will-quit', () => {
sessionPersistence.saveNow();
});
// Cleanup orphaned buffers on startup (after initial load)
app.whenReady().then(() => {
setTimeout(() => {
sessionPersistence.cleanupOrphanedBuffers();
}, 5000); // Wait 5 seconds after app ready
});
@@ -9,12 +9,12 @@ import { IPC_CHANNELS } from '../../shared/constants';
import type { TerminalSession } from '../terminal-session-store';
import * as PtyManager from './pty-manager';
import * as SessionHandler from './session-handler';
import * as TerminalEventHandler from './terminal-event-handler';
import type {
TerminalProcess,
WindowGetter,
TerminalOperationResult
} from './types';
import { debugLog, debugError } from '../../shared/utils/debug-logger';
/**
* Options for terminal restoration
@@ -40,10 +40,10 @@ export async function createTerminal(
): Promise<TerminalOperationResult> {
const { id, cwd, cols = 80, rows = 24, projectPath } = options;
console.log('[TerminalLifecycle] Creating terminal:', { id, cwd, cols, rows, projectPath });
debugLog('[TerminalLifecycle] Creating terminal:', { id, cwd, cols, rows, projectPath });
if (terminals.has(id)) {
console.log('[TerminalLifecycle] Terminal already exists, returning success:', id);
debugLog('[TerminalLifecycle] Terminal already exists, returning success:', id);
return { success: true };
}
@@ -51,7 +51,7 @@ export async function createTerminal(
const profileEnv = PtyManager.getActiveProfileEnv();
if (profileEnv.CLAUDE_CODE_OAUTH_TOKEN) {
console.log('[TerminalLifecycle] Injecting OAuth token from active profile');
debugLog('[TerminalLifecycle] Injecting OAuth token from active profile');
}
const ptyProcess = PtyManager.spawnPtyProcess(
@@ -61,7 +61,7 @@ export async function createTerminal(
profileEnv
);
console.log('[TerminalLifecycle] PTY process spawned, pid:', ptyProcess.pid);
debugLog('[TerminalLifecycle] PTY process spawned, pid:', ptyProcess.pid);
const terminalCwd = cwd || os.homedir();
const terminal: TerminalProcess = {
@@ -88,10 +88,10 @@ export async function createTerminal(
SessionHandler.persistSession(terminal);
}
console.log('[TerminalLifecycle] Terminal created successfully:', id);
debugLog('[TerminalLifecycle] Terminal created successfully:', id);
return { success: true };
} catch (error) {
console.error('[TerminalLifecycle] Error creating terminal:', error);
debugError('[TerminalLifecycle] Error creating terminal:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to create terminal',
@@ -111,7 +111,7 @@ export async function restoreTerminal(
cols = 80,
rows = 24
): Promise<TerminalOperationResult> {
console.log('[TerminalLifecycle] Restoring terminal session:', session.id, 'Claude mode:', session.isClaudeMode);
debugLog('[TerminalLifecycle] Restoring terminal session:', session.id, 'Claude mode:', session.isClaudeMode);
const result = await createTerminal(
{
@@ -137,34 +137,17 @@ export async function restoreTerminal(
terminal.title = session.title;
if (session.isClaudeMode && options.resumeClaudeSession) {
await new Promise(resolve => setTimeout(resolve, 1000));
// Restore Claude mode state without sending resume commands
// The PTY daemon keeps processes alive, so we just need to reconnect to the existing session
if (session.isClaudeMode) {
terminal.isClaudeMode = true;
terminal.claudeSessionId = session.claudeSessionId;
const projectDir = session.cwd || session.projectPath;
const startTime = Date.now();
const clearCmd = process.platform === 'win32' ? 'cls' : 'clear';
let resumeCommand: string;
if (session.claudeSessionId) {
resumeCommand = `${clearCmd} && cd "${projectDir}" && claude --resume "${session.claudeSessionId}"`;
console.log('[TerminalLifecycle] Resuming Claude with session ID:', session.claudeSessionId, 'in', projectDir);
} else {
resumeCommand = `${clearCmd} && cd "${projectDir}" && claude --resume`;
console.log('[TerminalLifecycle] Opening Claude session picker in', projectDir);
}
terminal.pty.write(`${resumeCommand}\r`);
debugLog('[TerminalLifecycle] Restored Claude mode state for session:', session.id, 'sessionId:', session.claudeSessionId);
const win = getWindow();
if (win) {
win.webContents.send(IPC_CHANNELS.TERMINAL_TITLE_CHANGE, session.id, 'Claude');
}
if (!session.claudeSessionId && projectDir) {
options.captureSessionId(session.id, projectDir, startTime);
win.webContents.send(IPC_CHANNELS.TERMINAL_TITLE_CHANGE, session.id, session.title);
}
}
@@ -238,12 +221,14 @@ export async function destroyAllTerminals(
/**
* Handle terminal exit event
* Note: We don't remove sessions here because terminal exit might be due to app shutdown.
* Sessions are only removed when explicitly destroyed by user action via destroyTerminal().
*/
function handleTerminalExit(
terminal: TerminalProcess,
terminals: Map<string, TerminalProcess>
_terminal: TerminalProcess,
_terminals: Map<string, TerminalProcess>
): void {
SessionHandler.removePersistedSession(terminal);
// Don't remove session - let it persist for restoration
}
/**
+1 -1
View File
@@ -1,4 +1,4 @@
import type * as pty from 'node-pty';
import type * as pty from '@lydell/node-pty';
import type { BrowserWindow } from 'electron';
/**
+16 -9
View File
@@ -4,6 +4,7 @@ import { spawn } from 'child_process';
import { app } from 'electron';
import { EventEmitter } from 'events';
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from './rate-limit-detector';
import { findPythonCommand, parsePythonCommand } from './python-detector';
/**
* Debug logging - only logs when AUTO_CLAUDE_DEBUG env var is set
@@ -12,7 +13,7 @@ const DEBUG = process.env.AUTO_CLAUDE_DEBUG === 'true' || process.env.AUTO_CLAUD
function debug(...args: unknown[]): void {
if (DEBUG) {
console.log('[TitleGenerator]', ...args);
console.warn('[TitleGenerator]', ...args);
}
}
@@ -20,7 +21,8 @@ function debug(...args: unknown[]): void {
* Service for generating task titles from descriptions using Claude AI
*/
export class TitleGenerator extends EventEmitter {
private pythonPath: string = 'python3';
// Auto-detect Python command on initialization
private pythonPath: string = findPythonCommand() || 'python';
private autoBuildSourcePath: string = '';
constructor() {
@@ -55,7 +57,8 @@ export class TitleGenerator extends EventEmitter {
];
for (const p of possiblePaths) {
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
// Use requirements.txt as marker - it always exists in auto-claude source
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
return p;
}
}
@@ -128,20 +131,24 @@ export class TitleGenerator extends EventEmitter {
const profileEnv = getProfileEnv();
return new Promise((resolve) => {
const childProcess = spawn(this.pythonPath, ['-c', script], {
// Parse Python command to handle space-separated commands like "py -3"
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.pythonPath);
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, '-c', script], {
cwd: autoBuildSource,
env: {
...process.env,
...autoBuildEnv,
...profileEnv, // Include active Claude profile config
PYTHONUNBUFFERED: '1'
PYTHONUNBUFFERED: '1',
PYTHONIOENCODING: 'utf-8',
PYTHONUTF8: '1'
}
});
let output = '';
let errorOutput = '';
const timeout = setTimeout(() => {
console.log('[TitleGenerator] Title generation timed out after 60s');
console.warn('[TitleGenerator] Title generation timed out after 60s');
childProcess.kill();
resolve(null);
}, 60000); // 60 second timeout for SDK initialization + API call
@@ -166,7 +173,7 @@ export class TitleGenerator extends EventEmitter {
const combinedOutput = `${output}\n${errorOutput}`;
const rateLimitDetection = detectRateLimit(combinedOutput);
if (rateLimitDetection.isRateLimited) {
console.log('[TitleGenerator] Rate limit detected:', {
console.warn('[TitleGenerator] Rate limit detected:', {
resetTime: rateLimitDetection.resetTime,
limitType: rateLimitDetection.limitType,
suggestedProfile: rateLimitDetection.suggestedProfile?.name
@@ -177,7 +184,7 @@ export class TitleGenerator extends EventEmitter {
}
// Always log failures to help diagnose issues
console.log('[TitleGenerator] Title generation failed', {
console.warn('[TitleGenerator] Title generation failed', {
code,
errorOutput: errorOutput.substring(0, 500),
output: output.substring(0, 200),
@@ -189,7 +196,7 @@ export class TitleGenerator extends EventEmitter {
childProcess.on('error', (err) => {
clearTimeout(timeout);
console.log('[TitleGenerator] Process error:', err.message);
console.warn('[TitleGenerator] Process error:', err.message);
resolve(null);
});
});

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