Compare commits
85 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0acdba6f01 | |||
| de2eccd209 | |||
| 948db57763 | |||
| f98a13eaa0 | |||
| 24ff491d3c | |||
| a8f2d0b110 | |||
| 46d2536600 | |||
| 71535581c2 | |||
| 26725286d5 | |||
| 569e921759 | |||
| 03ccce5cc1 | |||
| 64d5170c94 | |||
| 0710c13964 | |||
| 56cedec2ae | |||
| c0c8067bc5 | |||
| db3a034d75 | |||
| 059315d6ab | |||
| 8df7ba4f16 | |||
| 2bffea842b | |||
| 99cf21e61b | |||
| da5e26b923 | |||
| c957eaa3a1 | |||
| 73d01c0103 | |||
| 41a507fe8b | |||
| e02aa597f2 | |||
| 909305c82b | |||
| 121b2b294f | |||
| c2fe3322a7 | |||
| aac6b106aa | |||
| 7f6beba3ad | |||
| 4b354e7b9f | |||
| eed5297e9d | |||
| 9a5ca8c78f | |||
| 63a1d3c138 | |||
| 3caf9cf18e | |||
| 7d351e3422 | |||
| 9dea155505 | |||
| d3cdd3a1c7 | |||
| a9d1ddb84f | |||
| 6985934825 | |||
| 4f1766b501 | |||
| 7ff326d898 | |||
| 48f7c3cc61 | |||
| 892e01d608 | |||
| 54501cbd73 | |||
| f1d578fd18 | |||
| 2e3a5d9de5 | |||
| a6dad428e9 | |||
| 3d24f8f59e | |||
| 9106038a17 | |||
| 895ed9f605 | |||
| cbe14fda9b | |||
| 4c1dd89840 | |||
| d93eefe806 | |||
| e11f5fcd50 | |||
| 8e891dfcfe | |||
| c721dc23b6 | |||
| 1a2b7a1bbb | |||
| b194c0e11f | |||
| a20b8cf12a | |||
| 0ed6afb805 | |||
| 914a09d0da | |||
| e44202a066 | |||
| 42496446bc | |||
| b0fc497583 | |||
| 462edcdd93 | |||
| affbc48cbe | |||
| d7fd1a24da | |||
| 96dd04d411 | |||
| 1d0566fce7 | |||
| 7f3cd5969d | |||
| 0ef0e1588b | |||
| efc112a313 | |||
| d33a0aaff6 | |||
| 6cff4420c9 | |||
| 12bf69def6 | |||
| 3818b4641f | |||
| 219b66dcc6 | |||
| 4e63e8559d | |||
| 2fa3c51659 | |||
| 59b091a79f | |||
| a0c775f690 | |||
| 9babdc23c1 | |||
| dc886dce44 | |||
| 32760348ae |
@@ -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
|
||||
@@ -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/
|
||||
|
||||
+203
@@ -1,3 +1,206 @@
|
||||
## 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
|
||||
|
||||
@@ -4,7 +4,7 @@ Your AI coding companion. Build features, fix bugs, and ship faster — with aut
|
||||
|
||||

|
||||
|
||||
[](https://discord.gg/maj9EWmY)
|
||||
[](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
|
||||
@@ -251,6 +277,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.
|
||||
@@ -272,7 +321,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:
|
||||
|
||||
[](https://discord.gg/maj9EWmY)
|
||||
[](https://discord.gg/KCXaPBr4Dj)
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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,7 +1,7 @@
|
||||
/**
|
||||
* Playwright configuration for Electron E2E tests
|
||||
*/
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
import { defineConfig } from '@playwright/test';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: '.',
|
||||
|
||||
@@ -5,13 +5,21 @@ 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')
|
||||
},
|
||||
// Only node-pty needs to be external (native module rebuilt by electron-builder)
|
||||
external: ['node-pty']
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
|
||||
|
||||
Generated
+1581
-59
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "auto-claude-ui",
|
||||
"version": "2.3.0",
|
||||
"version": "2.5.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 .",
|
||||
@@ -55,10 +55,11 @@
|
||||
"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",
|
||||
"node-pty": "^1.1.0-beta42",
|
||||
"react": "^19.2.3",
|
||||
"react-dom": "^19.2.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
@@ -114,12 +115,42 @@
|
||||
"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/node-pty",
|
||||
"to": "node_modules/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",
|
||||
@@ -130,7 +161,7 @@
|
||||
]
|
||||
},
|
||||
"win": {
|
||||
"icon": "resources/icon-256.png",
|
||||
"icon": "resources/icon.ico",
|
||||
"target": [
|
||||
"nsis",
|
||||
"zip"
|
||||
|
||||
Generated
+46
-11
@@ -96,6 +96,9 @@ importers:
|
||||
clsx:
|
||||
specifier: ^2.1.1
|
||||
version: 2.1.1
|
||||
electron-updater:
|
||||
specifier: ^6.6.2
|
||||
version: 6.6.2
|
||||
ioredis:
|
||||
specifier: ^5.8.2
|
||||
version: 5.8.2
|
||||
@@ -106,8 +109,8 @@ importers:
|
||||
specifier: ^12.23.26
|
||||
version: 12.23.26(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
node-pty:
|
||||
specifier: ^1.0.0
|
||||
version: 1.0.0
|
||||
specifier: ^1.1.0-beta42
|
||||
version: 1.1.0-beta9
|
||||
react:
|
||||
specifier: ^19.2.3
|
||||
version: 19.2.3
|
||||
@@ -2204,6 +2207,9 @@ packages:
|
||||
electron-to-chromium@1.5.267:
|
||||
resolution: {integrity: sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==}
|
||||
|
||||
electron-updater@6.6.2:
|
||||
resolution: {integrity: sha512-Cr4GDOkbAUqRHP5/oeOmH/L2Bn6+FQPxVLZtPbcmKZC63a1F3uu5EefYOssgZXG3u/zBlubbJ5PJdITdMVggbw==}
|
||||
|
||||
electron-vite@5.0.0:
|
||||
resolution: {integrity: sha512-OHp/vjdlubNlhNkPkL/+3JD34ii5ov7M0GpuXEVdQeqdQ3ulvVR7Dg/rNBLfS5XPIFwgoBLDf9sjjrL+CuDyRQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
@@ -3048,9 +3054,16 @@ packages:
|
||||
lodash.defaults@4.2.0:
|
||||
resolution: {integrity: sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==}
|
||||
|
||||
lodash.escaperegexp@4.1.2:
|
||||
resolution: {integrity: sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==}
|
||||
|
||||
lodash.isarguments@3.1.0:
|
||||
resolution: {integrity: sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==}
|
||||
|
||||
lodash.isequal@4.5.0:
|
||||
resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==}
|
||||
deprecated: This package is deprecated. Use require('node:util').isDeepStrictEqual instead.
|
||||
|
||||
lodash.merge@4.6.2:
|
||||
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}
|
||||
|
||||
@@ -3365,9 +3378,6 @@ packages:
|
||||
ms@2.1.3:
|
||||
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
||||
|
||||
nan@2.24.0:
|
||||
resolution: {integrity: sha512-Vpf9qnVW1RaDkoNKFUvfxqAbtI8ncb8OJlqZ9wwpXzWPEsvsB1nvdUi6oYrHIkQ1Y/tMDnr1h4nczS0VB9Xykg==}
|
||||
|
||||
nano-spawn@2.0.0:
|
||||
resolution: {integrity: sha512-tacvGzUY5o2D8CBh2rrwxyNojUsZNU2zjNTzKQrkgGJQTbGAfArVWXSKMBokBeeg6C7OLRGUEyoFlYbfeWQIqw==}
|
||||
engines: {node: '>=20.17'}
|
||||
@@ -3391,11 +3401,14 @@ packages:
|
||||
node-addon-api@1.7.2:
|
||||
resolution: {integrity: sha512-ibPK3iA+vaY1eEjESkQkM0BbCqFOaZMiXRTtdB0u7b4djtY6JnsjvPdUHVMg6xQt3B8fpTTWHI9A+ADjM9frzg==}
|
||||
|
||||
node-addon-api@7.1.1:
|
||||
resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==}
|
||||
|
||||
node-api-version@0.2.1:
|
||||
resolution: {integrity: sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==}
|
||||
|
||||
node-pty@1.0.0:
|
||||
resolution: {integrity: sha512-wtBMWWS7dFZm/VgqElrTvtfMq4GzJ6+edFI0Y0zyzygUSZMgZdraDUMUhCIvkjhJjme15qWmbyJbtAx4ot4uZA==}
|
||||
node-pty@1.1.0-beta9:
|
||||
resolution: {integrity: sha512-/Ue38pvXJdgRZ3+me1FgfglLd301GhJN0NStiotdt61tm43N5htUyR/IXOUzOKuNaFmCwIhy6nwb77Ky41LMbw==}
|
||||
|
||||
node-releases@2.0.27:
|
||||
resolution: {integrity: sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==}
|
||||
@@ -4044,6 +4057,9 @@ packages:
|
||||
tiny-async-pool@1.3.0:
|
||||
resolution: {integrity: sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==}
|
||||
|
||||
tiny-typed-emitter@2.1.0:
|
||||
resolution: {integrity: sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==}
|
||||
|
||||
tinybench@2.9.0:
|
||||
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
|
||||
|
||||
@@ -6585,6 +6601,19 @@ snapshots:
|
||||
|
||||
electron-to-chromium@1.5.267: {}
|
||||
|
||||
electron-updater@6.6.2:
|
||||
dependencies:
|
||||
builder-util-runtime: 9.3.1
|
||||
fs-extra: 10.1.0
|
||||
js-yaml: 4.1.1
|
||||
lazy-val: 1.0.5
|
||||
lodash.escaperegexp: 4.1.2
|
||||
lodash.isequal: 4.5.0
|
||||
semver: 7.7.3
|
||||
tiny-typed-emitter: 2.1.0
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
electron-vite@5.0.0(vite@7.2.7(@types/node@25.0.0)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)):
|
||||
dependencies:
|
||||
'@babel/core': 7.28.5
|
||||
@@ -7621,8 +7650,12 @@ snapshots:
|
||||
|
||||
lodash.defaults@4.2.0: {}
|
||||
|
||||
lodash.escaperegexp@4.1.2: {}
|
||||
|
||||
lodash.isarguments@3.1.0: {}
|
||||
|
||||
lodash.isequal@4.5.0: {}
|
||||
|
||||
lodash.merge@4.6.2: {}
|
||||
|
||||
lodash@4.17.21: {}
|
||||
@@ -8143,8 +8176,6 @@ snapshots:
|
||||
|
||||
ms@2.1.3: {}
|
||||
|
||||
nan@2.24.0: {}
|
||||
|
||||
nano-spawn@2.0.0: {}
|
||||
|
||||
nanoid@3.3.11: {}
|
||||
@@ -8160,13 +8191,15 @@ snapshots:
|
||||
node-addon-api@1.7.2:
|
||||
optional: true
|
||||
|
||||
node-addon-api@7.1.1: {}
|
||||
|
||||
node-api-version@0.2.1:
|
||||
dependencies:
|
||||
semver: 7.7.3
|
||||
|
||||
node-pty@1.0.0:
|
||||
node-pty@1.1.0-beta9:
|
||||
dependencies:
|
||||
nan: 2.24.0
|
||||
node-addon-api: 7.1.1
|
||||
|
||||
node-releases@2.0.27: {}
|
||||
|
||||
@@ -8919,6 +8952,8 @@ snapshots:
|
||||
dependencies:
|
||||
semver: 5.7.2
|
||||
|
||||
tiny-typed-emitter@2.1.0: {}
|
||||
|
||||
tinybench@2.9.0: {}
|
||||
|
||||
tinyexec@1.0.2: {}
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
@@ -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,8 +47,8 @@ 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 runners subdirectory (where spec_runner.py lives after restructure)
|
||||
mkdirSync(path.join(AUTO_CLAUDE_SOURCE, 'runners'), { recursive: true });
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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) {
|
||||
@@ -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);
|
||||
|
||||
@@ -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,7 +6,7 @@ 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';
|
||||
|
||||
@@ -65,7 +65,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 +100,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,11 +158,6 @@ 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();
|
||||
|
||||
@@ -174,12 +167,12 @@ export class AgentProcessManager {
|
||||
...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,18 +232,16 @@ 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);
|
||||
});
|
||||
|
||||
// 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);
|
||||
@@ -259,13 +250,11 @@ export class AgentProcessManager {
|
||||
|
||||
// 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 +263,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 +300,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 +328,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, {
|
||||
|
||||
@@ -7,6 +7,7 @@ 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';
|
||||
|
||||
/**
|
||||
* Queue management for ideation and roadmap generation
|
||||
@@ -38,16 +39,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 +73,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 +88,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 +140,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 +154,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 +173,42 @@ 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();
|
||||
|
||||
// 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'
|
||||
});
|
||||
|
||||
const childProcess = spawn(pythonPath, args, {
|
||||
cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...combinedEnv,
|
||||
...profileEnv,
|
||||
PYTHONUNBUFFERED: '1'
|
||||
}
|
||||
env: finalEnv
|
||||
});
|
||||
|
||||
this.state.addProcess(projectId, {
|
||||
@@ -165,7 +216,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 +232,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 +255,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 +271,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 +297,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 +313,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 +322,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 +334,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 +350,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 +389,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 +408,42 @@ 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'
|
||||
};
|
||||
|
||||
// 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'
|
||||
});
|
||||
|
||||
const childProcess = spawn(pythonPath, args, {
|
||||
cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...combinedEnv,
|
||||
...profileEnv,
|
||||
PYTHONUNBUFFERED: '1'
|
||||
}
|
||||
env: finalEnv
|
||||
});
|
||||
|
||||
this.state.addProcess(projectId, {
|
||||
@@ -363,7 +451,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 +467,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 +494,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 +510,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 +519,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 +531,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 +547,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 +583,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 +603,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';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -119,7 +119,7 @@ export class ChangelogService extends EventEmitter {
|
||||
*/
|
||||
private debug(...args: unknown[]): void {
|
||||
if (this.isDebugEnabled()) {
|
||||
console.log('[ChangelogService]', ...args);
|
||||
console.warn('[ChangelogService]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +150,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ export class ChangelogGenerator extends EventEmitter {
|
||||
|
||||
private debug(...args: unknown[]): void {
|
||||
if (this.debugEnabled) {
|
||||
console.log('[ChangelogGenerator]', ...args);
|
||||
console.warn('[ChangelogGenerator]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,7 +277,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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -28,7 +28,7 @@ export class VersionSuggester {
|
||||
|
||||
private debug(...args: unknown[]): void {
|
||||
if (this.debugEnabled) {
|
||||
console.log('[VersionSuggester]', ...args);
|
||||
console.warn('[VersionSuggester]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ export class VersionSuggester {
|
||||
// Build environment
|
||||
const spawnEnv = this.buildSpawnEnvironment();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
return new Promise((resolve, _reject) => {
|
||||
const childProcess = spawn(this.pythonPath, ['-c', script], {
|
||||
cwd: this.autoBuildSourcePath,
|
||||
env: spawnEnv
|
||||
@@ -237,7 +237,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,14 @@ 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);
|
||||
if (!usage) {
|
||||
console.log('[UsageMonitor] Failed to fetch usage');
|
||||
console.warn('[UsageMonitor] Failed to fetch usage');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -116,7 +116,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 +154,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 +191,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 +237,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 +261,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 +277,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 +285,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[UsageMonitor] Proactive swap:', {
|
||||
console.warn('[UsageMonitor] Proactive swap:', {
|
||||
from: currentProfileId,
|
||||
to: bestProfile.id,
|
||||
reason: limitType
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
@@ -136,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
|
||||
@@ -159,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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -45,7 +45,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 +104,9 @@ export class InsightsConfig {
|
||||
...process.env as Record<string, string>,
|
||||
...autoBuildEnv,
|
||||
...profileEnv,
|
||||
PYTHONUNBUFFERED: '1'
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,10 @@ 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 +61,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 +72,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 +86,23 @@ export class InsightsExecutor extends EventEmitter {
|
||||
// Get process environment
|
||||
const processEnv = this.config.getProcessEnv();
|
||||
|
||||
// Spawn Python process
|
||||
const proc = spawn(this.config.getPythonPath(), [
|
||||
// Build command arguments
|
||||
const args = [
|
||||
runnerPath,
|
||||
'--project-dir', projectPath,
|
||||
'--message', message,
|
||||
'--history', JSON.stringify(conversationHistory)
|
||||
], {
|
||||
];
|
||||
|
||||
// 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
|
||||
});
|
||||
@@ -251,7 +264,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');
|
||||
}
|
||||
@@ -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
|
||||
@@ -85,7 +85,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)
|
||||
@@ -304,15 +304,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) => {
|
||||
|
||||
@@ -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, {
|
||||
|
||||
@@ -7,7 +7,7 @@ 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 type { GitHubAPIIssue, GitHubAPIComment } from './types';
|
||||
|
||||
/**
|
||||
* Transform GitHub API issue to application format
|
||||
@@ -116,10 +116,45 @@ 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 comments = await githubFetch(
|
||||
config.token,
|
||||
`/repos/${config.repo}/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();
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
|
||||
import { ipcMain } from 'electron';
|
||||
import { execSync, spawn } from 'child_process';
|
||||
import { execSync, execFileSync, spawn } from 'child_process';
|
||||
import { IPC_CHANNELS } from '../../../shared/constants';
|
||||
import type { IPCResult } from '../../../shared/types';
|
||||
|
||||
@@ -14,13 +14,25 @@ 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if gh CLI is installed
|
||||
*/
|
||||
@@ -296,6 +308,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 +419,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();
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -69,7 +69,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)
|
||||
// ============================================
|
||||
|
||||
@@ -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,
|
||||
@@ -13,21 +14,68 @@ import type { BrowserWindow } from 'electron';
|
||||
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;
|
||||
};
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -6,6 +6,8 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
|
||||
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)
|
||||
@@ -20,10 +22,10 @@ export function registerTaskExecutionHandlers(
|
||||
ipcMain.on(
|
||||
IPC_CHANNELS.TASK_START,
|
||||
(_, taskId: string, _options?: TaskStartOptions) => {
|
||||
console.log('[TASK_START] Received request for taskId:', taskId);
|
||||
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 +33,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 +42,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 +95,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 +103,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
|
||||
@@ -83,7 +118,7 @@ export function registerTaskExecutionHandlers(
|
||||
// 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 +134,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,
|
||||
@@ -216,23 +251,64 @@ export function registerTaskExecutionHandlers(
|
||||
taskId: string,
|
||||
status: TaskStatus
|
||||
): Promise<IPCResult> => {
|
||||
// Validate status transition - 'done' can only be set through merge handler
|
||||
// This prevents AI agents from bypassing the human review workflow
|
||||
if (status === 'done') {
|
||||
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."
|
||||
};
|
||||
}
|
||||
|
||||
// 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(
|
||||
@@ -252,17 +328,16 @@ 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
|
||||
// Note: 'done' is blocked at the start of this handler - only set via merge workflow
|
||||
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();
|
||||
|
||||
writeFileSync(planPath, JSON.stringify(plan, null, 2));
|
||||
} else {
|
||||
// If no implementation plan exists yet, create a basic one
|
||||
// Note: 'done' status is blocked at the start of this handler
|
||||
const plan = {
|
||||
feature: task.title,
|
||||
description: task.description || '',
|
||||
@@ -272,6 +347,7 @@ export function registerTaskExecutionHandlers(
|
||||
planStatus: status === 'in_progress' ? 'in_progress'
|
||||
: status === 'ai_review' ? 'review'
|
||||
: status === 'human_review' ? 'review'
|
||||
: status === 'done' ? 'completed'
|
||||
: 'pending',
|
||||
phases: []
|
||||
};
|
||||
@@ -287,7 +363,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);
|
||||
@@ -298,16 +403,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,
|
||||
@@ -320,7 +425,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,
|
||||
@@ -498,6 +603,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';
|
||||
@@ -523,11 +662,11 @@ 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(`[Recovery] Starting spec creation for: ${task.specId}`);
|
||||
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.log(`[Recovery] Starting task execution for: ${task.specId}`);
|
||||
console.warn(`[Recovery] Starting task execution for: ${task.specId}`);
|
||||
agentManager.startTaskExecution(
|
||||
taskId,
|
||||
project.path,
|
||||
@@ -540,7 +679,7 @@ export function registerTaskExecutionHandlers(
|
||||
}
|
||||
|
||||
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,5 +1,5 @@
|
||||
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';
|
||||
@@ -226,11 +226,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
|
||||
@@ -315,7 +315,9 @@ export function registerWorktreeHandlers(
|
||||
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 +402,75 @@ 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);
|
||||
|
||||
// Persist the status change to implementation_plan.json
|
||||
const planPath = path.join(specDir, AUTO_BUILD_PATHS.IMPLEMENTATION_PLAN);
|
||||
@@ -417,7 +482,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 +497,13 @@ 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
|
||||
}
|
||||
});
|
||||
} else {
|
||||
@@ -499,11 +560,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 +583,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 +592,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);
|
||||
@@ -560,7 +623,7 @@ export function registerWorktreeHandlers(
|
||||
];
|
||||
|
||||
const pythonPath = pythonEnvManager.getPythonPath() || 'python3';
|
||||
console.log('[IPC] Running merge preview:', pythonPath, args.join(' '));
|
||||
console.warn('[IPC] Running merge preview:', pythonPath, args.join(' '));
|
||||
|
||||
// Get profile environment for consistency
|
||||
const previewProfileEnv = getProfileEnv();
|
||||
@@ -568,7 +631,7 @@ export function registerWorktreeHandlers(
|
||||
return new Promise((resolve) => {
|
||||
const previewProcess = spawn(pythonPath, 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 +640,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: {
|
||||
|
||||
@@ -208,7 +208,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);
|
||||
console.warn('[IPC] Created config directory:', profile.configDir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,7 +217,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:', {
|
||||
console.warn('[IPC] Initializing Claude profile:', {
|
||||
profileId,
|
||||
profileName: profile.name,
|
||||
configDir: profile.configDir,
|
||||
@@ -240,7 +240,7 @@ export function registerTerminalHandlers(
|
||||
loginCommand = 'claude setup-token';
|
||||
}
|
||||
|
||||
console.log('[IPC] Sending login command to terminal:', loginCommand);
|
||||
console.warn('[IPC] Sending login command to terminal:', loginCommand);
|
||||
|
||||
// Write the login command to the terminal
|
||||
terminalManager.write(terminalId, `${loginCommand}\r`);
|
||||
@@ -255,12 +255,12 @@ 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);
|
||||
@@ -569,5 +569,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');
|
||||
console.warn('[terminal-handlers] Usage monitor event forwarding initialized');
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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');
|
||||
|
||||
|
||||
@@ -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[] = [];
|
||||
@@ -294,7 +294,7 @@ export class ProjectStore {
|
||||
id: dir.name, // Use spec directory name as ID
|
||||
specId: dir.name,
|
||||
projectId,
|
||||
title: plan?.feature || dir.name,
|
||||
title: plan?.feature || plan?.title || dir.name,
|
||||
description,
|
||||
status,
|
||||
reviewReason,
|
||||
@@ -312,7 +312,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -147,7 +147,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 +163,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);
|
||||
@@ -200,7 +200,7 @@ export class PythonEnvManager extends EventEmitter {
|
||||
}
|
||||
|
||||
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], {
|
||||
@@ -228,7 +228,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 +264,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 +282,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 +301,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 +309,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 +362,3 @@ export class PythonEnvManager extends EventEmitter {
|
||||
|
||||
// Singleton instance
|
||||
export const pythonEnvManager = new PythonEnvManager();
|
||||
|
||||
|
||||
@@ -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 {};
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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');
|
||||
@@ -45,6 +46,13 @@ export class TaskLogService extends EventEmitter {
|
||||
const logs = JSON.parse(content) as TaskLogs;
|
||||
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 +197,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 +208,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 +233,7 @@ export class TaskLogService extends EventEmitter {
|
||||
lastMainContent = currentContent;
|
||||
mainChanged = true;
|
||||
}
|
||||
} catch (error) {
|
||||
} catch (_error) {
|
||||
// Ignore read/parse errors
|
||||
}
|
||||
}
|
||||
@@ -240,7 +248,7 @@ export class TaskLogService extends EventEmitter {
|
||||
lastWorktreeContent = currentContent;
|
||||
worktreeChanged = true;
|
||||
}
|
||||
} catch (error) {
|
||||
} catch (_error) {
|
||||
// Ignore read/parse errors
|
||||
}
|
||||
}
|
||||
@@ -262,7 +270,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 +282,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}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,7 +55,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;
|
||||
}
|
||||
}
|
||||
@@ -135,7 +136,9 @@ export class TerminalNameGenerator extends EventEmitter {
|
||||
...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,7 +6,6 @@
|
||||
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';
|
||||
@@ -39,14 +38,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 +67,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,7 +89,7 @@ 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+)-/);
|
||||
@@ -101,7 +100,7 @@ export function handleOAuthToken(
|
||||
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,7 +116,7 @@ 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');
|
||||
console.warn('[ClaudeIntegration] OAuth token detected but not in a profile login terminal');
|
||||
const win = getWindow();
|
||||
if (win) {
|
||||
win.webContents.send(IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
|
||||
@@ -140,7 +139,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);
|
||||
@@ -187,17 +186,17 @@ export function invokeClaude(
|
||||
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)');
|
||||
console.warn('[ClaudeIntegration] Switching to Claude profile:', activeProfile.name, '(via secure 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);
|
||||
console.warn('[ClaudeIntegration] Using Claude profile:', activeProfile.name, 'config:', activeProfile.configDir);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (activeProfile && !activeProfile.isDefault) {
|
||||
console.log('[ClaudeIntegration] Using Claude profile:', activeProfile.name, '(from terminal environment)');
|
||||
console.warn('[ClaudeIntegration] Using Claude profile:', activeProfile.name, '(from terminal environment)');
|
||||
}
|
||||
|
||||
terminal.pty.write(`${cwdCommand}claude\r`);
|
||||
@@ -265,7 +264,7 @@ export async function switchClaudeProfile(
|
||||
return { success: false, error: 'Profile not found' };
|
||||
}
|
||||
|
||||
console.log('[ClaudeIntegration] Switching to Claude profile:', profile.name);
|
||||
console.warn('[ClaudeIntegration] Switching to Claude profile:', profile.name);
|
||||
|
||||
if (terminal.isClaudeMode) {
|
||||
terminal.pty.write('\x03');
|
||||
|
||||
@@ -15,7 +15,20 @@ const SOCKET_PATH =
|
||||
? `\\\\.\\pipe\\auto-claude-pty-${process.getuid?.() || 'default'}`
|
||||
: `/tmp/auto-claude-pty-${process.getuid?.() || 'default'}.sock`;
|
||||
|
||||
type ResponseHandler = (response: any) => void;
|
||||
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;
|
||||
@@ -62,13 +75,13 @@ class PtyDaemonClient {
|
||||
try {
|
||||
// Try to connect to existing daemon
|
||||
await this.tryConnect();
|
||||
console.log('[PtyDaemonClient] Connected to existing daemon');
|
||||
console.warn('[PtyDaemonClient] Connected to existing daemon');
|
||||
} catch {
|
||||
// Spawn daemon and connect
|
||||
console.log('[PtyDaemonClient] Spawning new daemon...');
|
||||
console.warn('[PtyDaemonClient] Spawning new daemon...');
|
||||
await this.spawnDaemon();
|
||||
await this.tryConnect();
|
||||
console.log('[PtyDaemonClient] Connected to new daemon');
|
||||
console.warn('[PtyDaemonClient] Connected to new daemon');
|
||||
} finally {
|
||||
this.isConnecting = false;
|
||||
this.reconnectAttempts = 0;
|
||||
@@ -119,7 +132,7 @@ class PtyDaemonClient {
|
||||
// Unref so parent can exit independently
|
||||
this.daemonProcess.unref();
|
||||
|
||||
console.log(`[PtyDaemonClient] Spawned daemon process (PID: ${this.daemonProcess.pid})`);
|
||||
console.warn(`[PtyDaemonClient] Spawned daemon process (PID: ${this.daemonProcess.pid})`);
|
||||
|
||||
// Wait for daemon to start listening
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
@@ -154,7 +167,7 @@ class PtyDaemonClient {
|
||||
});
|
||||
|
||||
this.socket.on('close', () => {
|
||||
console.log('[PtyDaemonClient] Disconnected from daemon');
|
||||
console.warn('[PtyDaemonClient] Disconnected from daemon');
|
||||
this.socket = null;
|
||||
if (!this.isShuttingDown) {
|
||||
this.attemptReconnect();
|
||||
@@ -169,7 +182,7 @@ class PtyDaemonClient {
|
||||
/**
|
||||
* Handle response from daemon
|
||||
*/
|
||||
private handleResponse(response: any): void {
|
||||
private handleResponse(response: DaemonResponse): void {
|
||||
// Handle request-response pattern
|
||||
if (response.requestId) {
|
||||
const handler = this.pendingRequests.get(response.requestId);
|
||||
@@ -183,7 +196,7 @@ class PtyDaemonClient {
|
||||
// Handle streaming data
|
||||
if (response.type === 'data' && response.id) {
|
||||
const handler = this.dataHandlers.get(response.id);
|
||||
if (handler) {
|
||||
if (handler && typeof response.data === 'string') {
|
||||
handler(response.data);
|
||||
}
|
||||
return;
|
||||
@@ -192,8 +205,9 @@ class PtyDaemonClient {
|
||||
// Handle exit events
|
||||
if (response.type === 'exit' && response.id) {
|
||||
const handler = this.exitHandlers.get(response.id);
|
||||
if (handler) {
|
||||
handler(response.data.exitCode, response.data.signal);
|
||||
if (handler && typeof response.data === 'object' && response.data !== null) {
|
||||
const exitData = response.data as DaemonResponseData;
|
||||
handler(exitData.exitCode ?? 0, exitData.signal);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -213,7 +227,7 @@ class PtyDaemonClient {
|
||||
this.reconnectAttempts++;
|
||||
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 10000);
|
||||
|
||||
console.log(
|
||||
console.warn(
|
||||
`[PtyDaemonClient] Reconnect attempt ${this.reconnectAttempts} in ${delay}ms...`
|
||||
);
|
||||
|
||||
@@ -227,7 +241,7 @@ class PtyDaemonClient {
|
||||
/**
|
||||
* Send a request and wait for response
|
||||
*/
|
||||
private async request<T>(msg: any): Promise<T> {
|
||||
private async request<T>(msg: Record<string, unknown>): Promise<T> {
|
||||
await this.connect();
|
||||
|
||||
if (!this.socket) {
|
||||
@@ -258,7 +272,7 @@ class PtyDaemonClient {
|
||||
/**
|
||||
* Send a message without expecting a response
|
||||
*/
|
||||
private send(msg: any): void {
|
||||
private send(msg: Record<string, unknown>): void {
|
||||
if (!this.socket) {
|
||||
console.warn('[PtyDaemonClient] Cannot send - not connected');
|
||||
return;
|
||||
|
||||
@@ -56,14 +56,14 @@ interface DaemonMessage {
|
||||
| 'get-buffer'
|
||||
| 'ping';
|
||||
id?: string;
|
||||
data?: any;
|
||||
data?: unknown;
|
||||
requestId?: string;
|
||||
}
|
||||
|
||||
interface DaemonResponse {
|
||||
type: 'created' | 'list' | 'buffer' | 'data' | 'exit' | 'error' | 'pong';
|
||||
id?: string;
|
||||
data?: any;
|
||||
data?: unknown;
|
||||
requestId?: string;
|
||||
error?: string;
|
||||
}
|
||||
@@ -102,9 +102,9 @@ class PtyDaemon {
|
||||
this.handleConnection(socket);
|
||||
});
|
||||
|
||||
this.server.on('error', (err) => {
|
||||
this.server.on('error', (err: NodeJS.ErrnoException) => {
|
||||
console.error('[PTY Daemon] Server error:', err);
|
||||
if ((err as any).code === 'EADDRINUSE') {
|
||||
if (err.code === 'EADDRINUSE') {
|
||||
console.error('[PTY Daemon] Address in use - another daemon may be running');
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -172,20 +172,22 @@ class PtyDaemon {
|
||||
break;
|
||||
|
||||
case 'create': {
|
||||
const id = this.createPty(msg.data);
|
||||
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);
|
||||
this.writeToPty(msg.id, msg.data as string);
|
||||
break;
|
||||
|
||||
case 'resize':
|
||||
case 'resize': {
|
||||
if (!msg.id) throw new Error('Missing PTY id');
|
||||
this.resizePty(msg.id, msg.data.cols, msg.data.rows);
|
||||
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');
|
||||
@@ -221,7 +223,7 @@ class PtyDaemon {
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown message type: ${(msg as any).type}`);
|
||||
throw new Error(`Unknown message type: ${(msg as DaemonMessage).type}`);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||
@@ -428,7 +430,7 @@ class PtyDaemon {
|
||||
socket.write(JSON.stringify(response) + '\n');
|
||||
} catch {
|
||||
// Socket may be closed, ignore
|
||||
console.debug('[PTY Daemon] Failed to send response (socket closed?)');
|
||||
console.warn('[PTY Daemon] Failed to send response (socket closed?)');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
import * as pty from '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,7 +6,7 @@
|
||||
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';
|
||||
@@ -115,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) {
|
||||
|
||||
@@ -49,7 +49,7 @@ class SessionPersistence {
|
||||
const sessions = this.loadSessions();
|
||||
this.isInitialized = true;
|
||||
|
||||
console.log(`[SessionPersistence] Initialized with ${sessions.length} sessions`);
|
||||
console.warn(`[SessionPersistence] Initialized with ${sessions.length} sessions`);
|
||||
return this.getRecoveryInfo();
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ class SessionPersistence {
|
||||
|
||||
validSessions.forEach((s) => this.sessions.set(s.id, s));
|
||||
|
||||
console.log(
|
||||
console.warn(
|
||||
`[SessionPersistence] Loaded ${validSessions.length} valid sessions, cleaned ${staleSessions.length} stale sessions`
|
||||
);
|
||||
return validSessions;
|
||||
@@ -188,7 +188,7 @@ class SessionPersistence {
|
||||
fs.writeFileSync(bufferPath, serializedBuffer, 'utf8');
|
||||
session.bufferFile = bufferFile;
|
||||
this.saveSession(session);
|
||||
console.debug(`[SessionPersistence] Saved buffer for session ${sessionId} (${serializedBuffer.length} bytes)`);
|
||||
console.warn(`[SessionPersistence] Saved buffer for session ${sessionId} (${serializedBuffer.length} bytes)`);
|
||||
} catch (error) {
|
||||
console.error(`[SessionPersistence] Failed to save buffer for ${sessionId}:`, error);
|
||||
}
|
||||
@@ -223,7 +223,7 @@ class SessionPersistence {
|
||||
if (fs.existsSync(bufferPath)) {
|
||||
try {
|
||||
fs.unlinkSync(bufferPath);
|
||||
console.debug(`[SessionPersistence] Deleted buffer file: ${bufferFile}`);
|
||||
console.warn(`[SessionPersistence] Deleted buffer file: ${bufferFile}`);
|
||||
} catch (error) {
|
||||
console.error(`[SessionPersistence] Failed to delete buffer file ${bufferFile}:`, error);
|
||||
}
|
||||
@@ -266,7 +266,7 @@ class SessionPersistence {
|
||||
|
||||
try {
|
||||
fs.writeFileSync(SESSIONS_FILE, JSON.stringify(data, null, 2), 'utf8');
|
||||
console.debug(`[SessionPersistence] Saved ${data.sessions.length} sessions to disk`);
|
||||
console.warn(`[SessionPersistence] Saved ${data.sessions.length} sessions to disk`);
|
||||
} catch (error) {
|
||||
console.error('[SessionPersistence] Failed to save sessions:', error);
|
||||
}
|
||||
@@ -296,7 +296,7 @@ class SessionPersistence {
|
||||
}
|
||||
|
||||
if (cleanedCount > 0) {
|
||||
console.log(`[SessionPersistence] Cleaned up ${cleanedCount} orphaned buffer files`);
|
||||
console.warn(`[SessionPersistence] Cleaned up ${cleanedCount} orphaned buffer files`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[SessionPersistence] Failed to cleanup orphaned buffers:', error);
|
||||
@@ -309,7 +309,7 @@ export const sessionPersistence = new SessionPersistence();
|
||||
|
||||
// Hook into app lifecycle
|
||||
app.on('before-quit', () => {
|
||||
console.log('[SessionPersistence] App quitting, saving sessions...');
|
||||
console.warn('[SessionPersistence] App quitting, saving sessions...');
|
||||
sessionPersistence.saveNow();
|
||||
});
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ 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,
|
||||
@@ -226,8 +225,8 @@ export async function destroyAllTerminals(
|
||||
* 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 {
|
||||
// Don't remove session - let it persist for restoration
|
||||
}
|
||||
|
||||
@@ -12,7 +12,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,7 +55,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;
|
||||
}
|
||||
}
|
||||
@@ -134,14 +135,16 @@ export class TitleGenerator extends EventEmitter {
|
||||
...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 +169,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 +180,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 +192,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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -75,7 +75,7 @@ export function copyDirectoryRecursive(
|
||||
const destPath = path.join(dest, entry.name);
|
||||
|
||||
// Skip certain files/directories
|
||||
if (SKIP_FILES.includes(entry.name as any)) {
|
||||
if (SKIP_FILES.includes(entry.name as (typeof SKIP_FILES)[number])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,12 +11,12 @@ import { TIMEOUTS } from './config';
|
||||
*/
|
||||
export function fetchJson<T>(url: string): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = https.get(url, {
|
||||
headers: {
|
||||
'User-Agent': 'Auto-Claude-UI',
|
||||
'Accept': 'application/vnd.github.v3+json'
|
||||
}
|
||||
}, (response) => {
|
||||
const headers = {
|
||||
'User-Agent': 'Auto-Claude-UI',
|
||||
'Accept': 'application/vnd.github+json'
|
||||
};
|
||||
|
||||
const request = https.get(url, { headers }, (response) => {
|
||||
// Handle redirects
|
||||
if (response.statusCode === 301 || response.statusCode === 302) {
|
||||
const redirectUrl = response.headers.location;
|
||||
@@ -27,7 +27,19 @@ export function fetchJson<T>(url: string): Promise<T> {
|
||||
}
|
||||
|
||||
if (response.statusCode !== 200) {
|
||||
reject(new Error(`HTTP ${response.statusCode}`));
|
||||
// Collect response body for error details (limit to 10KB)
|
||||
const maxErrorSize = 10 * 1024;
|
||||
let errorData = '';
|
||||
response.on('data', chunk => {
|
||||
if (errorData.length < maxErrorSize) {
|
||||
errorData += chunk.toString().slice(0, maxErrorSize - errorData.length);
|
||||
}
|
||||
});
|
||||
response.on('end', () => {
|
||||
const errorMsg = `HTTP ${response.statusCode}: ${errorData || response.statusMessage || 'No error details'}`;
|
||||
reject(new Error(errorMsg));
|
||||
});
|
||||
response.on('error', reject);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -36,7 +48,7 @@ export function fetchJson<T>(url: string): Promise<T> {
|
||||
response.on('end', () => {
|
||||
try {
|
||||
resolve(JSON.parse(data) as T);
|
||||
} catch (e) {
|
||||
} catch (_e) {
|
||||
reject(new Error('Failed to parse JSON response'));
|
||||
}
|
||||
});
|
||||
@@ -62,12 +74,12 @@ export function downloadFile(
|
||||
return new Promise((resolve, reject) => {
|
||||
const file = createWriteStream(destPath);
|
||||
|
||||
const request = https.get(url, {
|
||||
headers: {
|
||||
'User-Agent': 'Auto-Claude-UI',
|
||||
'Accept': 'application/octet-stream'
|
||||
}
|
||||
}, (response) => {
|
||||
const headers = {
|
||||
'User-Agent': 'Auto-Claude-UI',
|
||||
'Accept': 'application/octet-stream'
|
||||
};
|
||||
|
||||
const request = https.get(url, { headers }, (response) => {
|
||||
// Handle redirects
|
||||
if (response.statusCode === 301 || response.statusCode === 302) {
|
||||
file.close();
|
||||
@@ -80,7 +92,19 @@ export function downloadFile(
|
||||
|
||||
if (response.statusCode !== 200) {
|
||||
file.close();
|
||||
reject(new Error(`HTTP ${response.statusCode}`));
|
||||
// Collect response body for error details (limit to 10KB)
|
||||
const maxErrorSize = 10 * 1024;
|
||||
let errorData = '';
|
||||
response.on('data', chunk => {
|
||||
if (errorData.length < maxErrorSize) {
|
||||
errorData += chunk.toString().slice(0, maxErrorSize - errorData.length);
|
||||
}
|
||||
});
|
||||
response.on('end', () => {
|
||||
const errorMsg = `HTTP ${response.statusCode}: ${errorData || response.statusMessage || 'No error details'}`;
|
||||
reject(new Error(errorMsg));
|
||||
});
|
||||
response.on('error', reject);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import { app } from 'electron';
|
||||
import { GITHUB_CONFIG, PRESERVE_FILES } from './config';
|
||||
import { downloadFile, fetchJson } from './http-client';
|
||||
import { parseVersionFromTag } from './version-manager';
|
||||
import { getUpdateCachePath, getUpdateTargetPath, getBundledSourcePath } from './path-resolver';
|
||||
import { getUpdateCachePath, getUpdateTargetPath } from './path-resolver';
|
||||
import { extractTarball, copyDirectoryRecursive, preserveFiles, restoreFiles, cleanTargetDirectory } from './file-operations';
|
||||
import { getCachedRelease, setCachedRelease, clearCachedRelease } from './update-checker';
|
||||
import { GitHubRelease, AutoBuildUpdateResult, UpdateProgressCallback, UpdateMetadata } from './types';
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import type {
|
||||
AppUpdateInfo,
|
||||
AppUpdateProgress,
|
||||
AppUpdateAvailableEvent,
|
||||
AppUpdateDownloadedEvent,
|
||||
IPCResult
|
||||
} from '../../shared/types';
|
||||
import { createIpcListener, invokeIpc, IpcListenerCleanup } from './modules/ipc-utils';
|
||||
|
||||
/**
|
||||
* App Auto-Update API operations
|
||||
* Handles Electron app updates using electron-updater
|
||||
*/
|
||||
export interface AppUpdateAPI {
|
||||
// Operations
|
||||
checkAppUpdate: () => Promise<IPCResult<AppUpdateInfo | null>>;
|
||||
downloadAppUpdate: () => Promise<IPCResult>;
|
||||
installAppUpdate: () => void;
|
||||
getAppVersion: () => Promise<string>;
|
||||
|
||||
// Event Listeners
|
||||
onAppUpdateAvailable: (
|
||||
callback: (info: AppUpdateAvailableEvent) => void
|
||||
) => IpcListenerCleanup;
|
||||
onAppUpdateDownloaded: (
|
||||
callback: (info: AppUpdateDownloadedEvent) => void
|
||||
) => IpcListenerCleanup;
|
||||
onAppUpdateProgress: (
|
||||
callback: (progress: AppUpdateProgress) => void
|
||||
) => IpcListenerCleanup;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the App Auto-Update API implementation
|
||||
*/
|
||||
export const createAppUpdateAPI = (): AppUpdateAPI => ({
|
||||
// Operations
|
||||
checkAppUpdate: (): Promise<IPCResult<AppUpdateInfo | null>> =>
|
||||
invokeIpc(IPC_CHANNELS.APP_UPDATE_CHECK),
|
||||
|
||||
downloadAppUpdate: (): Promise<IPCResult> =>
|
||||
invokeIpc(IPC_CHANNELS.APP_UPDATE_DOWNLOAD),
|
||||
|
||||
installAppUpdate: (): void => {
|
||||
invokeIpc(IPC_CHANNELS.APP_UPDATE_INSTALL);
|
||||
},
|
||||
|
||||
getAppVersion: (): Promise<string> =>
|
||||
invokeIpc(IPC_CHANNELS.APP_UPDATE_GET_VERSION),
|
||||
|
||||
// Event Listeners
|
||||
onAppUpdateAvailable: (
|
||||
callback: (info: AppUpdateAvailableEvent) => void
|
||||
): IpcListenerCleanup =>
|
||||
createIpcListener(IPC_CHANNELS.APP_UPDATE_AVAILABLE, callback),
|
||||
|
||||
onAppUpdateDownloaded: (
|
||||
callback: (info: AppUpdateDownloadedEvent) => void
|
||||
): IpcListenerCleanup =>
|
||||
createIpcListener(IPC_CHANNELS.APP_UPDATE_DOWNLOADED, callback),
|
||||
|
||||
onAppUpdateProgress: (
|
||||
callback: (progress: AppUpdateProgress) => void
|
||||
): IpcListenerCleanup =>
|
||||
createIpcListener(IPC_CHANNELS.APP_UPDATE_PROGRESS, callback)
|
||||
});
|
||||
@@ -5,6 +5,8 @@ import { SettingsAPI, createSettingsAPI } from './settings-api';
|
||||
import { FileAPI, createFileAPI } from './file-api';
|
||||
import { AgentAPI, createAgentAPI } from './agent-api';
|
||||
import { IdeationAPI, createIdeationAPI } from './modules/ideation-api';
|
||||
import { InsightsAPI, createInsightsAPI } from './modules/insights-api';
|
||||
import { AppUpdateAPI, createAppUpdateAPI } from './app-update-api';
|
||||
|
||||
export interface ElectronAPI extends
|
||||
ProjectAPI,
|
||||
@@ -13,7 +15,9 @@ export interface ElectronAPI extends
|
||||
SettingsAPI,
|
||||
FileAPI,
|
||||
AgentAPI,
|
||||
IdeationAPI {}
|
||||
IdeationAPI,
|
||||
InsightsAPI,
|
||||
AppUpdateAPI {}
|
||||
|
||||
export const createElectronAPI = (): ElectronAPI => ({
|
||||
...createProjectAPI(),
|
||||
@@ -22,7 +26,9 @@ export const createElectronAPI = (): ElectronAPI => ({
|
||||
...createSettingsAPI(),
|
||||
...createFileAPI(),
|
||||
...createAgentAPI(),
|
||||
...createIdeationAPI()
|
||||
...createIdeationAPI(),
|
||||
...createInsightsAPI(),
|
||||
...createAppUpdateAPI()
|
||||
});
|
||||
|
||||
// Export individual API creators for potential use in tests or specialized contexts
|
||||
@@ -33,7 +39,9 @@ export {
|
||||
createSettingsAPI,
|
||||
createFileAPI,
|
||||
createAgentAPI,
|
||||
createIdeationAPI
|
||||
createIdeationAPI,
|
||||
createInsightsAPI,
|
||||
createAppUpdateAPI
|
||||
};
|
||||
|
||||
export type {
|
||||
@@ -43,5 +51,7 @@ export type {
|
||||
SettingsAPI,
|
||||
FileAPI,
|
||||
AgentAPI,
|
||||
IdeationAPI
|
||||
IdeationAPI,
|
||||
InsightsAPI,
|
||||
AppUpdateAPI
|
||||
};
|
||||
|
||||
@@ -6,7 +6,8 @@ import type {
|
||||
GitHubImportResult,
|
||||
GitHubInvestigationStatus,
|
||||
GitHubInvestigationResult,
|
||||
IPCResult
|
||||
IPCResult,
|
||||
VersionSuggestion
|
||||
} from '../../../shared/types';
|
||||
import { createIpcListener, invokeIpc, sendIpc, IpcListenerCleanup } from './ipc-utils';
|
||||
|
||||
@@ -18,8 +19,9 @@ export interface GitHubAPI {
|
||||
getGitHubRepositories: (projectId: string) => Promise<IPCResult<GitHubRepository[]>>;
|
||||
getGitHubIssues: (projectId: string, state?: 'open' | 'closed' | 'all') => Promise<IPCResult<GitHubIssue[]>>;
|
||||
getGitHubIssue: (projectId: string, issueNumber: number) => Promise<IPCResult<GitHubIssue>>;
|
||||
getIssueComments: (projectId: string, issueNumber: number) => Promise<IPCResult<any[]>>;
|
||||
checkGitHubConnection: (projectId: string) => Promise<IPCResult<GitHubSyncStatus>>;
|
||||
investigateGitHubIssue: (projectId: string, issueNumber: number) => void;
|
||||
investigateGitHubIssue: (projectId: string, issueNumber: number, selectedCommentIds?: number[]) => void;
|
||||
importGitHubIssues: (projectId: string, issueNumbers: number[]) => Promise<IPCResult<GitHubImportResult>>;
|
||||
createGitHubRelease: (
|
||||
projectId: string,
|
||||
@@ -28,6 +30,9 @@ export interface GitHubAPI {
|
||||
options?: { draft?: boolean; prerelease?: boolean }
|
||||
) => Promise<IPCResult<{ url: string }>>;
|
||||
|
||||
/** AI-powered version suggestion based on commits since last release */
|
||||
suggestReleaseVersion: (projectId: string) => Promise<IPCResult<VersionSuggestion>>;
|
||||
|
||||
// OAuth operations (gh CLI)
|
||||
checkGitHubCli: () => Promise<IPCResult<{ installed: boolean; version?: string }>>;
|
||||
checkGitHubAuth: () => Promise<IPCResult<{ authenticated: boolean; username?: string }>>;
|
||||
@@ -36,6 +41,10 @@ export interface GitHubAPI {
|
||||
getGitHubUser: () => Promise<IPCResult<{ username: string; name?: string }>>;
|
||||
listGitHubUserRepos: () => Promise<IPCResult<{ repos: Array<{ fullName: string; description: string | null; isPrivate: boolean }> }>>;
|
||||
|
||||
// Repository detection
|
||||
detectGitHubRepo: (projectPath: string) => Promise<IPCResult<string>>;
|
||||
getGitHubBranches: (repo: string, token: string) => Promise<IPCResult<string[]>>;
|
||||
|
||||
// Event Listeners
|
||||
onGitHubInvestigationProgress: (
|
||||
callback: (projectId: string, status: GitHubInvestigationStatus) => void
|
||||
@@ -62,11 +71,14 @@ export const createGitHubAPI = (): GitHubAPI => ({
|
||||
getGitHubIssue: (projectId: string, issueNumber: number): Promise<IPCResult<GitHubIssue>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_GET_ISSUE, projectId, issueNumber),
|
||||
|
||||
getIssueComments: (projectId: string, issueNumber: number): Promise<IPCResult<any[]>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_GET_ISSUE_COMMENTS, projectId, issueNumber),
|
||||
|
||||
checkGitHubConnection: (projectId: string): Promise<IPCResult<GitHubSyncStatus>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_CHECK_CONNECTION, projectId),
|
||||
|
||||
investigateGitHubIssue: (projectId: string, issueNumber: number): void =>
|
||||
sendIpc(IPC_CHANNELS.GITHUB_INVESTIGATE_ISSUE, projectId, issueNumber),
|
||||
investigateGitHubIssue: (projectId: string, issueNumber: number, selectedCommentIds?: number[]): void =>
|
||||
sendIpc(IPC_CHANNELS.GITHUB_INVESTIGATE_ISSUE, projectId, issueNumber, selectedCommentIds),
|
||||
|
||||
importGitHubIssues: (projectId: string, issueNumbers: number[]): Promise<IPCResult<GitHubImportResult>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_IMPORT_ISSUES, projectId, issueNumbers),
|
||||
@@ -79,6 +91,9 @@ export const createGitHubAPI = (): GitHubAPI => ({
|
||||
): Promise<IPCResult<{ url: string }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_CREATE_RELEASE, projectId, version, releaseNotes, options),
|
||||
|
||||
suggestReleaseVersion: (projectId: string): Promise<IPCResult<VersionSuggestion>> =>
|
||||
invokeIpc(IPC_CHANNELS.RELEASE_SUGGEST_VERSION, projectId),
|
||||
|
||||
// OAuth operations (gh CLI)
|
||||
checkGitHubCli: (): Promise<IPCResult<{ installed: boolean; version?: string }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_CHECK_CLI),
|
||||
@@ -98,6 +113,13 @@ export const createGitHubAPI = (): GitHubAPI => ({
|
||||
listGitHubUserRepos: (): Promise<IPCResult<{ repos: Array<{ fullName: string; description: string | null; isPrivate: boolean }> }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_LIST_USER_REPOS),
|
||||
|
||||
// Repository detection
|
||||
detectGitHubRepo: (projectPath: string): Promise<IPCResult<string>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_DETECT_REPO, projectPath),
|
||||
|
||||
getGitHubBranches: (repo: string, token: string): Promise<IPCResult<string[]>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_GET_BRANCHES, repo, token),
|
||||
|
||||
// Event Listeners
|
||||
onGitHubInvestigationProgress: (
|
||||
callback: (projectId: string, status: GitHubInvestigationStatus) => void
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
InsightsSessionSummary,
|
||||
InsightsChatStatus,
|
||||
InsightsStreamChunk,
|
||||
InsightsModelConfig,
|
||||
Task,
|
||||
TaskMetadata,
|
||||
IPCResult
|
||||
@@ -16,7 +17,7 @@ import { createIpcListener, invokeIpc, sendIpc, IpcListenerCleanup } from './ipc
|
||||
export interface InsightsAPI {
|
||||
// Operations
|
||||
getInsightsSession: (projectId: string) => Promise<IPCResult<InsightsSession | null>>;
|
||||
sendInsightsMessage: (projectId: string, message: string) => void;
|
||||
sendInsightsMessage: (projectId: string, message: string, modelConfig?: InsightsModelConfig) => void;
|
||||
clearInsightsSession: (projectId: string) => Promise<IPCResult>;
|
||||
createTaskFromInsights: (
|
||||
projectId: string,
|
||||
@@ -29,6 +30,7 @@ export interface InsightsAPI {
|
||||
switchInsightsSession: (projectId: string, sessionId: string) => Promise<IPCResult<InsightsSession | null>>;
|
||||
deleteInsightsSession: (projectId: string, sessionId: string) => Promise<IPCResult>;
|
||||
renameInsightsSession: (projectId: string, sessionId: string, newTitle: string) => Promise<IPCResult>;
|
||||
updateInsightsModelConfig: (projectId: string, sessionId: string, modelConfig: InsightsModelConfig) => Promise<IPCResult>;
|
||||
|
||||
// Event Listeners
|
||||
onInsightsStreamChunk: (
|
||||
@@ -50,8 +52,8 @@ export const createInsightsAPI = (): InsightsAPI => ({
|
||||
getInsightsSession: (projectId: string): Promise<IPCResult<InsightsSession | null>> =>
|
||||
invokeIpc(IPC_CHANNELS.INSIGHTS_GET_SESSION, projectId),
|
||||
|
||||
sendInsightsMessage: (projectId: string, message: string): void =>
|
||||
sendIpc(IPC_CHANNELS.INSIGHTS_SEND_MESSAGE, projectId, message),
|
||||
sendInsightsMessage: (projectId: string, message: string, modelConfig?: InsightsModelConfig): void =>
|
||||
sendIpc(IPC_CHANNELS.INSIGHTS_SEND_MESSAGE, projectId, message, modelConfig),
|
||||
|
||||
clearInsightsSession: (projectId: string): Promise<IPCResult> =>
|
||||
invokeIpc(IPC_CHANNELS.INSIGHTS_CLEAR_SESSION, projectId),
|
||||
@@ -79,6 +81,9 @@ export const createInsightsAPI = (): InsightsAPI => ({
|
||||
renameInsightsSession: (projectId: string, sessionId: string, newTitle: string): Promise<IPCResult> =>
|
||||
invokeIpc(IPC_CHANNELS.INSIGHTS_RENAME_SESSION, projectId, sessionId, newTitle),
|
||||
|
||||
updateInsightsModelConfig: (projectId: string, sessionId: string, modelConfig: InsightsModelConfig): Promise<IPCResult> =>
|
||||
invokeIpc(IPC_CHANNELS.INSIGHTS_UPDATE_MODEL_CONFIG, projectId, sessionId, modelConfig),
|
||||
|
||||
// Event Listeners
|
||||
onInsightsStreamChunk: (
|
||||
callback: (projectId: string, chunk: InsightsStreamChunk) => void
|
||||
|
||||
@@ -12,7 +12,7 @@ export type IpcListenerCleanup = () => void;
|
||||
* @param callback - The callback function to execute when event is received
|
||||
* @returns Cleanup function to remove the listener
|
||||
*/
|
||||
export function createIpcListener<T extends any[]>(
|
||||
export function createIpcListener<T extends unknown[]>(
|
||||
channel: string,
|
||||
callback: (...args: T) => void
|
||||
): IpcListenerCleanup {
|
||||
@@ -32,7 +32,7 @@ export function createIpcListener<T extends any[]>(
|
||||
* @param args - Arguments to pass to the IPC handler
|
||||
* @returns Promise with the typed result
|
||||
*/
|
||||
export function invokeIpc<T>(channel: string, ...args: any[]): Promise<T> {
|
||||
export function invokeIpc<T>(channel: string, ...args: unknown[]): Promise<T> {
|
||||
return ipcRenderer.invoke(channel, ...args);
|
||||
}
|
||||
|
||||
@@ -42,6 +42,6 @@ export function invokeIpc<T>(channel: string, ...args: any[]): Promise<T> {
|
||||
* @param channel - The IPC channel to send to
|
||||
* @param args - Arguments to pass to the IPC handler
|
||||
*/
|
||||
export function sendIpc(channel: string, ...args: any[]): void {
|
||||
export function sendIpc(channel: string, ...args: unknown[]): void {
|
||||
ipcRenderer.send(channel, ...args);
|
||||
}
|
||||
|
||||
@@ -14,9 +14,11 @@ import { createIpcListener, invokeIpc, sendIpc, IpcListenerCleanup } from './ipc
|
||||
export interface RoadmapAPI {
|
||||
// Operations
|
||||
getRoadmap: (projectId: string) => Promise<IPCResult<Roadmap | null>>;
|
||||
getRoadmapStatus: (projectId: string) => Promise<IPCResult<{ isRunning: boolean }>>;
|
||||
saveRoadmap: (projectId: string, roadmap: Roadmap) => Promise<IPCResult>;
|
||||
generateRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean) => void;
|
||||
refreshRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean) => void;
|
||||
stopRoadmap: (projectId: string) => Promise<IPCResult>;
|
||||
updateFeatureStatus: (
|
||||
projectId: string,
|
||||
featureId: string,
|
||||
@@ -37,6 +39,9 @@ export interface RoadmapAPI {
|
||||
onRoadmapError: (
|
||||
callback: (projectId: string, error: string) => void
|
||||
) => IpcListenerCleanup;
|
||||
onRoadmapStopped: (
|
||||
callback: (projectId: string) => void
|
||||
) => IpcListenerCleanup;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -47,6 +52,9 @@ export const createRoadmapAPI = (): RoadmapAPI => ({
|
||||
getRoadmap: (projectId: string): Promise<IPCResult<Roadmap | null>> =>
|
||||
invokeIpc(IPC_CHANNELS.ROADMAP_GET, projectId),
|
||||
|
||||
getRoadmapStatus: (projectId: string): Promise<IPCResult<{ isRunning: boolean }>> =>
|
||||
invokeIpc(IPC_CHANNELS.ROADMAP_GET_STATUS, projectId),
|
||||
|
||||
saveRoadmap: (projectId: string, roadmap: Roadmap): Promise<IPCResult> =>
|
||||
invokeIpc(IPC_CHANNELS.ROADMAP_SAVE, projectId, roadmap),
|
||||
|
||||
@@ -56,6 +64,9 @@ export const createRoadmapAPI = (): RoadmapAPI => ({
|
||||
refreshRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean): void =>
|
||||
sendIpc(IPC_CHANNELS.ROADMAP_REFRESH, projectId, enableCompetitorAnalysis),
|
||||
|
||||
stopRoadmap: (projectId: string): Promise<IPCResult> =>
|
||||
invokeIpc(IPC_CHANNELS.ROADMAP_STOP, projectId),
|
||||
|
||||
updateFeatureStatus: (
|
||||
projectId: string,
|
||||
featureId: string,
|
||||
@@ -83,5 +94,10 @@ export const createRoadmapAPI = (): RoadmapAPI => ({
|
||||
onRoadmapError: (
|
||||
callback: (projectId: string, error: string) => void
|
||||
): IpcListenerCleanup =>
|
||||
createIpcListener(IPC_CHANNELS.ROADMAP_ERROR, callback)
|
||||
createIpcListener(IPC_CHANNELS.ROADMAP_ERROR, callback),
|
||||
|
||||
onRoadmapStopped: (
|
||||
callback: (projectId: string) => void
|
||||
): IpcListenerCleanup =>
|
||||
createIpcListener(IPC_CHANNELS.ROADMAP_STOPPED, callback)
|
||||
});
|
||||
|
||||
@@ -6,16 +6,12 @@ import type {
|
||||
IPCResult,
|
||||
InitializationResult,
|
||||
AutoBuildVersionInfo,
|
||||
ProjectContextData,
|
||||
ProjectIndex,
|
||||
GraphitiMemoryStatus,
|
||||
ContextSearchResult,
|
||||
MemoryEpisode,
|
||||
ProjectEnvConfig,
|
||||
ClaudeAuthResult,
|
||||
InfrastructureStatus,
|
||||
GraphitiValidationResult,
|
||||
GraphitiConnectionTestResult
|
||||
GraphitiConnectionTestResult,
|
||||
GitStatus
|
||||
} from '../../shared/types';
|
||||
|
||||
export interface ProjectAPI {
|
||||
@@ -32,11 +28,11 @@ export interface ProjectAPI {
|
||||
checkProjectVersion: (projectId: string) => Promise<IPCResult<AutoBuildVersionInfo>>;
|
||||
|
||||
// Context Operations
|
||||
getProjectContext: (projectId: string) => Promise<any>;
|
||||
refreshProjectIndex: (projectId: string) => Promise<any>;
|
||||
getMemoryStatus: (projectId: string) => Promise<any>;
|
||||
searchMemories: (projectId: string, query: string) => Promise<any>;
|
||||
getRecentMemories: (projectId: string, limit?: number) => Promise<any>;
|
||||
getProjectContext: (projectId: string) => Promise<IPCResult<unknown>>;
|
||||
refreshProjectIndex: (projectId: string) => Promise<IPCResult<unknown>>;
|
||||
getMemoryStatus: (projectId: string) => Promise<IPCResult<unknown>>;
|
||||
searchMemories: (projectId: string, query: string) => Promise<IPCResult<unknown>>;
|
||||
getRecentMemories: (projectId: string, limit?: number) => Promise<IPCResult<unknown>>;
|
||||
|
||||
// Environment Configuration
|
||||
getProjectEnv: (projectId: string) => Promise<IPCResult<ProjectEnvConfig>>;
|
||||
@@ -72,6 +68,8 @@ export interface ProjectAPI {
|
||||
getGitBranches: (projectPath: string) => Promise<IPCResult<string[]>>;
|
||||
getCurrentGitBranch: (projectPath: string) => Promise<IPCResult<string | null>>;
|
||||
detectMainBranch: (projectPath: string) => Promise<IPCResult<string | null>>;
|
||||
checkGitStatus: (projectPath: string) => Promise<IPCResult<GitStatus>>;
|
||||
initializeGit: (projectPath: string) => Promise<IPCResult<InitializationResult>>;
|
||||
}
|
||||
|
||||
export const createProjectAPI = (): ProjectAPI => ({
|
||||
@@ -180,5 +178,11 @@ export const createProjectAPI = (): ProjectAPI => ({
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_GET_CURRENT_BRANCH, projectPath),
|
||||
|
||||
detectMainBranch: (projectPath: string): Promise<IPCResult<string | null>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_DETECT_MAIN_BRANCH, projectPath)
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_DETECT_MAIN_BRANCH, projectPath),
|
||||
|
||||
checkGitStatus: (projectPath: string): Promise<IPCResult<GitStatus>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_CHECK_STATUS, projectPath),
|
||||
|
||||
initializeGit: (projectPath: string): Promise<IPCResult<InitializationResult>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_INITIALIZE, projectPath)
|
||||
});
|
||||
|
||||
@@ -5,9 +5,18 @@ import type {
|
||||
TerminalCreateOptions,
|
||||
RateLimitInfo,
|
||||
ClaudeProfile,
|
||||
ClaudeProfileSettings
|
||||
ClaudeProfileSettings,
|
||||
ClaudeUsageSnapshot
|
||||
} from '../../shared/types';
|
||||
|
||||
/** Type for proactive swap notification events */
|
||||
interface ProactiveSwapNotification {
|
||||
fromProfile: { id: string; name: string };
|
||||
toProfile: { id: string; name: string };
|
||||
reason: string;
|
||||
usageSnapshot: ClaudeUsageSnapshot;
|
||||
}
|
||||
|
||||
export interface TerminalAPI {
|
||||
// Terminal Operations
|
||||
createTerminal: (options: TerminalCreateOptions) => Promise<IPCResult>;
|
||||
@@ -67,7 +76,7 @@ export interface TerminalAPI {
|
||||
// Usage Monitoring (Proactive Account Switching)
|
||||
requestUsageUpdate: () => Promise<IPCResult<import('../../shared/types').ClaudeUsageSnapshot | null>>;
|
||||
onUsageUpdated: (callback: (usage: import('../../shared/types').ClaudeUsageSnapshot) => void) => () => void;
|
||||
onProactiveSwapNotification: (callback: (notification: any) => void) => () => void;
|
||||
onProactiveSwapNotification: (callback: (notification: ProactiveSwapNotification) => void) => () => void;
|
||||
}
|
||||
|
||||
export const createTerminalAPI = (): TerminalAPI => ({
|
||||
@@ -294,9 +303,9 @@ export const createTerminalAPI = (): TerminalAPI => ({
|
||||
},
|
||||
|
||||
onProactiveSwapNotification: (
|
||||
callback: (notification: any) => void
|
||||
callback: (notification: ProactiveSwapNotification) => void
|
||||
): (() => void) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, notification: any): void => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, notification: ProactiveSwapNotification): void => {
|
||||
callback(notification);
|
||||
};
|
||||
ipcRenderer.on(IPC_CHANNELS.PROACTIVE_SWAP_NOTIFICATION, handler);
|
||||
|
||||
@@ -6,3 +6,6 @@ const electronAPI = createElectronAPI();
|
||||
|
||||
// Expose to renderer via contextBridge
|
||||
contextBridge.exposeInMainWorld('electronAPI', electronAPI);
|
||||
|
||||
// Expose debug flag for debug logging
|
||||
contextBridge.exposeInMainWorld('DEBUG', process.env.DEBUG === 'true');
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user