Compare commits
47 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a20b8cf12a | |||
| 0ed6afb805 | |||
| 914a09d0da | |||
| e44202a066 | |||
| 42496446bc | |||
| b0fc497583 | |||
| 462edcdd93 | |||
| affbc48cbe | |||
| d7fd1a24da | |||
| 96dd04d411 | |||
| 1d0566fce7 | |||
| 7f3cd5969d | |||
| 0ef0e1588b | |||
| efc112a313 | |||
| d33a0aaff6 | |||
| 2fa3c51659 | |||
| 59b091a79f | |||
| a0c775f690 | |||
| 9babdc23c1 | |||
| dc886dce44 | |||
| 32760348ae | |||
| 395ba60098 | |||
| d85a1b4f63 | |||
| 43a593c1e1 | |||
| 5078191d74 | |||
| 99850512e6 | |||
| f92fcfa075 | |||
| f201f7e3a8 | |||
| 0da4bc4a84 | |||
| a0d142ba95 | |||
| 473b04530a | |||
| e5b9488a86 | |||
| de33b2c7c3 | |||
| eb77915879 | |||
| 7e09739f17 | |||
| e6d6cea9e4 | |||
| dfb5cf9c50 | |||
| 34631c38ea | |||
| 7c327ed007 | |||
| 5f9653a961 | |||
| 2d2a8131cc | |||
| ce9c2cddc1 | |||
| 460c76de42 | |||
| 4eb66f5004 | |||
| 788b8d0e3e | |||
| 957746e09c | |||
| 36338f3546 |
@@ -12,13 +12,14 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Send to Discord
|
||||
uses: SethCohen/github-releases-to-discord@v1
|
||||
uses: SethCohen/github-releases-to-discord@v1.19.0
|
||||
with:
|
||||
webhook_url: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||
color: "5865F2"
|
||||
color: "5793266"
|
||||
username: "Auto Claude Releases"
|
||||
avatar_url: "https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png"
|
||||
footer_title: "Auto Claude Changelog"
|
||||
footer_timestamp: true
|
||||
reduce_headings: true
|
||||
remove_github_reference_links: true
|
||||
|
||||
|
||||
+246
@@ -1,3 +1,249 @@
|
||||
## 2.3.2 - UI Polish & Build Improvements
|
||||
|
||||
### 🛠️ Improvements
|
||||
|
||||
- Restructured SortableFeatureCard badge layout for improved visual presentation
|
||||
|
||||
Bug Fixes:
|
||||
- Fixed spec runner path configuration for more reliable task execution
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- fix: fix to spec runner paths by @AndyMik90 in 9babdc2
|
||||
|
||||
- feat: auto-claude: subtask-1-1 - Restructure SortableFeatureCard badge layout by @AndyMik90 in dc886dc
|
||||
|
||||
## 2.3.1 - Linux Compatibility Fix
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- Resolved path handling issues on Linux systems for improved cross-platform compatibility
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- fix: Fix to linux path issue by @AndyMik90 in 3276034
|
||||
|
||||
## 2.2.0 - 2025-12-17
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
- Add usage monitoring with profile swap detection to prevent cascading resource issues
|
||||
|
||||
- Option to stash changes before merge operations for safer branch integration
|
||||
|
||||
- Add hideCloseButton prop to DialogContent component for improved UI flexibility
|
||||
|
||||
### 🛠️ Improvements
|
||||
|
||||
- Enhance AgentManager to manage task context cleanup and preserve swapCount on restarts
|
||||
|
||||
- Improve changelog feature with version tracking, markdown/preview, and persistent styling options
|
||||
|
||||
- Refactor merge conflict handling to use branch names instead of commit hashes for better clarity
|
||||
|
||||
- Streamline usage monitoring logic by removing unnecessary dynamic imports
|
||||
|
||||
- Better handling of lock files during merge conflicts
|
||||
|
||||
- Refactor code for improved readability and maintainability
|
||||
|
||||
- Refactor IdeationHeader and update handleDeleteSelected logic
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- Fix worktree merge logic to correctly handle branch operations
|
||||
|
||||
- Fix spec_runner.py path resolution after move to runners/ directory
|
||||
|
||||
- Fix Discord release webhook failing on large changelogs
|
||||
|
||||
- Fix branch logic for merge AI operations
|
||||
|
||||
- Hotfix for spec-runner path location
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- fix: hotfix/spec-runner path location by @AndyMik90 in f201f7e
|
||||
|
||||
- refactor: Remove unnecessary dynamic imports of getUsageMonitor in terminal-handlers.ts to streamline usage monitoring logic by @AndyMik90 in 0da4bc4
|
||||
|
||||
- feat: Improve changelog feature, version tracking, markdown/preview, persistent styling options by @AndyMik90 in a0d142b
|
||||
|
||||
- refactor: Refactor code for improved readability and maintainability by @AndyMik90 in 473b045
|
||||
|
||||
- feat: Enhance AgentManager to manage task context cleanup and preserve swapCount on restarts. Update UsageMonitor to delay profile usage checks to prevent cascading swaps by @AndyMik90 in e5b9488
|
||||
|
||||
- feat: Usage-monitoring by @AndyMik90 in de33b2c
|
||||
|
||||
- feat: option to stash changes before merge by @AndyMik90 in 7e09739
|
||||
|
||||
- refactor: Refactor merge conflict check to use branch names instead of commit hashes by @AndyMik90 in e6d6cea
|
||||
|
||||
- fix: worktree merge logic by @AndyMik90 in dfb5cf9
|
||||
|
||||
- test: Sign off - all verification passed by @AndyMik90 in 34631c3
|
||||
|
||||
- feat: Pass hideCloseButton={showFileExplorer} to DialogContent by @AndyMik90 in 7c327ed
|
||||
|
||||
- feat: Add hideCloseButton prop to DialogContent component by @AndyMik90 in 5f9653a
|
||||
|
||||
- fix: branch logic for merge AI by @AndyMik90 in 2d2a813
|
||||
|
||||
- fix: spec_runner.py path resolution after move to runners/ directory by @AndyMik90 in ce9c2cd
|
||||
|
||||
- refactor: Better handling of lock files during merge conflicts by @AndyMik90 in 460c76d
|
||||
|
||||
- fix: Discord release webhook failing on large changelogs by @AndyMik90 in 4eb66f5
|
||||
|
||||
- chore: Update CHANGELOG with new features, improvements, bug fixes, and other changes by @AndyMik90 in 788b8d0
|
||||
|
||||
- refactor: Enhance merge conflict handling by excluding lock files by @AndyMik90 in 957746e
|
||||
|
||||
- refactor: Refactor IdeationHeader and update handleDeleteSelected logic by @AndyMik90 in 36338f3
|
||||
|
||||
## What's New
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
- Added GitHub OAuth integration for seamless authentication
|
||||
|
||||
- Implemented roadmap feature management with kanban board and drag-and-drop support
|
||||
|
||||
- Added ability to select AI model during task creation with agent profiles
|
||||
|
||||
- Introduced file explorer integration and referenced files section in task creation wizard
|
||||
|
||||
- Added .gitignore entry management during project initialization
|
||||
|
||||
- Created comprehensive onboarding wizard with OAuth configuration, Graphiti setup, and first spec guidance
|
||||
|
||||
- Introduced Electron MCP for debugging and validation support
|
||||
|
||||
- Added BMM workflow status tracking and project scan reporting
|
||||
|
||||
### 🛠️ Improvements
|
||||
|
||||
- Refactored IdeationHeader component and improved deleteSelected logic
|
||||
|
||||
- Refactored backend for upcoming features with improved architecture
|
||||
|
||||
- Enhanced RouteDetector to exclude specific directories from route detection
|
||||
|
||||
- Improved merge conflict resolution with parallel processing and AI-assisted resolution
|
||||
|
||||
- Optimized merge conflict resolution performance and context sending
|
||||
|
||||
- Refactored AI resolver to use async context manager and Claude SDK patterns
|
||||
|
||||
- Enhanced merge orchestrator logic and frontend UX for conflict handling
|
||||
|
||||
- Refactored components for better maintainability and faster development
|
||||
|
||||
- Refactored changelog formatter for GitHub Release compatibility
|
||||
|
||||
- Enhanced onboarding wizard completion logic and step progression
|
||||
|
||||
- Updated README to clarify Auto Claude's role as an AI coding companion
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- Fixed GraphitiStep TypeScript compilation error
|
||||
|
||||
- Added missing onRerunWizard prop to AppSettingsDialog
|
||||
|
||||
- Improved merge lock file conflict handling
|
||||
|
||||
### 🔧 Other Changes
|
||||
|
||||
- Removed .auto-claude and _bmad-output from git tracking (already in .gitignore)
|
||||
|
||||
- Updated Python versions in CI workflows
|
||||
|
||||
- General linting improvements and code cleanup
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- feat: New github oauth integration by @AndyMik90 in afeb54f
|
||||
- feat: Implement roadmap feature management kanban with drag-and-drop support by @AndyMik90 in 9403230
|
||||
- feat: Agent profiles, be able to select model on task creation by @AndyMik90 in d735c5c
|
||||
- feat: Add Referenced Files Section and File Explorer Integration in Task Creation Wizard by @AndyMik90 in 31e4e87
|
||||
- feat: Add functionality to manage .gitignore entries during project initialization by @AndyMik90 in 2ac00a9
|
||||
- feat: Introduce electron mcp for electron debugging/validation by @AndyMik90 in 3eb2ead
|
||||
- feat: Add BMM workflow status tracking and project scan report by @AndyMik90 in 7f6456f
|
||||
- refactor: Refactor IdeationHeader and update handleDeleteSelected logic by @AndyMik90 in 36338f3
|
||||
- refactor: Big backend refactor for upcoming features by @AndyMik90 in 11fcdf4
|
||||
- refactor: Refactoring for better codebase by @AndyMik90 in feb0d4e
|
||||
- refactor: Refactor Roadmap component to utilize RoadmapGenerationProgress for better status display by @AndyMik90 in d8e5784
|
||||
- refactor: refactoring components for better future maintence and more rapid coding by @AndyMik90 in 131ec4c
|
||||
- refactor: Enhance RouteDetector to exclude specific directories from route detection by @AndyMik90 in 08dc24c
|
||||
- refactor: Update AI resolver to use Claude Opus model and improve error logging by @AndyMik90 in 1d830ba
|
||||
- refactor: Use claude sdk pattern for ai resolver by @AndyMik90 in 4bba9d1
|
||||
- refactor: Refactor AI resolver to use async context manager for client connection by @AndyMik90 in 579ea40
|
||||
- refactor: Update changelog formatter for GitHub Release compatibility by @AndyMik90 in 3b832db
|
||||
- refactor: Enhance onboarding wizard completion logic by @AndyMik90 in 7c01638
|
||||
- refactor: Update GraphitiStep to proceed to the next step after successful configuration save by @AndyMik90 in a5a1eb1
|
||||
- fix: Add onRerunWizard prop to AppSettingsDialog (qa-requested) by @AndyMik90 in 6b5b714
|
||||
- fix: Add first-run detection to App.tsx by @AndyMik90 in 779e36f
|
||||
- fix: Add TypeScript compilation check - fix GraphitiStep type error by @AndyMik90 in f90fa80
|
||||
- improve: ideation improvements and linting by @AndyMik90 in 36a69fc
|
||||
- improve: improve merge conflicts for lock files by @AndyMik90 in a891225
|
||||
- improve: Roadmap competitor analysis by @AndyMik90 in ddf47ae
|
||||
- improve: parallell merge conflict resolution by @AndyMik90 in f00aa33
|
||||
- improve: improvement to speed of merge conflict resolution by @AndyMik90 in 56ff586
|
||||
- improve: improve context sending to merge agent by @AndyMik90 in e409ae8
|
||||
- improve: better conflict handling in the frontend app for merge contlicts (better UX) by @AndyMik90 in 65937e1
|
||||
- improve: resolve claude agent sdk by @AndyMik90 in 901e83a
|
||||
- improve: Getting ready for BMAD integration by @AndyMik90 in b94eb65
|
||||
- improve: Enhance AI resolver and debugging output by @AndyMik90 in bf787ad
|
||||
- improve: Integrate profile environment for OAuth token in task handlers by @AndyMik90 in 01e801a
|
||||
- chore: Remove .auto-claude from tracking (already in .gitignore) by @AndyMik90 in 87f353c
|
||||
- chore: Update Python versions in CI workflows by @AndyMik90 in 43a338c
|
||||
- chore: Linting gods pleased now? by @AndyMik90 in 6aea4bb
|
||||
- chore: Linting and test fixes by @AndyMik90 in 140f11f
|
||||
- chore: Remove _bmad-output from git tracking by @AndyMik90 in 4cd7500
|
||||
- chore: Add _bmad-output to .gitignore by @AndyMik90 in dbe27f0
|
||||
- chore: Linting gods are happy by @AndyMik90 in 3fc1592
|
||||
- chore: Getting ready for the lint gods by @AndyMik90 in 142cd67
|
||||
- chore: CLI testing/linting by @AndyMik90 in d8ad17d
|
||||
- chore: CLI and tests by @AndyMik90 in 9a59b7e
|
||||
- chore: Update implementation_plan.json - fixes applied by @AndyMik90 in 555a46f
|
||||
- chore: Update parallel merge conflict resolution metrics in workspace.py by @AndyMik90 in 2e151ac
|
||||
- chore: merge logic v0.3 by @AndyMik90 in c5d33cd
|
||||
- chore: merge orcehestrator logic by @AndyMik90 in e8b6669
|
||||
- chore: Merge-orchestrator by @AndyMik90 in d8ba532
|
||||
- chore: merge orcehstrator logic by @AndyMik90 in e8b6669
|
||||
- chore: Electron UI fix for merge orcehstrator by @AndyMik90 in e08ab62
|
||||
- chore: Frontend lints by @AndyMik90 in 488bbfa
|
||||
- docs: Revise README.md to enhance clarity and focus on Auto Claude's capabilities by @AndyMik90 in f9ef7ea
|
||||
- qa: Sign off - all verification passed by @AndyMik90 in b3f4803
|
||||
- qa: Rejected - fixes required by @AndyMik90 in 5e56890
|
||||
- qa: subtask-6-2 - Run existing tests to verify no regressions by @AndyMik90 in 5f989a4
|
||||
- qa: subtask-5-2 - Enhance OAuthStep to detect and display if token is already configured by @AndyMik90 in 50f22da
|
||||
- qa: subtask-5-1 - Add settings migration logic - set onboardingCompleted by @AndyMik90 in f57c28e
|
||||
- qa: subtask-4-1 - Add 'Re-run Wizard' button to AppSettings navigation by @AndyMik90 in 9144e7f
|
||||
- qa: subtask-3-1 - Add first-run detection to App.tsx by @AndyMik90 in 779e36f
|
||||
- qa: subtask-2-8 - Create index.ts barrel export for onboarding components by @AndyMik90 in b0af2dc
|
||||
- qa: subtask-2-7 - Create OnboardingWizard component by @AndyMik90 in 3de8928
|
||||
- qa: subtask-2-6 - Create CompletionStep component - success message by @AndyMik90 in aa0f608
|
||||
- qa: subtask-2-5 - Create FirstSpecStep component - guided first spec by @AndyMik90 in 32f17a1
|
||||
- qa: subtask-2-4 - Create GraphitiStep component - optional Graphiti/FalkorDB configuration by @AndyMik90 in 61184b0
|
||||
- qa: subtask-2-3 - Create OAuthStep component - Claude OAuth token configuration step by @AndyMik90 in 79d622e
|
||||
- qa: subtask-2-2 - Create WelcomeStep component by @AndyMik90 in a97f697
|
||||
- qa: subtask-2-1 - Create WizardProgress component - step progress indicator by @AndyMik90 in b6e604c
|
||||
- qa: subtask-1-2 - Add onboardingCompleted to DEFAULT_APP_SETTINGS by @AndyMik90 in c5a0331
|
||||
- qa: subtask-1-1 - Add onboardingCompleted to AppSettings type interface by @AndyMik90 in 7c24b48
|
||||
- chore: Version 2.0.1 by @AndyMik90 in 4b242c4
|
||||
- test: Merge-orchestrator by @AndyMik90 in d8ba532
|
||||
- test: test for ai merge AI by @AndyMik90 in 9d9cf16
|
||||
|
||||
## What's New in 2.0.1
|
||||
|
||||
### 🚀 New Features
|
||||
|
||||
@@ -39,6 +39,20 @@ The Desktop UI is the recommended way to use Auto Claude. It provides visual tas
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
@@ -251,6 +265,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.
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
# Auto Claude Update System Analysis
|
||||
|
||||
## Current State
|
||||
|
||||
The app has **TWO separate update systems** for different components:
|
||||
|
||||
### 1. ✅ Auto Claude Framework Updates (WORKING)
|
||||
|
||||
**What it updates:** The Python framework source code (`auto-claude/` directory)
|
||||
|
||||
**How it works:**
|
||||
- Checks GitHub Releases API for new versions
|
||||
- Downloads release tarball
|
||||
- Extracts and applies update to the bundled source
|
||||
- Preserves user configuration files (.env, etc.)
|
||||
|
||||
**User Experience:**
|
||||
- **Settings > Advanced > Updates** section
|
||||
- Visual update checker with version display
|
||||
- Release notes rendered in UI
|
||||
- Progress bar during download
|
||||
- One-click update button
|
||||
- Works across all platforms (macOS, Windows, Linux)
|
||||
|
||||
**Files:**
|
||||
- `auto-claude-ui/src/main/auto-claude-updater.ts` - Main updater module
|
||||
- `auto-claude-ui/src/main/updater/update-checker.ts` - Update checking
|
||||
- `auto-claude-ui/src/main/updater/update-installer.ts` - Download & install
|
||||
- `auto-claude-ui/src/main/ipc-handlers/autobuild-source-handlers.ts` - IPC handlers
|
||||
- `auto-claude-ui/src/renderer/components/settings/AdvancedSettings.tsx` - UI
|
||||
|
||||
**Status:** ✅ **FULLY FUNCTIONAL** - Non-technical users can update the framework with one click!
|
||||
|
||||
---
|
||||
|
||||
### 2. ❌ Electron App Updates (NOT IMPLEMENTED)
|
||||
|
||||
**What it updates:** The Electron application itself (Auto Claude UI)
|
||||
|
||||
**Current State:**
|
||||
- ❌ No `electron-updater` dependency installed
|
||||
- ❌ No auto-update configuration in electron-builder
|
||||
- ❌ No update checking in main process
|
||||
- ❌ No UI for app update notifications
|
||||
- ❌ Users must manually download new releases from GitHub
|
||||
|
||||
**What users currently need to do:**
|
||||
1. Go to GitHub Releases page
|
||||
2. Download the appropriate installer (.dmg, .exe, .AppImage, etc.)
|
||||
3. Run the installer
|
||||
4. Manually replace the old app
|
||||
|
||||
---
|
||||
|
||||
## What Needs to Be Implemented
|
||||
|
||||
To enable automatic Electron app updates for non-technical users, we need to add:
|
||||
|
||||
### 1. Install electron-updater
|
||||
|
||||
```bash
|
||||
npm install electron-updater
|
||||
```
|
||||
|
||||
### 2. Configure electron-builder for Publishing
|
||||
|
||||
Add to `package.json` build config:
|
||||
|
||||
```json
|
||||
{
|
||||
"build": {
|
||||
"publish": [
|
||||
{
|
||||
"provider": "github",
|
||||
"owner": "AndyMik90",
|
||||
"repo": "Auto-Claude"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Implement Auto-Update Logic in Main Process
|
||||
|
||||
Create `auto-claude-ui/src/main/app-updater.ts`:
|
||||
|
||||
```typescript
|
||||
import { autoUpdater } from 'electron-updater';
|
||||
import { app, BrowserWindow } from 'electron';
|
||||
|
||||
export function initializeAppUpdater(mainWindow: BrowserWindow) {
|
||||
// Configure update checking
|
||||
autoUpdater.autoDownload = false; // Let user decide
|
||||
autoUpdater.autoInstallOnAppQuit = true;
|
||||
|
||||
// Check for updates on launch (after 3 seconds)
|
||||
setTimeout(() => {
|
||||
autoUpdater.checkForUpdates();
|
||||
}, 3000);
|
||||
|
||||
// Check periodically (every 4 hours)
|
||||
setInterval(() => {
|
||||
autoUpdater.checkForUpdates();
|
||||
}, 4 * 60 * 60 * 1000);
|
||||
|
||||
// Event handlers
|
||||
autoUpdater.on('update-available', (info) => {
|
||||
mainWindow.webContents.send('app-update-available', {
|
||||
version: info.version,
|
||||
releaseNotes: info.releaseNotes,
|
||||
releaseDate: info.releaseDate
|
||||
});
|
||||
});
|
||||
|
||||
autoUpdater.on('update-downloaded', (info) => {
|
||||
mainWindow.webContents.send('app-update-downloaded', {
|
||||
version: info.version
|
||||
});
|
||||
});
|
||||
|
||||
autoUpdater.on('error', (error) => {
|
||||
console.error('App update error:', error);
|
||||
});
|
||||
|
||||
autoUpdater.on('download-progress', (progress) => {
|
||||
mainWindow.webContents.send('app-update-progress', {
|
||||
percent: progress.percent,
|
||||
transferred: progress.transferred,
|
||||
total: progress.total
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// IPC handlers
|
||||
export function registerAppUpdateHandlers() {
|
||||
ipcMain.handle('app-update-download', async () => {
|
||||
await autoUpdater.downloadUpdate();
|
||||
});
|
||||
|
||||
ipcMain.handle('app-update-install', () => {
|
||||
autoUpdater.quitAndInstall();
|
||||
});
|
||||
|
||||
ipcMain.handle('app-update-check', async () => {
|
||||
return await autoUpdater.checkForUpdates();
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Add UI Notification Component
|
||||
|
||||
Create an update banner or modal in the renderer that:
|
||||
- Shows when app update is available
|
||||
- Displays version and release notes
|
||||
- Has "Download Update" button
|
||||
- Shows download progress
|
||||
- Has "Install and Restart" button after download
|
||||
|
||||
### 5. Update GitHub Release Workflow
|
||||
|
||||
Ensure GitHub releases are created with proper assets:
|
||||
- macOS: `.dmg` and `.zip` files + `latest-mac.yml`
|
||||
- Windows: `.exe` installer + `latest.yml`
|
||||
- Linux: `.AppImage` and `.deb` + `latest-linux.yml`
|
||||
|
||||
The `latest-*.yml` files are auto-generated by electron-builder and contain update metadata.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Strategy
|
||||
|
||||
### Option A: Full Auto-Update (Recommended)
|
||||
|
||||
**Pros:**
|
||||
- Best user experience
|
||||
- Automatic background downloads
|
||||
- One-click install
|
||||
- Industry standard
|
||||
|
||||
**Cons:**
|
||||
- Requires code signing certificates for production (macOS, Windows)
|
||||
- Without signing, users get security warnings
|
||||
|
||||
### Option B: Update Notification Only
|
||||
|
||||
**Pros:**
|
||||
- Simpler implementation
|
||||
- No code signing required
|
||||
- User downloads from GitHub (trusted source)
|
||||
|
||||
**Cons:**
|
||||
- Users still need to manually download and install
|
||||
- Less convenient than auto-update
|
||||
|
||||
**Implementation:**
|
||||
```typescript
|
||||
// Just notify, don't auto-download
|
||||
autoUpdater.autoDownload = false;
|
||||
|
||||
autoUpdater.on('update-available', (info) => {
|
||||
// Show notification with link to GitHub Releases
|
||||
mainWindow.webContents.send('app-update-available', {
|
||||
version: info.version,
|
||||
downloadUrl: `https://github.com/AndyMik90/Auto-Claude/releases/tag/v${info.version}`
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Development vs Production
|
||||
|
||||
**Important:** `electron-updater` only works in **packaged apps**, not in development mode.
|
||||
|
||||
During development:
|
||||
```typescript
|
||||
if (app.isPackaged) {
|
||||
initializeAppUpdater(mainWindow);
|
||||
} else {
|
||||
console.log('[Dev] Auto-updater disabled in development mode');
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Code Signing Requirements
|
||||
|
||||
For production auto-updates without security warnings:
|
||||
|
||||
### macOS
|
||||
- Requires Apple Developer account ($99/year)
|
||||
- Code signing certificate
|
||||
- Notarization with Apple
|
||||
|
||||
### Windows
|
||||
- Requires code signing certificate (~$200-400/year)
|
||||
- Without: Windows SmartScreen warnings
|
||||
|
||||
### Linux
|
||||
- No code signing required
|
||||
- Users may need to mark `.AppImage` as executable
|
||||
|
||||
---
|
||||
|
||||
## Testing Auto-Updates
|
||||
|
||||
1. **Local Testing:**
|
||||
- Build and package: `npm run package`
|
||||
- Create local update server or use GitHub Releases
|
||||
- Test with different versions
|
||||
|
||||
2. **GitHub Releases Testing:**
|
||||
- Create a draft release on GitHub
|
||||
- Publish with version tag (e.g., `v2.4.0`)
|
||||
- electron-builder automatically uploads assets
|
||||
- Test with previous version installed
|
||||
|
||||
---
|
||||
|
||||
## Recommended Next Steps
|
||||
|
||||
1. **Phase 1: Add Update Notification** (Quick win)
|
||||
- Install `electron-updater`
|
||||
- Add basic update checking
|
||||
- Show notification with link to GitHub Releases
|
||||
- No auto-download, users download manually
|
||||
|
||||
2. **Phase 2: Enable Auto-Download** (Better UX)
|
||||
- Add download progress UI
|
||||
- Enable auto-download of updates
|
||||
- Add "Install and Restart" button
|
||||
|
||||
3. **Phase 3: Code Signing** (Production ready)
|
||||
- Acquire code signing certificates
|
||||
- Configure signing in electron-builder
|
||||
- Notarize macOS builds
|
||||
- Sign Windows builds
|
||||
|
||||
---
|
||||
|
||||
## Current Framework Update Flow (Already Working!)
|
||||
|
||||
For reference, here's how the existing Auto Claude framework updater works:
|
||||
|
||||
1. User opens **Settings > Advanced > Updates**
|
||||
2. App checks GitHub Releases API
|
||||
3. If update available, shows version + release notes
|
||||
4. User clicks "Download Update"
|
||||
5. Progress bar shows download status
|
||||
6. Update is extracted and applied to bundled source
|
||||
7. User configuration (.env) is preserved
|
||||
8. Done - no restart needed!
|
||||
|
||||
**This same UX could be replicated for app updates!**
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
| Component | Status | User Experience |
|
||||
|-----------|--------|-----------------|
|
||||
| Auto Claude Framework | ✅ Working | One-click update in Settings |
|
||||
| Electron App (UI) | ❌ Missing | Must download from GitHub manually |
|
||||
|
||||
**Recommendation:** Implement electron-updater with update notifications (Phase 1) as a quick win. This will enable non-technical users to update the app without using git or terminal commands.
|
||||
|
||||
**Estimated effort:**
|
||||
- Phase 1 (Notifications): 2-4 hours
|
||||
- Phase 2 (Auto-download): 2-3 hours
|
||||
- Phase 3 (Code signing): Varies by platform
|
||||
|
||||
The existing framework updater code provides an excellent reference for the UI implementation!
|
||||
@@ -0,0 +1,139 @@
|
||||
# Windows/Linux Source Path Detection Fix
|
||||
|
||||
## Problem
|
||||
|
||||
On Windows and Linux, when initializing a project, users were getting a "Source path not configured" error even though the `auto-claude` source directory exists. This error did not occur on macOS.
|
||||
|
||||
## Root Cause
|
||||
|
||||
The `detectAutoBuildSourcePath()` function in two files was using path resolution logic that worked on macOS in development mode but failed on Windows/Linux, especially in production/packaged builds. The function was trying to auto-detect where the Auto Claude framework source code (`auto-claude/` directory) is located, but the paths resolved differently across platforms.
|
||||
|
||||
## Changes Made
|
||||
|
||||
### 1. Enhanced Path Detection Logic
|
||||
|
||||
Updated `detectAutoBuildSourcePath()` in two files:
|
||||
- `auto-claude-ui/src/main/ipc-handlers/settings-handlers.ts`
|
||||
- `auto-claude-ui/src/main/ipc-handlers/project-handlers.ts`
|
||||
|
||||
**Key improvements:**
|
||||
|
||||
1. **Platform-aware path detection**: Separates development vs production mode using `is.dev` from `@electron-toolkit/utils`
|
||||
|
||||
2. **More comprehensive path checking**:
|
||||
- **Development mode**: Checks multiple relative paths from `__dirname`, `process.cwd()`, and parent directories
|
||||
- **Production mode**: Checks paths relative to `app.getAppPath()`, `process.resourcesPath`, and multiple levels up
|
||||
|
||||
3. **Debug logging**: Added detailed logging that can be enabled with `AUTO_CLAUDE_DEBUG=1` environment variable
|
||||
|
||||
4. **Better error messages**: Console warnings now guide users to enable debug mode if auto-detection fails
|
||||
|
||||
## Testing on Windows/Linux
|
||||
|
||||
### 1. Run with Debug Logging
|
||||
|
||||
Set the environment variable to see detailed path checking:
|
||||
|
||||
**Windows (PowerShell):**
|
||||
```powershell
|
||||
$env:AUTO_CLAUDE_DEBUG="1"
|
||||
.\Auto-Claude.exe
|
||||
```
|
||||
|
||||
**Windows (Command Prompt):**
|
||||
```cmd
|
||||
set AUTO_CLAUDE_DEBUG=1
|
||||
Auto-Claude.exe
|
||||
```
|
||||
|
||||
**Linux:**
|
||||
```bash
|
||||
AUTO_CLAUDE_DEBUG=1 ./Auto-Claude
|
||||
```
|
||||
|
||||
### 2. Check Console Output
|
||||
|
||||
The debug output will show:
|
||||
- Current platform (win32/linux/darwin)
|
||||
- Whether running in dev or production mode
|
||||
- All paths being checked
|
||||
- Which paths exist and which don't
|
||||
- Whether auto-detection succeeded
|
||||
|
||||
Example debug output:
|
||||
```
|
||||
[detectAutoBuildSourcePath] Platform: win32
|
||||
[detectAutoBuildSourcePath] Is dev: false
|
||||
[detectAutoBuildSourcePath] __dirname: C:\Program Files\Auto-Claude\resources\app.asar\out\main
|
||||
[detectAutoBuildSourcePath] app.getAppPath(): C:\Program Files\Auto-Claude\resources\app.asar
|
||||
[detectAutoBuildSourcePath] process.cwd(): C:\Program Files\Auto-Claude
|
||||
[detectAutoBuildSourcePath] Checking paths: [...]
|
||||
[detectAutoBuildSourcePath] Checking C:\Program Files\auto-claude: ✗ not found
|
||||
[detectAutoBuildSourcePath] Checking C:\auto-claude: ✓ FOUND
|
||||
[detectAutoBuildSourcePath] Auto-detected source path: C:\auto-claude
|
||||
```
|
||||
|
||||
### 3. Manual Configuration (Fallback)
|
||||
|
||||
If auto-detection still fails, users can manually configure the path:
|
||||
|
||||
1. Open **App Settings** in Auto Claude UI
|
||||
2. Go to the **General** tab
|
||||
3. Set **Auto Claude Source Path** to the location of your `auto-claude` directory
|
||||
4. Click **Save**
|
||||
|
||||
Example paths:
|
||||
- Windows: `C:\Users\YourName\Projects\autonomous-coding\auto-claude`
|
||||
- Linux: `/home/yourname/projects/autonomous-coding/auto-claude`
|
||||
|
||||
## What Gets Checked
|
||||
|
||||
The function now checks these paths in order:
|
||||
|
||||
### Development Mode (`is.dev = true`):
|
||||
1. `__dirname/../../../auto-claude` - From out/main up 3 levels
|
||||
2. `__dirname/../../auto-claude` - From out/main up 2 levels
|
||||
3. `process.cwd()/auto-claude` - From current working directory
|
||||
4. `process.cwd()/../auto-claude` - From parent of cwd
|
||||
|
||||
### Production Mode (`is.dev = false`):
|
||||
1. `app.getAppPath()/../auto-claude` - Sibling to app
|
||||
2. `app.getAppPath()/../../auto-claude` - Up 2 from app
|
||||
3. `app.getAppPath()/../../../auto-claude` - Up 3 from app
|
||||
4. `process.resourcesPath/../auto-claude` - Relative to resources
|
||||
5. `process.resourcesPath/../../auto-claude` - Up 2 from resources
|
||||
|
||||
### All Modes:
|
||||
- `process.cwd()/auto-claude` - Last resort fallback
|
||||
|
||||
## Verification
|
||||
|
||||
For each path, the function checks:
|
||||
1. Does the directory exist?
|
||||
2. Does `VERSION` file exist inside it?
|
||||
|
||||
Both must be true for a path to be considered valid.
|
||||
|
||||
## Build Verification
|
||||
|
||||
The changes have been compiled and tested:
|
||||
```
|
||||
✓ Built successfully with no errors
|
||||
✓ All TypeScript files compiled
|
||||
✓ Electron app bundle created
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. **Test on Windows**: Have Windows users test the updated build with `AUTO_CLAUDE_DEBUG=1`
|
||||
2. **Test on Linux**: Have Linux users test the updated build with `AUTO_CLAUDE_DEBUG=1`
|
||||
3. **Collect feedback**: If issues persist, the debug output will help identify the correct path patterns
|
||||
4. **Update documentation**: Add troubleshooting section to main README if needed
|
||||
|
||||
## Related Files
|
||||
|
||||
- `auto-claude-ui/src/main/ipc-handlers/settings-handlers.ts`
|
||||
- `auto-claude-ui/src/main/ipc-handlers/project-handlers.ts`
|
||||
- `auto-claude-ui/src/main/project-initializer.ts`
|
||||
- `auto-claude-ui/src/renderer/App.tsx` (shows the error dialog)
|
||||
- `auto-claude-ui/src/renderer/components/Sidebar.tsx` (shows the error dialog)
|
||||
+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,6 +1,6 @@
|
||||
{
|
||||
"name": "auto-claude-ui",
|
||||
"version": "2.0.1",
|
||||
"version": "2.3.0",
|
||||
"description": "Desktop UI for Auto Claude autonomous coding framework",
|
||||
"main": "./out/main/index.js",
|
||||
"author": "Auto Claude Team",
|
||||
@@ -45,20 +45,26 @@
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@radix-ui/react-toast": "^1.2.15",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@tailwindcss/typography": "^0.5.19",
|
||||
"@tanstack/react-virtual": "^3.13.13",
|
||||
"@xterm/addon-fit": "^0.10.0",
|
||||
"@xterm/addon-serialize": "^0.13.0",
|
||||
"@xterm/addon-web-links": "^0.11.0",
|
||||
"@xterm/addon-webgl": "^0.18.0",
|
||||
"@xterm/xterm": "^5.5.0",
|
||||
"chokidar": "^5.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"electron-updater": "^6.6.2",
|
||||
"ioredis": "^5.8.2",
|
||||
"lucide-react": "^0.560.0",
|
||||
"motion": "^12.23.26",
|
||||
"node-pty": "^1.0.0",
|
||||
"node-pty": "^1.1.0-beta42",
|
||||
"react": "^19.2.3",
|
||||
"react-dom": "^19.2.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-resizable-panels": "^3.0.6",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"uuid": "^13.0.0",
|
||||
"zustand": "^5.0.9"
|
||||
@@ -109,12 +115,30 @@
|
||||
"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"
|
||||
}
|
||||
],
|
||||
"mac": {
|
||||
"category": "public.app-category.developer-tools",
|
||||
@@ -125,7 +149,7 @@
|
||||
]
|
||||
},
|
||||
"win": {
|
||||
"icon": "resources/icon-256.png",
|
||||
"icon": "resources/icon.ico",
|
||||
"target": [
|
||||
"nsis",
|
||||
"zip"
|
||||
|
||||
Generated
+955
-11
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 74 KiB |
@@ -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');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -39,12 +39,15 @@ function setupTestDirs(): void {
|
||||
// Create auto-claude source directory that getAutoBuildSourcePath looks for
|
||||
mkdirSync(AUTO_CLAUDE_SOURCE, { recursive: true });
|
||||
|
||||
// Create VERSION file (required by getAutoBuildSourcePath)
|
||||
writeFileSync(path.join(AUTO_CLAUDE_SOURCE, 'VERSION'), '1.0.0');
|
||||
// Create requirements.txt file (used as marker by getAutoBuildSourcePath)
|
||||
writeFileSync(path.join(AUTO_CLAUDE_SOURCE, 'requirements.txt'), '# Mock requirements');
|
||||
|
||||
// Create mock spec_runner.py
|
||||
// Create runners subdirectory (where spec_runner.py lives after restructure)
|
||||
mkdirSync(path.join(AUTO_CLAUDE_SOURCE, 'runners'), { recursive: true });
|
||||
|
||||
// Create mock spec_runner.py in runners/ subdirectory
|
||||
writeFileSync(
|
||||
path.join(AUTO_CLAUDE_SOURCE, 'spec_runner.py'),
|
||||
path.join(AUTO_CLAUDE_SOURCE, 'runners', 'spec_runner.py'),
|
||||
'# Mock spec runner\nprint("Starting spec creation")'
|
||||
);
|
||||
// Create mock run.py
|
||||
|
||||
@@ -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'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -6,9 +6,6 @@ import { AgentEvents } from './agent-events';
|
||||
import { AgentProcessManager } from './agent-process';
|
||||
import { AgentQueueManager } from './agent-queue';
|
||||
import {
|
||||
AgentManagerEvents,
|
||||
ExecutionProgressData,
|
||||
ProcessType,
|
||||
SpecCreationMetadata,
|
||||
TaskExecutionOptions,
|
||||
IdeationConfig
|
||||
@@ -23,6 +20,16 @@ export class AgentManager extends EventEmitter {
|
||||
private events: AgentEvents;
|
||||
private processManager: AgentProcessManager;
|
||||
private queueManager: AgentQueueManager;
|
||||
private taskExecutionContext: Map<string, {
|
||||
projectPath: string;
|
||||
specId: string;
|
||||
options: TaskExecutionOptions;
|
||||
isSpecCreation?: boolean;
|
||||
taskDescription?: string;
|
||||
specDir?: string;
|
||||
metadata?: SpecCreationMetadata;
|
||||
swapCount: number;
|
||||
}> = new Map();
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
@@ -32,6 +39,37 @@ export class AgentManager extends EventEmitter {
|
||||
this.events = new AgentEvents();
|
||||
this.processManager = new AgentProcessManager(this.state, this.events, this);
|
||||
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) => {
|
||||
this.restartTask(taskId);
|
||||
});
|
||||
|
||||
// Listen for task completion to clean up context (prevent memory leak)
|
||||
this.on('exit', (taskId: string, code: number | null) => {
|
||||
// Clean up context when:
|
||||
// 1. Task completed successfully (code === 0), or
|
||||
// 2. Task failed and won't be restarted (handled by auto-swap logic)
|
||||
|
||||
// Note: Auto-swap restart happens BEFORE this exit event is processed,
|
||||
// so we need a small delay to allow restart to preserve context
|
||||
setTimeout(() => {
|
||||
const context = this.taskExecutionContext.get(taskId);
|
||||
if (!context) return; // Already cleaned up or restarted
|
||||
|
||||
// If task completed successfully, always clean up
|
||||
if (code === 0) {
|
||||
this.taskExecutionContext.delete(taskId);
|
||||
return;
|
||||
}
|
||||
|
||||
// If task failed and hit max retries, clean up
|
||||
if (context.swapCount >= 2) {
|
||||
this.taskExecutionContext.delete(taskId);
|
||||
}
|
||||
// Otherwise keep context for potential restart
|
||||
}, 1000); // Delay to allow restart logic to run first
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -58,7 +96,7 @@ export class AgentManager extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
const specRunnerPath = path.join(autoBuildSource, 'spec_runner.py');
|
||||
const specRunnerPath = path.join(autoBuildSource, 'runners', 'spec_runner.py');
|
||||
|
||||
if (!existsSync(specRunnerPath)) {
|
||||
this.emit('error', taskId, `Spec runner not found at: ${specRunnerPath}`);
|
||||
@@ -82,6 +120,9 @@ export class AgentManager extends EventEmitter {
|
||||
args.push('--auto-approve');
|
||||
}
|
||||
|
||||
// Store context for potential restart
|
||||
this.storeTaskContext(taskId, projectPath, '', {}, true, taskDescription, specDir, metadata);
|
||||
|
||||
// Note: This is spec-creation but it chains to task-execution via run.py
|
||||
this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution');
|
||||
}
|
||||
@@ -95,21 +136,16 @@ export class AgentManager extends EventEmitter {
|
||||
specId: string,
|
||||
options: TaskExecutionOptions = {}
|
||||
): void {
|
||||
console.log('[AgentManager] startTaskExecution called for:', taskId, specId);
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -125,10 +161,17 @@ export class AgentManager extends EventEmitter {
|
||||
// Force: When user starts a task from the UI, that IS their approval
|
||||
args.push('--force');
|
||||
|
||||
// Pass base branch if specified (ensures worktrees are created from the correct branch)
|
||||
if (options.baseBranch) {
|
||||
args.push('--base-branch', options.baseBranch);
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
console.log('[AgentManager] Spawning process with args:', args);
|
||||
// Store context for potential restart
|
||||
this.storeTaskContext(taskId, projectPath, specId, options, false);
|
||||
|
||||
this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution');
|
||||
}
|
||||
|
||||
@@ -227,4 +270,77 @@ export class AgentManager extends EventEmitter {
|
||||
getRunningTasks(): string[] {
|
||||
return this.state.getRunningTaskIds();
|
||||
}
|
||||
|
||||
/**
|
||||
* Store task execution context for potential restarts
|
||||
*/
|
||||
private storeTaskContext(
|
||||
taskId: string,
|
||||
projectPath: string,
|
||||
specId: string,
|
||||
options: TaskExecutionOptions,
|
||||
isSpecCreation?: boolean,
|
||||
taskDescription?: string,
|
||||
specDir?: string,
|
||||
metadata?: SpecCreationMetadata
|
||||
): void {
|
||||
// Preserve swapCount if context already exists (for restarts)
|
||||
const existingContext = this.taskExecutionContext.get(taskId);
|
||||
const swapCount = existingContext?.swapCount ?? 0;
|
||||
|
||||
this.taskExecutionContext.set(taskId, {
|
||||
projectPath,
|
||||
specId,
|
||||
options,
|
||||
isSpecCreation,
|
||||
taskDescription,
|
||||
specDir,
|
||||
metadata,
|
||||
swapCount // Preserve existing count instead of resetting
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Restart task after profile swap
|
||||
*/
|
||||
restartTask(taskId: string): boolean {
|
||||
const context = this.taskExecutionContext.get(taskId);
|
||||
if (!context) {
|
||||
console.error('[AgentManager] No context for task:', taskId);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Prevent infinite swap loops
|
||||
if (context.swapCount >= 2) {
|
||||
console.error('[AgentManager] Max swap count reached for task:', taskId);
|
||||
return false;
|
||||
}
|
||||
|
||||
context.swapCount++;
|
||||
|
||||
// Kill current process
|
||||
this.killTask(taskId);
|
||||
|
||||
// Wait for cleanup, then restart
|
||||
setTimeout(() => {
|
||||
if (context.isSpecCreation) {
|
||||
this.startSpecCreation(
|
||||
taskId,
|
||||
context.projectPath,
|
||||
context.taskDescription!,
|
||||
context.specDir,
|
||||
context.metadata
|
||||
);
|
||||
} else {
|
||||
this.startTaskExecution(
|
||||
taskId,
|
||||
context.projectPath,
|
||||
context.specId,
|
||||
context.options
|
||||
);
|
||||
}
|
||||
}, 500);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
@@ -8,6 +8,7 @@ import { AgentEvents } from './agent-events';
|
||||
import { ProcessType, ExecutionProgressData } from './types';
|
||||
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from '../rate-limit-detector';
|
||||
import { projectStore } from '../project-store';
|
||||
import { getClaudeProfileManager } from '../claude-profile-manager';
|
||||
|
||||
/**
|
||||
* Process spawning and lifecycle management
|
||||
@@ -64,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;
|
||||
}
|
||||
}
|
||||
@@ -98,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 {};
|
||||
}
|
||||
|
||||
@@ -159,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();
|
||||
|
||||
@@ -173,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,
|
||||
@@ -238,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);
|
||||
@@ -258,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;
|
||||
}
|
||||
@@ -273,17 +263,39 @@ 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();
|
||||
|
||||
// Determine source type based on processType
|
||||
if (autoSwitchSettings.enabled && autoSwitchSettings.autoSwitchOnRateLimit) {
|
||||
const currentProfileId = rateLimitDetection.profileId;
|
||||
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
|
||||
|
||||
if (bestProfile) {
|
||||
// Switch active profile
|
||||
profileManager.setActiveProfile(bestProfile.id);
|
||||
|
||||
// Emit swap info (for modal)
|
||||
const source = processType === 'spec-creation' ? 'task' : 'task';
|
||||
const rateLimitInfo = createSDKRateLimitInfo(source, rateLimitDetection, {
|
||||
taskId
|
||||
});
|
||||
rateLimitInfo.wasAutoSwapped = true;
|
||||
rateLimitInfo.swappedToProfile = {
|
||||
id: bestProfile.id,
|
||||
name: bestProfile.name
|
||||
};
|
||||
rateLimitInfo.swapReason = 'reactive';
|
||||
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
|
||||
|
||||
// Restart task
|
||||
this.emitter.emit('auto-swap-restart-task', taskId, bestProfile.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to manual modal (no auto-swap or no alternative profile)
|
||||
const source = processType === 'spec-creation' ? 'task' : 'task';
|
||||
|
||||
// Emit rate limit event
|
||||
const rateLimitInfo = createSDKRateLimitInfo(source, rateLimitDetection, {
|
||||
taskId
|
||||
});
|
||||
@@ -305,7 +317,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, {
|
||||
|
||||
@@ -156,7 +156,9 @@ export class AgentQueueManager {
|
||||
...process.env,
|
||||
...combinedEnv,
|
||||
...profileEnv,
|
||||
PYTHONUNBUFFERED: '1'
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
}
|
||||
});
|
||||
|
||||
@@ -180,22 +182,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 +205,6 @@ export class AgentQueueManager {
|
||||
if (typeCompleteMatch) {
|
||||
const [, ideationType, ideasCount] = typeCompleteMatch;
|
||||
completedTypes.add(ideationType);
|
||||
console.log(`[Ideation] Type complete: ${ideationType} with ${ideasCount} ideas`);
|
||||
|
||||
// Emit event for UI to load this type's ideas immediately
|
||||
this.emitter.emit('ideation-type-complete', projectId, ideationType, parseInt(ideasCount, 10));
|
||||
@@ -217,7 +214,6 @@ export class AgentQueueManager {
|
||||
if (typeFailedMatch) {
|
||||
const [, ideationType] = typeFailedMatch;
|
||||
completedTypes.add(ideationType);
|
||||
console.log(`[Ideation] Type failed: ${ideationType}`);
|
||||
this.emitter.emit('ideation-type-failed', projectId, ideationType);
|
||||
}
|
||||
|
||||
@@ -242,9 +238,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,8 +254,6 @@ export class AgentQueueManager {
|
||||
|
||||
// Handle process exit
|
||||
childProcess.on('exit', (code: number | null) => {
|
||||
console.log('[Ideation] Process exited with code:', code);
|
||||
|
||||
// Get the stored project path before deleting from map
|
||||
const processInfo = this.state.getProcess(projectId);
|
||||
const storedProjectPath = processInfo?.projectPath;
|
||||
@@ -295,7 +289,6 @@ export class AgentQueueManager {
|
||||
if (existsSync(ideationFilePath)) {
|
||||
const content = readFileSync(ideationFilePath, 'utf-8');
|
||||
const session = JSON.parse(content);
|
||||
console.log('[Ideation] Emitting ideation-complete with session data');
|
||||
this.emitter.emit('ideation-complete', projectId, session);
|
||||
} else {
|
||||
console.warn('[Ideation] ideation.json not found at:', ideationFilePath);
|
||||
@@ -344,17 +337,15 @@ export class AgentQueueManager {
|
||||
// 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);
|
||||
|
||||
const childProcess = spawn(pythonPath, args, {
|
||||
cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...combinedEnv,
|
||||
...profileEnv,
|
||||
PYTHONUNBUFFERED: '1'
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
}
|
||||
});
|
||||
|
||||
@@ -378,15 +369,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 +396,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,8 +412,6 @@ export class AgentQueueManager {
|
||||
|
||||
// Handle process exit
|
||||
childProcess.on('exit', (code: number | null) => {
|
||||
console.log('[Roadmap] Process exited with code:', code);
|
||||
|
||||
// Get the stored project path before deleting from map
|
||||
const processInfo = this.state.getProcess(projectId);
|
||||
const storedProjectPath = processInfo?.projectPath;
|
||||
@@ -441,7 +429,6 @@ export class AgentQueueManager {
|
||||
}
|
||||
|
||||
if (code === 0) {
|
||||
console.log('[Roadmap] Roadmap generation completed successfully');
|
||||
this.emitter.emit('roadmap-progress', projectId, {
|
||||
phase: 'complete',
|
||||
progress: 100,
|
||||
@@ -460,7 +447,6 @@ export class AgentQueueManager {
|
||||
if (existsSync(roadmapFilePath)) {
|
||||
const content = readFileSync(roadmapFilePath, 'utf-8');
|
||||
const roadmap = JSON.parse(content);
|
||||
console.log('[Roadmap] Emitting roadmap-complete with roadmap data');
|
||||
this.emitter.emit('roadmap-complete', projectId, roadmap);
|
||||
} else {
|
||||
console.warn('[Roadmap] roadmap.json not found at:', roadmapFilePath);
|
||||
@@ -470,7 +456,6 @@ export class AgentQueueManager {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error('[Roadmap] Roadmap generation failed with exit code:', code);
|
||||
this.emitter.emit('roadmap-error', projectId, `Roadmap generation failed with exit code ${code}`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -40,6 +40,7 @@ export interface IdeationConfig {
|
||||
export interface TaskExecutionOptions {
|
||||
parallel?: boolean;
|
||||
workers?: number;
|
||||
baseBranch?: string;
|
||||
}
|
||||
|
||||
export interface SpecCreationMetadata {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import type {
|
||||
GitTagInfo
|
||||
} from '../../shared/types';
|
||||
import { ChangelogGenerator } from './generator';
|
||||
import { VersionSuggester } from './version-suggester';
|
||||
import { parseExistingChangelog } from './parser';
|
||||
import {
|
||||
getBranches,
|
||||
@@ -38,6 +39,7 @@ export class ChangelogService extends EventEmitter {
|
||||
private cachedEnv: Record<string, string> | null = null;
|
||||
private debugEnabled: boolean | null = null;
|
||||
private generator: ChangelogGenerator | null = null;
|
||||
private versionSuggester: VersionSuggester | null = null;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
@@ -117,7 +119,7 @@ export class ChangelogService extends EventEmitter {
|
||||
*/
|
||||
private debug(...args: unknown[]): void {
|
||||
if (this.isDebugEnabled()) {
|
||||
console.log('[ChangelogService]', ...args);
|
||||
console.warn('[ChangelogService]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,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;
|
||||
}
|
||||
}
|
||||
@@ -240,6 +243,32 @@ export class ChangelogService extends EventEmitter {
|
||||
return this.generator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create the version suggester instance
|
||||
*/
|
||||
private getVersionSuggester(): VersionSuggester {
|
||||
if (!this.versionSuggester) {
|
||||
const autoBuildSource = this.getAutoBuildSourcePath();
|
||||
if (!autoBuildSource) {
|
||||
throw new Error('Auto-build source path not found');
|
||||
}
|
||||
|
||||
// Verify claude CLI is available
|
||||
if (this.claudePath !== 'claude' && !existsSync(this.claudePath)) {
|
||||
throw new Error(`Claude CLI not found. Please ensure Claude Code is installed. Looked for: ${this.claudePath}`);
|
||||
}
|
||||
|
||||
this.versionSuggester = new VersionSuggester(
|
||||
this.pythonPath,
|
||||
this.claudePath,
|
||||
autoBuildSource,
|
||||
this.isDebugEnabled()
|
||||
);
|
||||
}
|
||||
|
||||
return this.versionSuggester;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Task Management
|
||||
// ============================================
|
||||
@@ -432,7 +461,7 @@ export class ChangelogService extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggest next version based on task types
|
||||
* Suggest next version based on task types (rule-based)
|
||||
*/
|
||||
suggestVersion(specs: TaskSpecContent[], currentVersion?: string): string {
|
||||
// Default starting version
|
||||
@@ -445,7 +474,7 @@ export class ChangelogService extends EventEmitter {
|
||||
return '1.0.0';
|
||||
}
|
||||
|
||||
let [major, minor, patch] = parts;
|
||||
const [major, minor, patch] = parts;
|
||||
|
||||
// Analyze specs for version increment decision
|
||||
let hasBreakingChanges = false;
|
||||
@@ -473,6 +502,46 @@ export class ChangelogService extends EventEmitter {
|
||||
return `${major}.${minor}.${patch + 1}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggest version using AI analysis of git commits
|
||||
*/
|
||||
async suggestVersionFromCommits(
|
||||
projectPath: string,
|
||||
commits: import('../../shared/types').GitCommit[],
|
||||
currentVersion?: string
|
||||
): Promise<{ version: string; reason: string }> {
|
||||
try {
|
||||
// Default starting version
|
||||
if (!currentVersion) {
|
||||
return { version: '1.0.0', reason: 'Initial version' };
|
||||
}
|
||||
|
||||
const parts = currentVersion.split('.').map(Number);
|
||||
if (parts.length !== 3 || parts.some(isNaN)) {
|
||||
return { version: '1.0.0', reason: 'Invalid current version, resetting to 1.0.0' };
|
||||
}
|
||||
|
||||
// Use AI to analyze commits and suggest version bump
|
||||
const suggester = this.getVersionSuggester();
|
||||
const suggestion = await suggester.suggestVersionBump(commits, currentVersion);
|
||||
|
||||
this.debug('AI version suggestion', suggestion);
|
||||
|
||||
return {
|
||||
version: suggestion.version,
|
||||
reason: suggestion.reason
|
||||
};
|
||||
} catch (error) {
|
||||
this.debug('Error in AI version suggestion, falling back to patch bump', error);
|
||||
// Fallback to patch bump if AI fails
|
||||
const [major, minor, patch] = (currentVersion || '1.0.0').split('.').map(Number);
|
||||
return {
|
||||
version: `${major}.${minor}.${patch + 1}`,
|
||||
reason: 'Patch version bump (AI analysis failed)'
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton instance
|
||||
|
||||
@@ -31,7 +31,7 @@ const FORMAT_TEMPLATES = {
|
||||
**Bug Fixes:**
|
||||
- [List fixes]`,
|
||||
|
||||
'github-release': (version: string) => `## What's New in v${version}
|
||||
'github-release': (version: string, date: string) => `## ${version} - ${date}
|
||||
|
||||
### New Features
|
||||
|
||||
@@ -160,11 +160,32 @@ export function buildChangelogPrompt(
|
||||
return parts.join('');
|
||||
}).join('\n');
|
||||
|
||||
// Format-specific instructions for tasks mode
|
||||
let formatSpecificInstructions = '';
|
||||
if (request.format === 'github-release') {
|
||||
formatSpecificInstructions = `
|
||||
For GitHub Release format:
|
||||
|
||||
RELEASE TITLE (CRITICAL):
|
||||
- First, analyze all completed tasks to identify the main theme or focus of this release
|
||||
- Create a concise, descriptive title (2-5 words) that captures what this release is about
|
||||
- Examples of good titles:
|
||||
* "Improved Terminal Experience" (for terminal-related improvements)
|
||||
* "Enhanced Security Features" (for security updates)
|
||||
* "UI/UX Refinements" (for interface changes)
|
||||
* "Agent Performance Boost" (for performance improvements)
|
||||
- The version header MUST be: "## ${request.version} - [Your Thematic Title]"
|
||||
- Focus on the USER BENEFIT or FUNCTIONAL AREA, not technical implementation details
|
||||
- The title should be what the release is "about" in layman's terms
|
||||
`;
|
||||
}
|
||||
|
||||
return `${audienceInstruction}
|
||||
|
||||
Format:
|
||||
${formatInstruction}
|
||||
${emojiInstruction ? `\nEmoji Usage:\n${emojiInstruction}` : ''}
|
||||
${formatSpecificInstructions}
|
||||
|
||||
Completed tasks:
|
||||
${taskSummaries}
|
||||
@@ -223,9 +244,23 @@ export function buildGitPrompt(
|
||||
let formatSpecificInstructions = '';
|
||||
if (request.format === 'github-release') {
|
||||
formatSpecificInstructions = `
|
||||
For GitHub Release format, create TWO parts:
|
||||
For GitHub Release format, you MUST follow this structure:
|
||||
|
||||
PART 1 - "What's New" (summarized changes):
|
||||
RELEASE TITLE (CRITICAL):
|
||||
- First, analyze all commits to identify the main theme or focus of this release
|
||||
- Create a concise, descriptive title (2-5 words) that captures what this release is about
|
||||
- Examples of good titles:
|
||||
* "Improved Terminal Experience" (for terminal-related improvements)
|
||||
* "Enhanced Security Features" (for security updates)
|
||||
* "Performance Optimizations" (for speed improvements)
|
||||
* "UI/UX Refinements" (for interface changes)
|
||||
* "Agent System Overhaul" (for major architectural changes)
|
||||
* "Build Pipeline Enhancements" (for CI/CD improvements)
|
||||
- The version header MUST be: "## ${request.version} - [Your Thematic Title]"
|
||||
- Focus on the USER BENEFIT or FUNCTIONAL AREA, not technical implementation details
|
||||
- The title should be what the release is "about" in layman's terms
|
||||
|
||||
PART 1 - Categorized changes (summarized):
|
||||
- Use category sections: New Features, Improvements, Bug Fixes, Documentation, Other Changes
|
||||
- ONLY include sections that have actual changes - skip empty sections entirely
|
||||
- Add a blank line between each bullet point for cleaner formatting
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* Architecture:
|
||||
* - changelog-service.ts: Main service facade (orchestrates all operations)
|
||||
* - generator.ts: AI-powered changelog generation
|
||||
* - version-suggester.ts: AI-powered version bump suggestions
|
||||
* - parser.ts: Changelog and spec parsing logic
|
||||
* - formatter.ts: Prompt building and formatting
|
||||
* - git-integration.ts: Git operations (branches, tags, commits)
|
||||
@@ -12,6 +13,7 @@
|
||||
|
||||
export { ChangelogService, changelogService } from './changelog-service';
|
||||
export { ChangelogGenerator } from './generator';
|
||||
export { VersionSuggester } from './version-suggester';
|
||||
export * from './parser';
|
||||
export * from './formatter';
|
||||
export * from './git-integration';
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
import { spawn } from 'child_process';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import type { GitCommit } from '../../shared/types';
|
||||
import { getProfileEnv } from '../rate-limit-detector';
|
||||
|
||||
interface VersionSuggestion {
|
||||
version: string;
|
||||
reason: string;
|
||||
bumpType: 'major' | 'minor' | 'patch';
|
||||
}
|
||||
|
||||
/**
|
||||
* AI-powered version bump suggester using Claude SDK with haiku model
|
||||
* Analyzes commits to intelligently suggest semantic version bumps
|
||||
*/
|
||||
export class VersionSuggester {
|
||||
private debugEnabled: boolean;
|
||||
|
||||
constructor(
|
||||
private pythonPath: string,
|
||||
private claudePath: string,
|
||||
private autoBuildSourcePath: string,
|
||||
debugEnabled: boolean
|
||||
) {
|
||||
this.debugEnabled = debugEnabled;
|
||||
}
|
||||
|
||||
private debug(...args: unknown[]): void {
|
||||
if (this.debugEnabled) {
|
||||
console.warn('[VersionSuggester]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggest version bump using AI analysis of commits
|
||||
*/
|
||||
async suggestVersionBump(
|
||||
commits: GitCommit[],
|
||||
currentVersion: string
|
||||
): Promise<VersionSuggestion> {
|
||||
this.debug('suggestVersionBump called', {
|
||||
commitCount: commits.length,
|
||||
currentVersion
|
||||
});
|
||||
|
||||
// Build prompt for Claude to analyze commits
|
||||
const prompt = this.buildPrompt(commits, currentVersion);
|
||||
const script = this.createAnalysisScript(prompt);
|
||||
|
||||
// Build environment
|
||||
const spawnEnv = this.buildSpawnEnvironment();
|
||||
|
||||
return new Promise((resolve, _reject) => {
|
||||
const childProcess = spawn(this.pythonPath, ['-c', script], {
|
||||
cwd: this.autoBuildSourcePath,
|
||||
env: spawnEnv
|
||||
});
|
||||
|
||||
let output = '';
|
||||
let errorOutput = '';
|
||||
|
||||
childProcess.stdout?.on('data', (data: Buffer) => {
|
||||
output += data.toString();
|
||||
});
|
||||
|
||||
childProcess.stderr?.on('data', (data: Buffer) => {
|
||||
errorOutput += data.toString();
|
||||
});
|
||||
|
||||
childProcess.on('exit', (code: number | null) => {
|
||||
if (code === 0 && output.trim()) {
|
||||
try {
|
||||
const result = this.parseAIResponse(output.trim(), currentVersion);
|
||||
this.debug('AI suggestion parsed', result);
|
||||
resolve(result);
|
||||
} catch (error) {
|
||||
this.debug('Failed to parse AI response', error);
|
||||
// Fallback to simple bump
|
||||
resolve(this.fallbackSuggestion(currentVersion));
|
||||
}
|
||||
} else {
|
||||
this.debug('AI analysis failed', { code, error: errorOutput });
|
||||
// Fallback to simple bump
|
||||
resolve(this.fallbackSuggestion(currentVersion));
|
||||
}
|
||||
});
|
||||
|
||||
childProcess.on('error', (err: Error) => {
|
||||
this.debug('Process error', err);
|
||||
resolve(this.fallbackSuggestion(currentVersion));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Build prompt for Claude to analyze commits and suggest version bump
|
||||
*/
|
||||
private buildPrompt(commits: GitCommit[], currentVersion: string): string {
|
||||
const commitSummary = commits
|
||||
.map((c, i) => `${i + 1}. ${c.hash} - ${c.subject}`)
|
||||
.join('\n');
|
||||
|
||||
return `You are a semantic versioning expert analyzing git commits to suggest the appropriate version bump.
|
||||
|
||||
Current version: ${currentVersion}
|
||||
|
||||
Analyze these ${commits.length} commits and determine the appropriate semantic version bump:
|
||||
|
||||
${commitSummary}
|
||||
|
||||
Consider:
|
||||
- MAJOR (X.0.0): Breaking changes, API changes, removed features, architectural changes
|
||||
- MINOR (0.X.0): New features, enhancements, additions that maintain backward compatibility
|
||||
- PATCH (0.0.X): Bug fixes, small tweaks, documentation updates, refactoring without new features
|
||||
|
||||
Respond with ONLY a JSON object in this exact format (no markdown, no extra text):
|
||||
{
|
||||
"bumpType": "major|minor|patch",
|
||||
"reason": "Brief explanation of the decision"
|
||||
}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create Python script to run Claude analysis
|
||||
*/
|
||||
private createAnalysisScript(prompt: string): string {
|
||||
// Escape the prompt for Python string literal
|
||||
const escapedPrompt = prompt
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/"/g, '\\"')
|
||||
.replace(/\n/g, '\\n');
|
||||
|
||||
return `
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
# Use haiku model for fast, cost-effective analysis
|
||||
prompt = "${escapedPrompt}"
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["${this.claudePath}", "chat", "--model", "haiku", "--prompt", prompt],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True
|
||||
)
|
||||
print(result.stdout)
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"Error: {e.stderr}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"Error: {str(e)}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse AI response to extract version suggestion
|
||||
*/
|
||||
private parseAIResponse(output: string, currentVersion: string): VersionSuggestion {
|
||||
// Extract JSON from output (Claude might wrap it in markdown or other text)
|
||||
const jsonMatch = output.match(/\{[\s\S]*"bumpType"[\s\S]*"reason"[\s\S]*\}/);
|
||||
if (!jsonMatch) {
|
||||
throw new Error('No JSON found in AI response');
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(jsonMatch[0]);
|
||||
const bumpType = parsed.bumpType as 'major' | 'minor' | 'patch';
|
||||
const reason = parsed.reason || 'AI analysis of commits';
|
||||
|
||||
// Calculate new version
|
||||
const [major, minor, patch] = currentVersion.split('.').map(Number);
|
||||
|
||||
let newVersion: string;
|
||||
switch (bumpType) {
|
||||
case 'major':
|
||||
newVersion = `${major + 1}.0.0`;
|
||||
break;
|
||||
case 'minor':
|
||||
newVersion = `${major}.${minor + 1}.0`;
|
||||
break;
|
||||
case 'patch':
|
||||
default:
|
||||
newVersion = `${major}.${minor}.${patch + 1}`;
|
||||
break;
|
||||
}
|
||||
|
||||
return {
|
||||
version: newVersion,
|
||||
reason,
|
||||
bumpType
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback suggestion if AI analysis fails
|
||||
*/
|
||||
private fallbackSuggestion(currentVersion: string): VersionSuggestion {
|
||||
const [major, minor, patch] = currentVersion.split('.').map(Number);
|
||||
return {
|
||||
version: `${major}.${minor}.${patch + 1}`,
|
||||
reason: 'Patch version bump (default)',
|
||||
bumpType: 'patch'
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build spawn environment with proper PATH and auth settings
|
||||
*/
|
||||
private buildSpawnEnvironment(): Record<string, string> {
|
||||
const homeDir = os.homedir();
|
||||
const isWindows = process.platform === 'win32';
|
||||
|
||||
// Build PATH with platform-appropriate separator and locations
|
||||
const pathAdditions = isWindows
|
||||
? [
|
||||
path.join(homeDir, 'AppData', 'Local', 'Programs', 'claude'),
|
||||
path.join(homeDir, 'AppData', 'Roaming', 'npm'),
|
||||
path.join(homeDir, '.local', 'bin'),
|
||||
'C:\\Program Files\\Claude',
|
||||
'C:\\Program Files (x86)\\Claude'
|
||||
]
|
||||
: [
|
||||
'/usr/local/bin',
|
||||
'/opt/homebrew/bin',
|
||||
path.join(homeDir, '.local', 'bin'),
|
||||
path.join(homeDir, 'bin')
|
||||
];
|
||||
|
||||
// Get active Claude profile environment
|
||||
const profileEnv = getProfileEnv();
|
||||
|
||||
const spawnEnv: Record<string, string> = {
|
||||
...process.env as Record<string, string>,
|
||||
...profileEnv,
|
||||
...(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',
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -51,3 +51,6 @@ export {
|
||||
hasValidToken,
|
||||
expandHomePath
|
||||
} from './profile-utils';
|
||||
|
||||
// Usage monitoring (proactive account switching)
|
||||
export { UsageMonitor, getUsageMonitor } from './usage-monitor';
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -13,10 +13,11 @@ export const STORE_VERSION = 3; // Bumped for encrypted token storage
|
||||
*/
|
||||
export const DEFAULT_AUTO_SWITCH_SETTINGS: ClaudeAutoSwitchSettings = {
|
||||
enabled: false,
|
||||
sessionThreshold: 85, // Consider switching at 85% session usage
|
||||
weeklyThreshold: 90, // Consider switching at 90% weekly usage
|
||||
proactiveSwapEnabled: false, // Proactive monitoring disabled by default
|
||||
sessionThreshold: 95, // Consider switching at 95% session usage
|
||||
weeklyThreshold: 99, // Consider switching at 99% weekly usage
|
||||
autoSwitchOnRateLimit: false, // Prompt user by default
|
||||
usageCheckInterval: 0 // Disabled by default (in ms, e.g., 300000 = 5 min)
|
||||
usageCheckInterval: 30000 // Check every 30s when enabled (0 = disabled)
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
/**
|
||||
* Usage Monitor - Proactive usage monitoring and account switching
|
||||
*
|
||||
* Monitors Claude account usage at configured intervals and automatically
|
||||
* switches to alternative accounts before hitting rate limits.
|
||||
*
|
||||
* Uses hybrid approach:
|
||||
* 1. Primary: Direct OAuth API (https://api.anthropic.com/api/oauth/usage)
|
||||
* 2. Fallback: CLI /usage command parsing
|
||||
*/
|
||||
|
||||
import { EventEmitter } from 'events';
|
||||
import { getClaudeProfileManager } from '../claude-profile-manager';
|
||||
import { ClaudeUsageSnapshot } from '../../shared/types/agent';
|
||||
|
||||
export class UsageMonitor extends EventEmitter {
|
||||
private static instance: UsageMonitor;
|
||||
private intervalId: NodeJS.Timeout | null = null;
|
||||
private currentUsage: ClaudeUsageSnapshot | null = null;
|
||||
private isChecking = false;
|
||||
private useApiMethod = true; // Try API first, fall back to CLI if it fails
|
||||
|
||||
private constructor() {
|
||||
super();
|
||||
console.warn('[UsageMonitor] Initialized');
|
||||
}
|
||||
|
||||
static getInstance(): UsageMonitor {
|
||||
if (!UsageMonitor.instance) {
|
||||
UsageMonitor.instance = new UsageMonitor();
|
||||
}
|
||||
return UsageMonitor.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start monitoring usage at configured interval
|
||||
*/
|
||||
start(): void {
|
||||
const profileManager = getClaudeProfileManager();
|
||||
const settings = profileManager.getAutoSwitchSettings();
|
||||
|
||||
if (!settings.enabled || !settings.proactiveSwapEnabled) {
|
||||
console.warn('[UsageMonitor] Proactive monitoring disabled');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.intervalId) {
|
||||
console.warn('[UsageMonitor] Already running');
|
||||
return;
|
||||
}
|
||||
|
||||
const interval = settings.usageCheckInterval || 30000;
|
||||
console.warn('[UsageMonitor] Starting with interval:', interval, 'ms');
|
||||
|
||||
// Check immediately
|
||||
this.checkUsageAndSwap();
|
||||
|
||||
// Then check periodically
|
||||
this.intervalId = setInterval(() => {
|
||||
this.checkUsageAndSwap();
|
||||
}, interval);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop monitoring
|
||||
*/
|
||||
stop(): void {
|
||||
if (this.intervalId) {
|
||||
clearInterval(this.intervalId);
|
||||
this.intervalId = null;
|
||||
console.warn('[UsageMonitor] Stopped');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current usage snapshot (for UI indicator)
|
||||
*/
|
||||
getCurrentUsage(): ClaudeUsageSnapshot | null {
|
||||
return this.currentUsage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check usage and trigger swap if thresholds exceeded
|
||||
*/
|
||||
private async checkUsageAndSwap(): Promise<void> {
|
||||
if (this.isChecking) {
|
||||
return; // Prevent concurrent checks
|
||||
}
|
||||
|
||||
this.isChecking = true;
|
||||
|
||||
try {
|
||||
const profileManager = getClaudeProfileManager();
|
||||
const activeProfile = profileManager.getActiveProfile();
|
||||
|
||||
if (!activeProfile) {
|
||||
console.warn('[UsageMonitor] No active profile');
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch current usage (hybrid approach)
|
||||
const usage = await this.fetchUsage(activeProfile.id, activeProfile.oauthToken);
|
||||
if (!usage) {
|
||||
console.warn('[UsageMonitor] Failed to fetch usage');
|
||||
return;
|
||||
}
|
||||
|
||||
this.currentUsage = usage;
|
||||
|
||||
// Emit usage update for UI
|
||||
this.emit('usage-updated', usage);
|
||||
|
||||
// Check thresholds
|
||||
const settings = profileManager.getAutoSwitchSettings();
|
||||
const sessionExceeded = usage.sessionPercent >= settings.sessionThreshold;
|
||||
const weeklyExceeded = usage.weeklyPercent >= settings.weeklyThreshold;
|
||||
|
||||
if (sessionExceeded || weeklyExceeded) {
|
||||
console.warn('[UsageMonitor] Threshold exceeded:', {
|
||||
sessionPercent: usage.sessionPercent,
|
||||
sessionThreshold: settings.sessionThreshold,
|
||||
weeklyPercent: usage.weeklyPercent,
|
||||
weeklyThreshold: settings.weeklyThreshold
|
||||
});
|
||||
|
||||
// Attempt proactive swap
|
||||
await this.performProactiveSwap(
|
||||
activeProfile.id,
|
||||
sessionExceeded ? 'session' : 'weekly'
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[UsageMonitor] Check failed:', error);
|
||||
} finally {
|
||||
this.isChecking = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch usage - HYBRID APPROACH
|
||||
* Tries API first, falls back to CLI if API fails
|
||||
*/
|
||||
private async fetchUsage(
|
||||
profileId: string,
|
||||
oauthToken?: string
|
||||
): Promise<ClaudeUsageSnapshot | null> {
|
||||
const profileManager = getClaudeProfileManager();
|
||||
const profile = profileManager.getProfile(profileId);
|
||||
if (!profile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Attempt 1: Direct API call (preferred)
|
||||
if (this.useApiMethod && oauthToken) {
|
||||
const apiUsage = await this.fetchUsageViaAPI(oauthToken, profileId, profile.name);
|
||||
if (apiUsage) {
|
||||
console.warn('[UsageMonitor] Successfully fetched via API');
|
||||
return apiUsage;
|
||||
}
|
||||
|
||||
// API failed - switch to CLI method for future calls
|
||||
console.warn('[UsageMonitor] API method failed, falling back to CLI');
|
||||
this.useApiMethod = false;
|
||||
}
|
||||
|
||||
// Attempt 2: CLI /usage command (fallback)
|
||||
return await this.fetchUsageViaCLI(profileId, profile.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch usage via OAuth API endpoint
|
||||
* Endpoint: https://api.anthropic.com/api/oauth/usage
|
||||
*/
|
||||
private async fetchUsageViaAPI(
|
||||
oauthToken: string,
|
||||
profileId: string,
|
||||
profileName: string
|
||||
): Promise<ClaudeUsageSnapshot | null> {
|
||||
try {
|
||||
const response = await fetch('https://api.anthropic.com/api/oauth/usage', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${oauthToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'anthropic-version': '2023-06-01'
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('[UsageMonitor] API error:', response.status, response.statusText);
|
||||
return null;
|
||||
}
|
||||
|
||||
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:
|
||||
// {
|
||||
// "five_hour_utilization": 0.72, // 0.0-1.0
|
||||
// "seven_day_utilization": 0.45, // 0.0-1.0
|
||||
// "five_hour_reset_at": "2025-01-17T15:00:00Z",
|
||||
// "seven_day_reset_at": "2025-01-20T12:00:00Z"
|
||||
// }
|
||||
|
||||
return {
|
||||
sessionPercent: Math.round((data.five_hour_utilization || 0) * 100),
|
||||
weeklyPercent: Math.round((data.seven_day_utilization || 0) * 100),
|
||||
sessionResetTime: this.formatResetTime(data.five_hour_reset_at),
|
||||
weeklyResetTime: this.formatResetTime(data.seven_day_reset_at),
|
||||
profileId,
|
||||
profileName,
|
||||
fetchedAt: new Date(),
|
||||
limitType: (data.seven_day_utilization || 0) > (data.five_hour_utilization || 0)
|
||||
? 'weekly'
|
||||
: 'session'
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[UsageMonitor] API fetch failed:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch usage via CLI /usage command (fallback)
|
||||
* Note: This is a fallback method. The API method is preferred.
|
||||
* CLI-based fetching would require spawning a Claude process and parsing output,
|
||||
* which is complex. For now, we rely on the API method.
|
||||
*/
|
||||
private async fetchUsageViaCLI(
|
||||
_profileId: string,
|
||||
_profileName: string
|
||||
): Promise<ClaudeUsageSnapshot | null> {
|
||||
// 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.warn('[UsageMonitor] CLI fallback not implemented, API method should be used');
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format ISO timestamp to human-readable reset time
|
||||
*/
|
||||
private formatResetTime(isoTimestamp?: string): string {
|
||||
if (!isoTimestamp) return 'Unknown';
|
||||
|
||||
try {
|
||||
const date = new Date(isoTimestamp);
|
||||
const now = new Date();
|
||||
const diffMs = date.getTime() - now.getTime();
|
||||
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
|
||||
const diffMins = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
|
||||
|
||||
if (diffHours < 24) {
|
||||
return `${diffHours}h ${diffMins}m`;
|
||||
}
|
||||
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
const remainingHours = diffHours % 24;
|
||||
return `${diffDays}d ${remainingHours}h`;
|
||||
} catch (_error) {
|
||||
return isoTimestamp;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform proactive profile swap
|
||||
*/
|
||||
private async performProactiveSwap(
|
||||
currentProfileId: string,
|
||||
limitType: 'session' | 'weekly'
|
||||
): Promise<void> {
|
||||
const profileManager = getClaudeProfileManager();
|
||||
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
|
||||
|
||||
if (!bestProfile) {
|
||||
console.warn('[UsageMonitor] No alternative profile for proactive swap');
|
||||
this.emit('proactive-swap-failed', {
|
||||
reason: 'no_alternative',
|
||||
currentProfile: currentProfileId
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.warn('[UsageMonitor] Proactive swap:', {
|
||||
from: currentProfileId,
|
||||
to: bestProfile.id,
|
||||
reason: limitType
|
||||
});
|
||||
|
||||
// Switch profile
|
||||
profileManager.setActiveProfile(bestProfile.id);
|
||||
|
||||
// Emit swap event
|
||||
this.emit('proactive-swap-completed', {
|
||||
fromProfile: { id: currentProfileId, name: profileManager.getProfile(currentProfileId)?.name },
|
||||
toProfile: { id: bestProfile.id, name: bestProfile.name },
|
||||
limitType,
|
||||
timestamp: new Date()
|
||||
});
|
||||
|
||||
// Notify UI
|
||||
this.emit('show-swap-notification', {
|
||||
fromProfile: profileManager.getProfile(currentProfileId)?.name,
|
||||
toProfile: bestProfile.name,
|
||||
reason: 'proactive',
|
||||
limitType
|
||||
});
|
||||
|
||||
// Note: Don't immediately check new profile - let normal interval handle it
|
||||
// This prevents cascading swaps if multiple profiles are near limits
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the singleton UsageMonitor instance
|
||||
*/
|
||||
export function getUsageMonitor(): UsageMonitor {
|
||||
return UsageMonitor.getInstance();
|
||||
}
|
||||
@@ -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}`,
|
||||
|
||||
@@ -5,6 +5,9 @@ import { setupIpcHandlers } from './ipc-setup';
|
||||
import { AgentManager } from './agent';
|
||||
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 {
|
||||
@@ -19,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';
|
||||
}
|
||||
@@ -49,7 +52,8 @@ function createWindow(): void {
|
||||
preload: join(__dirname, '../preload/index.js'),
|
||||
sandbox: false,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false
|
||||
nodeIntegration: false,
|
||||
backgroundThrottling: false // Prevent terminal lag when window loses focus
|
||||
}
|
||||
});
|
||||
|
||||
@@ -125,6 +129,34 @@ app.whenReady().then(() => {
|
||||
// Create window
|
||||
createWindow();
|
||||
|
||||
// Initialize usage monitoring after window is created
|
||||
if (mainWindow) {
|
||||
// Setup event forwarding from usage monitor to renderer
|
||||
initializeUsageMonitorForwarding(mainWindow);
|
||||
|
||||
// Start the usage monitor
|
||||
const usageMonitor = getUsageMonitor();
|
||||
usageMonitor.start();
|
||||
console.warn('[main] Usage monitor initialized and started');
|
||||
|
||||
// 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
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
@@ -142,6 +174,11 @@ app.on('window-all-closed', () => {
|
||||
|
||||
// Cleanup before quit
|
||||
app.on('before-quit', async () => {
|
||||
// Stop usage monitor
|
||||
const usageMonitor = getUsageMonitor();
|
||||
usageMonitor.stop();
|
||||
console.warn('[main] Usage monitor stopped');
|
||||
|
||||
// Kill all running agent processes
|
||||
if (agentManager) {
|
||||
await agentManager.killAll();
|
||||
|
||||
@@ -2,10 +2,7 @@ import { EventEmitter } from 'events';
|
||||
import type {
|
||||
InsightsSession,
|
||||
InsightsSessionSummary,
|
||||
InsightsChatMessage,
|
||||
InsightsChatStatus,
|
||||
InsightsStreamChunk,
|
||||
InsightsToolUsage
|
||||
InsightsChatMessage
|
||||
} from '../shared/types';
|
||||
import { InsightsConfig } from './insights/config';
|
||||
import { InsightsPaths } from './insights/paths';
|
||||
|
||||
@@ -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'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,7 +251,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,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,
|
||||
@@ -210,6 +209,48 @@ export function registerChangelogHandlers(
|
||||
}
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.CHANGELOG_SUGGEST_VERSION_FROM_COMMITS,
|
||||
async (_, projectId: string, commits: GitCommit[]): Promise<IPCResult<{ version: string; reason: string }>> => {
|
||||
const project = projectStore.getProject(projectId);
|
||||
if (!project) {
|
||||
return { success: false, error: 'Project not found' };
|
||||
}
|
||||
|
||||
try {
|
||||
// Get current version from existing changelog or git tags
|
||||
const existing = changelogService.readExistingChangelog(project.path);
|
||||
let currentVersion = existing.lastVersion;
|
||||
|
||||
// If no version in changelog, try to get latest tag
|
||||
if (!currentVersion) {
|
||||
const tags = changelogService.getTags(project.path);
|
||||
if (tags.length > 0) {
|
||||
// Extract version from tag name (e.g., "v2.1.0" -> "2.1.0")
|
||||
currentVersion = tags[0].name.replace(/^v/, '');
|
||||
}
|
||||
}
|
||||
|
||||
// Use AI to analyze commits and suggest version
|
||||
const result = await changelogService.suggestVersionFromCommits(
|
||||
project.path,
|
||||
commits,
|
||||
currentVersion
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: result
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to suggest version from commits'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// ============================================
|
||||
// Changelog Git Operations
|
||||
// ============================================
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -14,9 +14,9 @@ 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}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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
|
||||
};
|
||||
|
||||
@@ -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
|
||||
@@ -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, `
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
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';
|
||||
@@ -22,32 +27,144 @@ import { insightsService } from '../insights-service';
|
||||
import { titleGenerator } from '../title-generator';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
|
||||
// ============================================
|
||||
// Git Helper Functions
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Get list of git branches for a directory
|
||||
*/
|
||||
function getGitBranches(projectPath: string): string[] {
|
||||
try {
|
||||
const result = execSync('git branch --list --format="%(refname:short)"', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
});
|
||||
return result.trim().split('\n').filter(b => b.trim());
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current git branch for a directory
|
||||
*/
|
||||
function getCurrentGitBranch(projectPath: string): string | null {
|
||||
try {
|
||||
const result = execSync('git rev-parse --abbrev-ref HEAD', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
});
|
||||
return result.trim() || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect the main branch for a git repository
|
||||
* Checks for common main branch names in order of preference
|
||||
*/
|
||||
function detectMainBranch(projectPath: string): string | null {
|
||||
const branches = getGitBranches(projectPath);
|
||||
if (branches.length === 0) return null;
|
||||
|
||||
// Check for common main branch names in order of preference
|
||||
const mainBranchCandidates = ['main', 'master', 'develop', 'dev', 'trunk'];
|
||||
for (const candidate of mainBranchCandidates) {
|
||||
if (branches.includes(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
// If none of the common names found, check for origin/HEAD reference
|
||||
try {
|
||||
const result = execSync('git symbolic-ref refs/remotes/origin/HEAD', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
});
|
||||
const ref = result.trim();
|
||||
// Extract branch name from refs/remotes/origin/main
|
||||
const match = ref.match(/refs\/remotes\/origin\/(.+)/);
|
||||
if (match && branches.includes(match[1])) {
|
||||
return match[1];
|
||||
}
|
||||
} catch {
|
||||
// origin/HEAD not set, continue with fallback
|
||||
}
|
||||
|
||||
// Fallback: return the first branch (usually the current one)
|
||||
return branches[0] || 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;
|
||||
};
|
||||
|
||||
@@ -80,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);
|
||||
@@ -96,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,
|
||||
@@ -106,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) {
|
||||
@@ -163,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 };
|
||||
}
|
||||
);
|
||||
@@ -215,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
|
||||
@@ -330,4 +447,103 @@ export function registerProjectHandlers(
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// ============================================
|
||||
// Git Operations
|
||||
// ============================================
|
||||
|
||||
// Get all branches for a project
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GIT_GET_BRANCHES,
|
||||
async (_, projectPath: string): Promise<IPCResult<string[]>> => {
|
||||
try {
|
||||
if (!existsSync(projectPath)) {
|
||||
return { success: false, error: 'Directory does not exist' };
|
||||
}
|
||||
const branches = getGitBranches(projectPath);
|
||||
return { success: true, data: branches };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Get current branch for a project
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GIT_GET_CURRENT_BRANCH,
|
||||
async (_, projectPath: string): Promise<IPCResult<string | null>> => {
|
||||
try {
|
||||
if (!existsSync(projectPath)) {
|
||||
return { success: false, error: 'Directory does not exist' };
|
||||
}
|
||||
const branch = getCurrentGitBranch(projectPath);
|
||||
return { success: true, data: branch };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Auto-detect main branch for a project
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GIT_DETECT_MAIN_BRANCH,
|
||||
async (_, projectPath: string): Promise<IPCResult<string | null>> => {
|
||||
try {
|
||||
if (!existsSync(projectPath)) {
|
||||
return { success: false, error: 'Directory does not exist' };
|
||||
}
|
||||
const mainBranch = detectMainBranch(projectPath);
|
||||
return { success: true, data: mainBranch };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// 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,7 +5,6 @@ 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';
|
||||
|
||||
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { ipcMain } from 'electron';
|
||||
import { IPC_CHANNELS } from '../../../shared/constants';
|
||||
import type { IPCResult } from '../../../shared/types';
|
||||
import { projectStore } from '../../project-store';
|
||||
|
||||
/**
|
||||
* Register task archive handlers
|
||||
*/
|
||||
export function registerTaskArchiveHandlers(): void {
|
||||
/**
|
||||
* Archive tasks
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.TASK_ARCHIVE,
|
||||
async (
|
||||
_,
|
||||
projectId: string,
|
||||
taskIds: string[],
|
||||
version?: string
|
||||
): Promise<IPCResult<boolean>> => {
|
||||
console.warn('[IPC] TASK_ARCHIVE called with projectId:', projectId, 'taskIds:', taskIds);
|
||||
|
||||
const result = projectStore.archiveTasks(projectId, taskIds, version);
|
||||
|
||||
if (result) {
|
||||
console.warn('[IPC] TASK_ARCHIVE success');
|
||||
return { success: true, data: true };
|
||||
} else {
|
||||
console.error('[IPC] TASK_ARCHIVE failed');
|
||||
return { success: false, error: 'Failed to archive tasks' };
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Unarchive tasks
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.TASK_UNARCHIVE,
|
||||
async (_, projectId: string, taskIds: string[]): Promise<IPCResult<boolean>> => {
|
||||
console.warn('[IPC] TASK_UNARCHIVE called with projectId:', projectId, 'taskIds:', taskIds);
|
||||
|
||||
const result = projectStore.unarchiveTasks(projectId, taskIds);
|
||||
|
||||
if (result) {
|
||||
console.warn('[IPC] TASK_UNARCHIVE success');
|
||||
return { success: true, data: true };
|
||||
} else {
|
||||
console.error('[IPC] TASK_UNARCHIVE failed');
|
||||
return { success: false, error: 'Failed to unarchive tasks' };
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ipcMain } from 'electron';
|
||||
import { IPC_CHANNELS, AUTO_BUILD_PATHS, getSpecsDir } from '../../../shared/constants';
|
||||
import type { IPCResult, Task, TaskMetadata, Project } from '../../../shared/types';
|
||||
import type { IPCResult, Task, TaskMetadata } from '../../../shared/types';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync, writeFileSync, readdirSync, mkdirSync } from 'fs';
|
||||
import { projectStore } from '../../project-store';
|
||||
@@ -18,9 +18,9 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.TASK_LIST,
|
||||
async (_, projectId: string): Promise<IPCResult<Task[]>> => {
|
||||
console.log('[IPC] TASK_LIST called with projectId:', projectId);
|
||||
console.warn('[IPC] TASK_LIST called with projectId:', projectId);
|
||||
const tasks = projectStore.getTasks(projectId);
|
||||
console.log('[IPC] TASK_LIST returning', tasks.length, 'tasks');
|
||||
console.warn('[IPC] TASK_LIST returning', tasks.length, 'tasks');
|
||||
return { success: true, data: tasks };
|
||||
}
|
||||
);
|
||||
@@ -45,17 +45,17 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
|
||||
// Auto-generate title if empty using Claude AI
|
||||
let finalTitle = title;
|
||||
if (!title || !title.trim()) {
|
||||
console.log('[TASK_CREATE] Title is empty, generating with Claude AI...');
|
||||
console.warn('[TASK_CREATE] Title is empty, generating with Claude AI...');
|
||||
try {
|
||||
const generatedTitle = await titleGenerator.generateTitle(description);
|
||||
if (generatedTitle) {
|
||||
finalTitle = generatedTitle;
|
||||
console.log('[TASK_CREATE] Generated title:', finalTitle);
|
||||
console.warn('[TASK_CREATE] Generated title:', finalTitle);
|
||||
} else {
|
||||
// Fallback: create title from first line of description
|
||||
finalTitle = description.split('\n')[0].substring(0, 60);
|
||||
if (finalTitle.length === 60) finalTitle += '...';
|
||||
console.log('[TASK_CREATE] AI generation failed, using fallback:', finalTitle);
|
||||
console.warn('[TASK_CREATE] AI generation failed, using fallback:', finalTitle);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[TASK_CREATE] Title generation error:', err);
|
||||
@@ -226,7 +226,7 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
|
||||
try {
|
||||
if (existsSync(specDir)) {
|
||||
await rm(specDir, { recursive: true, force: true });
|
||||
console.log(`[TASK_DELETE] Deleted spec directory: ${specDir}`);
|
||||
console.warn(`[TASK_DELETE] Deleted spec directory: ${specDir}`);
|
||||
}
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
@@ -269,17 +269,17 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
|
||||
if (updates.title !== undefined && !updates.title.trim()) {
|
||||
// Get description to use for title generation
|
||||
const descriptionToUse = updates.description ?? task.description;
|
||||
console.log('[TASK_UPDATE] Title is empty, generating with Claude AI...');
|
||||
console.warn('[TASK_UPDATE] Title is empty, generating with Claude AI...');
|
||||
try {
|
||||
const generatedTitle = await titleGenerator.generateTitle(descriptionToUse);
|
||||
if (generatedTitle) {
|
||||
finalTitle = generatedTitle;
|
||||
console.log('[TASK_UPDATE] Generated title:', finalTitle);
|
||||
console.warn('[TASK_UPDATE] Generated title:', finalTitle);
|
||||
} else {
|
||||
// Fallback: create title from first line of description
|
||||
finalTitle = descriptionToUse.split('\n')[0].substring(0, 60);
|
||||
if (finalTitle.length === 60) finalTitle += '...';
|
||||
console.log('[TASK_UPDATE] AI generation failed, using fallback:', finalTitle);
|
||||
console.warn('[TASK_UPDATE] AI generation failed, using fallback:', finalTitle);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[TASK_UPDATE] Title generation error:', err);
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { ipcMain, BrowserWindow } from 'electron';
|
||||
import { IPC_CHANNELS, AUTO_BUILD_PATHS, getSpecsDir } from '../../../shared/constants';
|
||||
import type { IPCResult, Task, TaskStartOptions, TaskStatus } from '../../../shared/types';
|
||||
import type { IPCResult, TaskStartOptions, TaskStatus } from '../../../shared/types';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
|
||||
import { AgentManager } from '../../agent';
|
||||
import { fileWatcher } from '../../file-watcher';
|
||||
import { findTaskAndProject } from './shared';
|
||||
import { checkGitStatus } from '../../project-initializer';
|
||||
|
||||
/**
|
||||
* Register task execution handlers (start, stop, review, status management, recovery)
|
||||
@@ -19,11 +20,11 @@ export function registerTaskExecutionHandlers(
|
||||
*/
|
||||
ipcMain.on(
|
||||
IPC_CHANNELS.TASK_START,
|
||||
(_, taskId: string, options?: TaskStartOptions) => {
|
||||
console.log('[TASK_START] Received request for taskId:', taskId);
|
||||
(_, taskId: string, _options?: TaskStartOptions) => {
|
||||
console.warn('[TASK_START] Received request for taskId:', taskId);
|
||||
const mainWindow = getMainWindow();
|
||||
if (!mainWindow) {
|
||||
console.log('[TASK_START] No main window found');
|
||||
console.warn('[TASK_START] No main window found');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -31,7 +32,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 +41,28 @@ 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;
|
||||
}
|
||||
|
||||
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,12 +82,15 @@ 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;
|
||||
|
||||
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
|
||||
@@ -73,14 +98,14 @@ export function registerTaskExecutionHandlers(
|
||||
} else if (needsImplementation) {
|
||||
// Spec exists but no subtasks - run run.py to create implementation plan and execute
|
||||
// Read the spec.md to get the task description
|
||||
let taskDescription = task.description || task.title;
|
||||
const _taskDescription = task.description || task.title;
|
||||
try {
|
||||
taskDescription = readFileSync(specFilePath, 'utf-8');
|
||||
readFileSync(specFilePath, 'utf-8');
|
||||
} catch {
|
||||
// Use default description
|
||||
}
|
||||
|
||||
console.log('[TASK_START] Starting task execution (no subtasks) for:', task.specId);
|
||||
console.warn('[TASK_START] Starting task execution (no subtasks) for:', task.specId);
|
||||
// Start task execution which will create the implementation plan
|
||||
// Note: No parallel mode for planning phase - parallel only makes sense with multiple subtasks
|
||||
agentManager.startTaskExecution(
|
||||
@@ -89,13 +114,14 @@ export function registerTaskExecutionHandlers(
|
||||
task.specId,
|
||||
{
|
||||
parallel: false, // Sequential for planning phase
|
||||
workers: 1
|
||||
workers: 1,
|
||||
baseBranch
|
||||
}
|
||||
);
|
||||
} 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,
|
||||
@@ -103,7 +129,8 @@ export function registerTaskExecutionHandlers(
|
||||
task.specId,
|
||||
{
|
||||
parallel: false,
|
||||
workers: 1
|
||||
workers: 1,
|
||||
baseBranch
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -211,13 +238,33 @@ export function registerTaskExecutionHandlers(
|
||||
taskId: string,
|
||||
status: TaskStatus
|
||||
): Promise<IPCResult> => {
|
||||
// Find task and project
|
||||
// Find task and project first (needed for worktree check)
|
||||
const { task, project } = findTaskAndProject(taskId);
|
||||
|
||||
if (!task || !project) {
|
||||
return { success: false, error: 'Task not found' };
|
||||
}
|
||||
|
||||
// Validate status transition - 'done' can only be set through merge handler
|
||||
// UNLESS there's no worktree (limbo state - already merged/discarded or failed)
|
||||
if (status === 'done') {
|
||||
// Check if worktree exists
|
||||
const worktreePath = path.join(project.path, '.worktrees', taskId);
|
||||
const hasWorktree = existsSync(worktreePath);
|
||||
|
||||
if (hasWorktree) {
|
||||
// Worktree exists - must use merge workflow
|
||||
console.warn(`[TASK_UPDATE_STATUS] Blocked attempt to set status 'done' directly for task ${taskId}. Use merge workflow instead.`);
|
||||
return {
|
||||
success: false,
|
||||
error: "Cannot set status to 'done' directly. Complete the human review and merge the worktree changes instead."
|
||||
};
|
||||
} else {
|
||||
// No worktree - allow marking as done (limbo state recovery)
|
||||
console.log(`[TASK_UPDATE_STATUS] Allowing status 'done' for task ${taskId} (no worktree found - limbo state)`);
|
||||
}
|
||||
}
|
||||
|
||||
// Get the spec directory
|
||||
const specsBaseDir = getSpecsDir(project.autoBuildPath);
|
||||
const specDir = path.join(
|
||||
@@ -237,10 +284,10 @@ export function registerTaskExecutionHandlers(
|
||||
// Store the exact UI status - project-store.ts will map it back
|
||||
plan.status = status;
|
||||
// Also store mapped version for Python compatibility
|
||||
plan.planStatus = status === 'done' ? 'completed'
|
||||
: status === 'in_progress' ? 'in_progress'
|
||||
plan.planStatus = status === 'in_progress' ? 'in_progress'
|
||||
: status === 'ai_review' ? 'review'
|
||||
: status === 'human_review' ? 'review'
|
||||
: status === 'done' ? 'completed'
|
||||
: 'pending';
|
||||
plan.updated_at = new Date().toISOString();
|
||||
|
||||
@@ -253,10 +300,10 @@ export function registerTaskExecutionHandlers(
|
||||
created_at: task.createdAt.toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
status: status, // Store exact UI status for persistence
|
||||
planStatus: status === 'done' ? 'completed'
|
||||
: status === 'in_progress' ? 'in_progress'
|
||||
planStatus: status === 'in_progress' ? 'in_progress'
|
||||
: status === 'ai_review' ? 'review'
|
||||
: status === 'human_review' ? 'review'
|
||||
: status === 'done' ? 'completed'
|
||||
: 'pending',
|
||||
phases: []
|
||||
};
|
||||
@@ -272,7 +319,22 @@ 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' };
|
||||
}
|
||||
|
||||
console.warn('[TASK_UPDATE_STATUS] Auto-starting task:', taskId);
|
||||
|
||||
// Start file watcher for this task
|
||||
fileWatcher.watch(taskId, specDir);
|
||||
@@ -283,16 +345,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,
|
||||
@@ -305,7 +367,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,
|
||||
@@ -483,6 +545,23 @@ 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
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
// Set status to in_progress for the restart
|
||||
newStatus = 'in_progress';
|
||||
@@ -500,19 +579,32 @@ export function registerTaskExecutionHandlers(
|
||||
const specDirForWatcher = path.join(project.path, specsBaseDir, task.specId);
|
||||
fileWatcher.watch(taskId, specDirForWatcher);
|
||||
|
||||
// Note: Parallel execution is handled internally by the agent
|
||||
agentManager.startTaskExecution(
|
||||
taskId,
|
||||
project.path,
|
||||
task.specId,
|
||||
{
|
||||
parallel: false,
|
||||
workers: 1
|
||||
}
|
||||
);
|
||||
// Check if spec.md exists to determine whether to run spec creation or task execution
|
||||
const specFilePath = path.join(specDirForWatcher, AUTO_BUILD_PATHS.SPEC_FILE);
|
||||
const hasSpec = existsSync(specFilePath);
|
||||
const needsSpecCreation = !hasSpec;
|
||||
|
||||
if (needsSpecCreation) {
|
||||
// No spec file - need to run spec_runner.py to create the spec
|
||||
const taskDescription = task.description || task.title;
|
||||
console.warn(`[Recovery] Starting spec creation for: ${task.specId}`);
|
||||
agentManager.startSpecCreation(task.specId, project.path, taskDescription, specDirForWatcher, task.metadata);
|
||||
} else {
|
||||
// Spec exists - run task execution
|
||||
console.warn(`[Recovery] Starting task execution for: ${task.specId}`);
|
||||
agentManager.startTaskExecution(
|
||||
taskId,
|
||||
project.path,
|
||||
task.specId,
|
||||
{
|
||||
parallel: false,
|
||||
workers: 1
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
autoRestarted = true;
|
||||
console.log(`[Recovery] Auto-restarted task ${taskId}`);
|
||||
console.warn(`[Recovery] Auto-restarted task ${taskId}`);
|
||||
} catch (restartError) {
|
||||
console.error('Failed to auto-restart task after recovery:', restartError);
|
||||
// Recovery succeeded but restart failed - still report success
|
||||
|
||||
@@ -15,6 +15,7 @@ import { registerTaskCRUDHandlers } from './crud-handlers';
|
||||
import { registerTaskExecutionHandlers } from './execution-handlers';
|
||||
import { registerWorktreeHandlers } from './worktree-handlers';
|
||||
import { registerTaskLogsHandlers } from './logs-handlers';
|
||||
import { registerTaskArchiveHandlers } from './archive-handlers';
|
||||
|
||||
/**
|
||||
* Register all task-related IPC handlers
|
||||
@@ -35,6 +36,9 @@ export function registerTaskHandlers(
|
||||
|
||||
// Register logs handlers (get, watch, unwatch)
|
||||
registerTaskLogsHandlers(getMainWindow);
|
||||
|
||||
// Register archive handlers (archive, unarchive)
|
||||
registerTaskArchiveHandlers();
|
||||
}
|
||||
|
||||
// Export shared utilities for use by other modules if needed
|
||||
|
||||
@@ -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';
|
||||
@@ -224,14 +224,13 @@ export function registerWorktreeHandlers(
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.TASK_WORKTREE_MERGE,
|
||||
async (_, taskId: string, options?: { noCommit?: boolean }): Promise<IPCResult<WorktreeMergeResult>> => {
|
||||
// Enable debug logging via DEBUG_MERGE or DEBUG environment variables
|
||||
const DEBUG_MERGE = process.env.DEBUG_MERGE === 'true' || process.env.DEBUG === 'true';
|
||||
// Always log merge operations for debugging
|
||||
const debug = (...args: unknown[]) => {
|
||||
if (DEBUG_MERGE) 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
|
||||
@@ -274,15 +273,13 @@ export function registerWorktreeHandlers(
|
||||
debug('Worktree path:', worktreePath, 'exists:', existsSync(worktreePath));
|
||||
|
||||
// Get git status before merge
|
||||
if (DEBUG_MERGE) {
|
||||
try {
|
||||
const gitStatusBefore = execSync('git status --short', { cwd: project.path, encoding: 'utf-8' });
|
||||
debug('Git status BEFORE merge in main project:\n', gitStatusBefore || '(clean)');
|
||||
const gitBranch = execSync('git branch --show-current', { cwd: project.path, encoding: 'utf-8' }).trim();
|
||||
debug('Current branch:', gitBranch);
|
||||
} catch (e) {
|
||||
debug('Failed to get git status before:', e);
|
||||
}
|
||||
try {
|
||||
const gitStatusBefore = execSync('git status --short', { cwd: project.path, encoding: 'utf-8' });
|
||||
debug('Git status BEFORE merge in main project:\n', gitStatusBefore || '(clean)');
|
||||
const gitBranch = execSync('git branch --show-current', { cwd: project.path, encoding: 'utf-8' }).trim();
|
||||
debug('Current branch:', gitBranch);
|
||||
} catch (e) {
|
||||
debug('Failed to get git status before:', e);
|
||||
}
|
||||
|
||||
const args = [
|
||||
@@ -309,18 +306,67 @@ export function registerWorktreeHandlers(
|
||||
});
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const MERGE_TIMEOUT_MS = 120000; // 2 minutes timeout for merge operations
|
||||
let timeoutId: NodeJS.Timeout | null = null;
|
||||
let resolved = false;
|
||||
|
||||
const mergeProcess = spawn(pythonPath, args, {
|
||||
cwd: sourcePath,
|
||||
env: {
|
||||
...process.env,
|
||||
...profileEnv, // Include active Claude profile OAuth token
|
||||
PYTHONUNBUFFERED: '1'
|
||||
}
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'] // Don't connect stdin to avoid blocking
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
// Set up timeout to kill hung processes
|
||||
timeoutId = setTimeout(() => {
|
||||
if (!resolved) {
|
||||
debug('TIMEOUT: Merge process exceeded', MERGE_TIMEOUT_MS, 'ms, killing...');
|
||||
resolved = true;
|
||||
mergeProcess.kill('SIGTERM');
|
||||
// Give it a moment to clean up, then force kill
|
||||
setTimeout(() => {
|
||||
try {
|
||||
mergeProcess.kill('SIGKILL');
|
||||
} catch {
|
||||
// Process may already be dead
|
||||
}
|
||||
}, 5000);
|
||||
|
||||
// Check if merge might have succeeded before the hang
|
||||
// Look for success indicators in the output
|
||||
const mayHaveSucceeded = stdout.includes('staged') ||
|
||||
stdout.includes('Successfully merged') ||
|
||||
stdout.includes('Changes from');
|
||||
|
||||
if (mayHaveSucceeded) {
|
||||
debug('TIMEOUT: Process hung but merge may have succeeded based on output');
|
||||
const isStageOnly = options?.noCommit === true;
|
||||
resolve({
|
||||
success: true,
|
||||
data: {
|
||||
success: true,
|
||||
message: 'Changes staged (process timed out but merge appeared successful)',
|
||||
staged: isStageOnly,
|
||||
projectPath: isStageOnly ? project.path : undefined
|
||||
}
|
||||
});
|
||||
} else {
|
||||
resolve({
|
||||
success: false,
|
||||
error: 'Merge process timed out. Check git status to see if merge completed.'
|
||||
});
|
||||
}
|
||||
}
|
||||
}, MERGE_TIMEOUT_MS);
|
||||
|
||||
mergeProcess.stdout.on('data', (data: Buffer) => {
|
||||
const chunk = data.toString();
|
||||
stdout += chunk;
|
||||
@@ -333,21 +379,24 @@ export function registerWorktreeHandlers(
|
||||
debug('STDERR:', chunk);
|
||||
});
|
||||
|
||||
mergeProcess.on('close', (code: number) => {
|
||||
debug('Process exited with code:', code);
|
||||
// Handler for when process exits
|
||||
const handleProcessExit = (code: number | null, signal: string | null = null) => {
|
||||
if (resolved) return; // Prevent double-resolution
|
||||
resolved = true;
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
|
||||
debug('Process exited with code:', code, 'signal:', signal);
|
||||
debug('Full stdout:', stdout);
|
||||
debug('Full stderr:', stderr);
|
||||
|
||||
// Get git status after merge
|
||||
if (DEBUG_MERGE) {
|
||||
try {
|
||||
const gitStatusAfter = execSync('git status --short', { cwd: project.path, encoding: 'utf-8' });
|
||||
debug('Git status AFTER merge in main project:\n', gitStatusAfter || '(clean)');
|
||||
const gitDiffStaged = execSync('git diff --staged --stat', { cwd: project.path, encoding: 'utf-8' });
|
||||
debug('Staged changes:\n', gitDiffStaged || '(none)');
|
||||
} catch (e) {
|
||||
debug('Failed to get git status after:', e);
|
||||
}
|
||||
try {
|
||||
const gitStatusAfter = execSync('git status --short', { cwd: project.path, encoding: 'utf-8' });
|
||||
debug('Git status AFTER merge in main project:\n', gitStatusAfter || '(clean)');
|
||||
const gitDiffStaged = execSync('git diff --staged --stat', { cwd: project.path, encoding: 'utf-8' });
|
||||
debug('Staged changes:\n', gitDiffStaged || '(none)');
|
||||
} catch (e) {
|
||||
debug('Failed to get git status after:', e);
|
||||
}
|
||||
|
||||
if (code === 0) {
|
||||
@@ -412,9 +461,22 @@ export function registerWorktreeHandlers(
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
mergeProcess.on('close', (code: number | null, signal: string | null) => {
|
||||
handleProcessExit(code, signal);
|
||||
});
|
||||
|
||||
// Also listen to 'exit' event in case 'close' doesn't fire
|
||||
mergeProcess.on('exit', (code: number | null, signal: string | null) => {
|
||||
// Give close event a chance to fire first with complete output
|
||||
setTimeout(() => handleProcessExit(code, signal), 100);
|
||||
});
|
||||
|
||||
mergeProcess.on('error', (err: Error) => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
console.error('[MERGE] Process spawn error:', err);
|
||||
resolve({
|
||||
success: false,
|
||||
@@ -439,11 +501,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);
|
||||
@@ -462,7 +524,28 @@ 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;
|
||||
let uncommittedFiles: string[] = [];
|
||||
try {
|
||||
const gitStatus = execSync('git status --porcelain', {
|
||||
cwd: project.path,
|
||||
encoding: 'utf-8'
|
||||
}).trim();
|
||||
|
||||
if (gitStatus) {
|
||||
// Parse the status output to get file names
|
||||
uncommittedFiles = gitStatus.split('\n')
|
||||
.filter(line => line.trim())
|
||||
.map(line => line.substring(3).trim()); // Remove status prefix (e.g., "M ", " M ", "?? ")
|
||||
hasUncommittedChanges = uncommittedFiles.length > 0;
|
||||
console.warn('[IPC] Uncommitted changes detected:', uncommittedFiles.length, 'files');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[IPC] Failed to check git status:', e);
|
||||
}
|
||||
|
||||
const sourcePath = getEffectiveSourcePath();
|
||||
if (!sourcePath) {
|
||||
@@ -479,7 +562,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();
|
||||
@@ -487,7 +570,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 = '';
|
||||
@@ -496,22 +579,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: {
|
||||
@@ -527,7 +610,13 @@ export function registerWorktreeHandlers(
|
||||
autoMergeable: 0,
|
||||
hasGitConflicts: false
|
||||
},
|
||||
gitConflicts: result.gitConflicts || null
|
||||
gitConflicts: result.gitConflicts || null,
|
||||
// Include uncommitted changes info for the frontend
|
||||
uncommittedChanges: hasUncommittedChanges ? {
|
||||
hasChanges: true,
|
||||
files: uncommittedFiles,
|
||||
count: uncommittedFiles.length
|
||||
} : null
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { ipcMain } from 'electron';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import type { IPCResult, TerminalCreateOptions, ClaudeProfile, ClaudeProfileSettings } from '../../shared/types';
|
||||
import type { IPCResult, TerminalCreateOptions, ClaudeProfile, ClaudeProfileSettings, ClaudeUsageSnapshot } from '../../shared/types';
|
||||
import { getClaudeProfileManager } from '../claude-profile-manager';
|
||||
import { getUsageMonitor } from '../claude-profile/usage-monitor';
|
||||
import { TerminalManager } from '../terminal-manager';
|
||||
import { projectStore } from '../project-store';
|
||||
import { terminalNameGenerator } from '../terminal-name-generator';
|
||||
@@ -207,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,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,
|
||||
@@ -239,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`);
|
||||
@@ -254,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);
|
||||
@@ -316,6 +317,12 @@ export function registerTerminalHandlers(
|
||||
try {
|
||||
const profileManager = getClaudeProfileManager();
|
||||
profileManager.updateAutoSwitchSettings(settings);
|
||||
|
||||
// Restart usage monitor with new settings
|
||||
const monitor = getUsageMonitor();
|
||||
monitor.stop();
|
||||
monitor.start();
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
@@ -408,6 +415,28 @@ export function registerTerminalHandlers(
|
||||
}
|
||||
);
|
||||
|
||||
// ============================================
|
||||
// Usage Monitoring (Proactive Account Switching)
|
||||
// ============================================
|
||||
|
||||
// Request current usage snapshot
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.USAGE_REQUEST,
|
||||
async (): Promise<IPCResult<import('../../shared/types').ClaudeUsageSnapshot | null>> => {
|
||||
try {
|
||||
const monitor = getUsageMonitor();
|
||||
const usage = monitor.getCurrentUsage();
|
||||
return { success: true, data: usage };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to get current usage'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
// Terminal session management (persistence/restore)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.TERMINAL_GET_SESSIONS,
|
||||
@@ -522,3 +551,23 @@ export function registerTerminalHandlers(
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize usage monitor event forwarding to renderer process
|
||||
* Call this after mainWindow is created
|
||||
*/
|
||||
export function initializeUsageMonitorForwarding(mainWindow: BrowserWindow): void {
|
||||
const monitor = getUsageMonitor();
|
||||
|
||||
// Forward usage updates to renderer
|
||||
monitor.on('usage-updated', (usage: ClaudeUsageSnapshot) => {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.USAGE_UPDATED, usage);
|
||||
});
|
||||
|
||||
// Forward proactive swap notifications to renderer
|
||||
monitor.on('show-swap-notification', (notification: unknown) => {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.PROACTIVE_SWAP_NOTIFICATION, notification);
|
||||
});
|
||||
|
||||
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[] = [];
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -144,7 +144,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 +154,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 +177,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 {};
|
||||
}
|
||||
|
||||
@@ -228,6 +228,17 @@ export interface SDKRateLimitInfo {
|
||||
detectedAt: Date;
|
||||
/** Original error message */
|
||||
originalError?: string;
|
||||
|
||||
// Auto-swap information
|
||||
/** Whether this rate limit was automatically handled via account swap */
|
||||
wasAutoSwapped?: boolean;
|
||||
/** Profile that was swapped to (if auto-swapped) */
|
||||
swappedToProfile?: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
/** Why the swap occurred: 'proactive' (before limit) or 'reactive' (after limit hit) */
|
||||
swapReason?: 'proactive' | 'reactive';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -189,7 +189,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 +200,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 +225,7 @@ export class TaskLogService extends EventEmitter {
|
||||
lastMainContent = currentContent;
|
||||
mainChanged = true;
|
||||
}
|
||||
} catch (error) {
|
||||
} catch (_error) {
|
||||
// Ignore read/parse errors
|
||||
}
|
||||
}
|
||||
@@ -240,7 +240,7 @@ export class TaskLogService extends EventEmitter {
|
||||
lastWorktreeContent = currentContent;
|
||||
worktreeChanged = true;
|
||||
}
|
||||
} catch (error) {
|
||||
} catch (_error) {
|
||||
// Ignore read/parse errors
|
||||
}
|
||||
}
|
||||
@@ -262,7 +262,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 +274,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');
|
||||
|
||||
@@ -0,0 +1,413 @@
|
||||
/**
|
||||
* PTY Daemon Client
|
||||
*
|
||||
* Communicates with the PTY daemon process via Unix socket/named pipe.
|
||||
* Handles connection management, automatic reconnection, and message routing.
|
||||
*/
|
||||
|
||||
import * as net from 'net';
|
||||
import * as path from 'path';
|
||||
import { spawn, ChildProcess } from 'child_process';
|
||||
import { app } from 'electron';
|
||||
|
||||
const SOCKET_PATH =
|
||||
process.platform === 'win32'
|
||||
? `\\\\.\\pipe\\auto-claude-pty-${process.getuid?.() || 'default'}`
|
||||
: `/tmp/auto-claude-pty-${process.getuid?.() || 'default'}.sock`;
|
||||
|
||||
interface DaemonResponseData {
|
||||
exitCode?: number;
|
||||
signal?: number;
|
||||
}
|
||||
|
||||
interface DaemonResponse {
|
||||
requestId?: string;
|
||||
type: string;
|
||||
id?: string;
|
||||
data?: string | DaemonResponseData;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
type ResponseHandler = (response: DaemonResponse) => void;
|
||||
|
||||
interface PtyConfig {
|
||||
shell: string;
|
||||
shellArgs: string[];
|
||||
cwd: string;
|
||||
env: Record<string, string>;
|
||||
rows: number;
|
||||
cols: number;
|
||||
}
|
||||
|
||||
interface PtyInfo {
|
||||
id: string;
|
||||
config: PtyConfig;
|
||||
createdAt: number;
|
||||
lastDataAt: number;
|
||||
isDead: boolean;
|
||||
bufferSize: number;
|
||||
}
|
||||
|
||||
class PtyDaemonClient {
|
||||
private socket: net.Socket | null = null;
|
||||
private daemonProcess: ChildProcess | null = null;
|
||||
private pendingRequests = new Map<string, ResponseHandler>();
|
||||
private dataHandlers = new Map<string, (data: string) => void>();
|
||||
private exitHandlers = new Map<string, (exitCode: number, signal?: number) => void>();
|
||||
private reconnectAttempts = 0;
|
||||
private maxReconnectAttempts = 5;
|
||||
private isConnecting = false;
|
||||
private buffer = '';
|
||||
private isShuttingDown = false;
|
||||
|
||||
/**
|
||||
* Connect to daemon, spawning if necessary
|
||||
*/
|
||||
async connect(): Promise<void> {
|
||||
if (this.isShuttingDown) {
|
||||
throw new Error('Client is shutting down');
|
||||
}
|
||||
|
||||
if (this.socket || this.isConnecting) return;
|
||||
|
||||
this.isConnecting = true;
|
||||
|
||||
try {
|
||||
// Try to connect to existing daemon
|
||||
await this.tryConnect();
|
||||
console.warn('[PtyDaemonClient] Connected to existing daemon');
|
||||
} catch {
|
||||
// Spawn daemon and connect
|
||||
console.warn('[PtyDaemonClient] Spawning new daemon...');
|
||||
await this.spawnDaemon();
|
||||
await this.tryConnect();
|
||||
console.warn('[PtyDaemonClient] Connected to new daemon');
|
||||
} finally {
|
||||
this.isConnecting = false;
|
||||
this.reconnectAttempts = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to connect to existing daemon
|
||||
*/
|
||||
private tryConnect(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = net.connect(SOCKET_PATH);
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
socket.destroy();
|
||||
reject(new Error('Connection timeout'));
|
||||
}, 3000);
|
||||
|
||||
socket.on('connect', () => {
|
||||
clearTimeout(timeout);
|
||||
this.socket = socket;
|
||||
this.setupSocketHandlers();
|
||||
resolve();
|
||||
});
|
||||
|
||||
socket.on('error', (err) => {
|
||||
clearTimeout(timeout);
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a new daemon process
|
||||
*/
|
||||
private async spawnDaemon(): Promise<void> {
|
||||
// In production, the daemon file is in the same directory
|
||||
const daemonPath = path.join(__dirname, 'pty-daemon.js');
|
||||
|
||||
try {
|
||||
// Spawn detached process that survives parent
|
||||
this.daemonProcess = spawn(process.execPath, [daemonPath], {
|
||||
detached: true,
|
||||
stdio: 'ignore', // Don't pipe stdout/stderr
|
||||
env: { ...process.env },
|
||||
});
|
||||
|
||||
// Unref so parent can exit independently
|
||||
this.daemonProcess.unref();
|
||||
|
||||
console.warn(`[PtyDaemonClient] Spawned daemon process (PID: ${this.daemonProcess.pid})`);
|
||||
|
||||
// Wait for daemon to start listening
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
} catch (error) {
|
||||
console.error('[PtyDaemonClient] Failed to spawn daemon:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup socket event handlers
|
||||
*/
|
||||
private setupSocketHandlers(): void {
|
||||
if (!this.socket) return;
|
||||
|
||||
this.socket.on('data', (chunk) => {
|
||||
this.buffer += chunk.toString();
|
||||
|
||||
// Handle newline-delimited JSON
|
||||
const lines = this.buffer.split('\n');
|
||||
this.buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.trim()) continue;
|
||||
try {
|
||||
const response = JSON.parse(line);
|
||||
this.handleResponse(response);
|
||||
} catch (e) {
|
||||
console.error('[PtyDaemonClient] Invalid response:', e);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.socket.on('close', () => {
|
||||
console.warn('[PtyDaemonClient] Disconnected from daemon');
|
||||
this.socket = null;
|
||||
if (!this.isShuttingDown) {
|
||||
this.attemptReconnect();
|
||||
}
|
||||
});
|
||||
|
||||
this.socket.on('error', (err) => {
|
||||
console.error('[PtyDaemonClient] Socket error:', err);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle response from daemon
|
||||
*/
|
||||
private handleResponse(response: DaemonResponse): void {
|
||||
// Handle request-response pattern
|
||||
if (response.requestId) {
|
||||
const handler = this.pendingRequests.get(response.requestId);
|
||||
if (handler) {
|
||||
this.pendingRequests.delete(response.requestId);
|
||||
handler(response);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle streaming data
|
||||
if (response.type === 'data' && response.id) {
|
||||
const handler = this.dataHandlers.get(response.id);
|
||||
if (handler && typeof response.data === 'string') {
|
||||
handler(response.data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle exit events
|
||||
if (response.type === 'exit' && response.id) {
|
||||
const handler = this.exitHandlers.get(response.id);
|
||||
if (handler && typeof response.data === 'object' && response.data !== null) {
|
||||
const exitData = response.data as DaemonResponseData;
|
||||
handler(exitData.exitCode ?? 0, exitData.signal);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to reconnect with exponential backoff
|
||||
*/
|
||||
private attemptReconnect(): void {
|
||||
if (this.isShuttingDown) return;
|
||||
|
||||
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
||||
console.error('[PtyDaemonClient] Max reconnect attempts reached');
|
||||
return;
|
||||
}
|
||||
|
||||
this.reconnectAttempts++;
|
||||
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 10000);
|
||||
|
||||
console.warn(
|
||||
`[PtyDaemonClient] Reconnect attempt ${this.reconnectAttempts} in ${delay}ms...`
|
||||
);
|
||||
|
||||
setTimeout(() => {
|
||||
this.connect().catch((error) => {
|
||||
console.error('[PtyDaemonClient] Reconnect failed:', error);
|
||||
});
|
||||
}, delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a request and wait for response
|
||||
*/
|
||||
private async request<T>(msg: Record<string, unknown>): Promise<T> {
|
||||
await this.connect();
|
||||
|
||||
if (!this.socket) {
|
||||
throw new Error('Not connected to daemon');
|
||||
}
|
||||
|
||||
const requestId = `req-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
this.pendingRequests.delete(requestId);
|
||||
reject(new Error('Request timeout'));
|
||||
}, 10000);
|
||||
|
||||
this.pendingRequests.set(requestId, (response) => {
|
||||
clearTimeout(timeout);
|
||||
if (response.type === 'error') {
|
||||
reject(new Error(response.error || 'Unknown error'));
|
||||
} else {
|
||||
resolve(response as T);
|
||||
}
|
||||
});
|
||||
|
||||
this.socket!.write(JSON.stringify({ ...msg, requestId }) + '\n');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message without expecting a response
|
||||
*/
|
||||
private send(msg: Record<string, unknown>): void {
|
||||
if (!this.socket) {
|
||||
console.warn('[PtyDaemonClient] Cannot send - not connected');
|
||||
return;
|
||||
}
|
||||
this.socket.write(JSON.stringify(msg) + '\n');
|
||||
}
|
||||
|
||||
// ===== Public API =====
|
||||
|
||||
/**
|
||||
* Create a new PTY in the daemon
|
||||
*/
|
||||
async createPty(config: PtyConfig): Promise<string> {
|
||||
const response = await this.request<{ type: 'created'; id: string }>({
|
||||
type: 'create',
|
||||
data: config,
|
||||
});
|
||||
return response.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data to a PTY
|
||||
*/
|
||||
write(id: string, data: string): void {
|
||||
this.send({ type: 'write', id, data });
|
||||
}
|
||||
|
||||
/**
|
||||
* Resize a PTY
|
||||
*/
|
||||
resize(id: string, cols: number, rows: number): void {
|
||||
this.send({ type: 'resize', id, data: { cols, rows } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Kill a PTY
|
||||
*/
|
||||
kill(id: string): void {
|
||||
this.send({ type: 'kill', id });
|
||||
this.dataHandlers.delete(id);
|
||||
this.exitHandlers.delete(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* List all PTYs in the daemon
|
||||
*/
|
||||
async list(): Promise<PtyInfo[]> {
|
||||
const response = await this.request<{ type: 'list'; data: PtyInfo[] }>({
|
||||
type: 'list',
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to PTY output and exit events
|
||||
*/
|
||||
subscribe(
|
||||
id: string,
|
||||
onData: (data: string) => void,
|
||||
onExit: (code: number, signal?: number) => void
|
||||
): void {
|
||||
this.dataHandlers.set(id, onData);
|
||||
this.exitHandlers.set(id, onExit);
|
||||
this.send({ type: 'subscribe', id });
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribe from PTY events
|
||||
*/
|
||||
unsubscribe(id: string): void {
|
||||
this.dataHandlers.delete(id);
|
||||
this.exitHandlers.delete(id);
|
||||
this.send({ type: 'unsubscribe', id });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get buffered output from a PTY
|
||||
*/
|
||||
async getBuffer(id: string): Promise<{ buffer: string; isDead: boolean }> {
|
||||
const response = await this.request<{
|
||||
type: 'buffer';
|
||||
data: { buffer: string; isDead: boolean };
|
||||
}>({
|
||||
type: 'get-buffer',
|
||||
id,
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if daemon is alive
|
||||
*/
|
||||
async ping(): Promise<boolean> {
|
||||
try {
|
||||
await this.request<{ type: 'pong' }>({ type: 'ping' });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if connected
|
||||
*/
|
||||
isConnected(): boolean {
|
||||
return this.socket !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect from daemon (does not kill daemon)
|
||||
*/
|
||||
disconnect(): void {
|
||||
if (this.socket) {
|
||||
this.isShuttingDown = true;
|
||||
this.socket.end();
|
||||
this.socket = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup on app shutdown
|
||||
*/
|
||||
shutdown(): void {
|
||||
this.isShuttingDown = true;
|
||||
this.disconnect();
|
||||
this.pendingRequests.clear();
|
||||
this.dataHandlers.clear();
|
||||
this.exitHandlers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton instance
|
||||
export const ptyDaemonClient = new PtyDaemonClient();
|
||||
|
||||
// Cleanup on app quit
|
||||
app.on('before-quit', () => {
|
||||
ptyDaemonClient.shutdown();
|
||||
});
|
||||
@@ -0,0 +1,499 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* PTY Daemon Process
|
||||
*
|
||||
* Runs as a separate detached process that owns all PTY instances.
|
||||
* Survives main Electron process restarts, providing session continuity.
|
||||
*
|
||||
* Communication: Unix socket (Linux/macOS) or Named Pipe (Windows)
|
||||
*/
|
||||
|
||||
import * as net from 'net';
|
||||
import * as fs from 'fs';
|
||||
import * as pty from 'node-pty';
|
||||
|
||||
const SOCKET_PATH =
|
||||
process.platform === 'win32'
|
||||
? `\\\\.\\pipe\\auto-claude-pty-${process.getuid?.() || 'default'}`
|
||||
: `/tmp/auto-claude-pty-${process.getuid?.() || 'default'}.sock`;
|
||||
|
||||
// Maximum buffer size per PTY (100KB)
|
||||
const MAX_BUFFER_SIZE = 100_000;
|
||||
|
||||
// Ring buffer to prevent memory growth
|
||||
const RING_BUFFER_MAX_CHUNKS = 1000;
|
||||
|
||||
interface ManagedPty {
|
||||
id: string;
|
||||
process: pty.IPty;
|
||||
config: PtyConfig;
|
||||
buffer: string[];
|
||||
bufferSize: number;
|
||||
clients: Set<net.Socket>;
|
||||
createdAt: number;
|
||||
lastDataAt: number;
|
||||
isDead: boolean;
|
||||
}
|
||||
|
||||
interface PtyConfig {
|
||||
shell: string;
|
||||
shellArgs: string[];
|
||||
cwd: string;
|
||||
env: Record<string, string>;
|
||||
rows: number;
|
||||
cols: number;
|
||||
}
|
||||
|
||||
interface DaemonMessage {
|
||||
type:
|
||||
| 'create'
|
||||
| 'write'
|
||||
| 'resize'
|
||||
| 'kill'
|
||||
| 'list'
|
||||
| 'subscribe'
|
||||
| 'unsubscribe'
|
||||
| 'get-buffer'
|
||||
| 'ping';
|
||||
id?: string;
|
||||
data?: unknown;
|
||||
requestId?: string;
|
||||
}
|
||||
|
||||
interface DaemonResponse {
|
||||
type: 'created' | 'list' | 'buffer' | 'data' | 'exit' | 'error' | 'pong';
|
||||
id?: string;
|
||||
data?: unknown;
|
||||
requestId?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
class PtyDaemon {
|
||||
private ptys = new Map<string, ManagedPty>();
|
||||
private server: net.Server | null = null;
|
||||
|
||||
constructor() {
|
||||
console.error('[PTY Daemon] Starting...');
|
||||
this.cleanup();
|
||||
this.startServer();
|
||||
this.setupSignalHandlers();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove stale socket/pipe
|
||||
*/
|
||||
private cleanup(): void {
|
||||
if (process.platform !== 'win32' && fs.existsSync(SOCKET_PATH)) {
|
||||
try {
|
||||
fs.unlinkSync(SOCKET_PATH);
|
||||
console.error('[PTY Daemon] Cleaned up stale socket');
|
||||
} catch (error) {
|
||||
console.error('[PTY Daemon] Failed to clean up socket:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the IPC server
|
||||
*/
|
||||
private startServer(): void {
|
||||
this.server = net.createServer((socket) => {
|
||||
console.error('[PTY Daemon] Client connected');
|
||||
this.handleConnection(socket);
|
||||
});
|
||||
|
||||
this.server.on('error', (err: NodeJS.ErrnoException) => {
|
||||
console.error('[PTY Daemon] Server error:', err);
|
||||
if (err.code === 'EADDRINUSE') {
|
||||
console.error('[PTY Daemon] Address in use - another daemon may be running');
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
this.server.listen(SOCKET_PATH, () => {
|
||||
console.error(`[PTY Daemon] Listening on ${SOCKET_PATH}`);
|
||||
// Set permissions on Unix
|
||||
if (process.platform !== 'win32') {
|
||||
try {
|
||||
fs.chmodSync(SOCKET_PATH, 0o600);
|
||||
} catch (error) {
|
||||
console.error('[PTY Daemon] Failed to set socket permissions:', error);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a client connection
|
||||
*/
|
||||
private handleConnection(socket: net.Socket): void {
|
||||
let buffer = '';
|
||||
|
||||
socket.on('data', (chunk) => {
|
||||
buffer += chunk.toString();
|
||||
|
||||
// Handle newline-delimited JSON messages
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.trim()) continue;
|
||||
try {
|
||||
const msg: DaemonMessage = JSON.parse(line);
|
||||
this.handleMessage(socket, msg);
|
||||
} catch (e) {
|
||||
console.error('[PTY Daemon] Invalid message:', e);
|
||||
this.sendError(socket, 'Invalid JSON message');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('close', () => {
|
||||
console.error('[PTY Daemon] Client disconnected');
|
||||
// Unsubscribe from all PTYs
|
||||
this.ptys.forEach((pty) => {
|
||||
pty.clients.delete(socket);
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('error', (err) => {
|
||||
console.error('[PTY Daemon] Socket error:', err);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle incoming message from client
|
||||
*/
|
||||
private handleMessage(socket: net.Socket, msg: DaemonMessage): void {
|
||||
try {
|
||||
switch (msg.type) {
|
||||
case 'ping':
|
||||
this.send(socket, { type: 'pong', requestId: msg.requestId });
|
||||
break;
|
||||
|
||||
case 'create': {
|
||||
const id = this.createPty(msg.data as PtyConfig);
|
||||
this.send(socket, { type: 'created', id, requestId: msg.requestId });
|
||||
break;
|
||||
}
|
||||
|
||||
case 'write':
|
||||
if (!msg.id) throw new Error('Missing PTY id');
|
||||
this.writeToPty(msg.id, msg.data as string);
|
||||
break;
|
||||
|
||||
case 'resize': {
|
||||
if (!msg.id) throw new Error('Missing PTY id');
|
||||
const resizeData = msg.data as { cols: number; rows: number };
|
||||
this.resizePty(msg.id, resizeData.cols, resizeData.rows);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'kill':
|
||||
if (!msg.id) throw new Error('Missing PTY id');
|
||||
this.killPty(msg.id);
|
||||
break;
|
||||
|
||||
case 'list': {
|
||||
const list = this.listPtys();
|
||||
this.send(socket, { type: 'list', data: list, requestId: msg.requestId });
|
||||
break;
|
||||
}
|
||||
|
||||
case 'subscribe':
|
||||
if (!msg.id) throw new Error('Missing PTY id');
|
||||
this.subscribeToPty(socket, msg.id);
|
||||
break;
|
||||
|
||||
case 'unsubscribe':
|
||||
if (!msg.id) throw new Error('Missing PTY id');
|
||||
this.unsubscribeFromPty(socket, msg.id);
|
||||
break;
|
||||
|
||||
case 'get-buffer': {
|
||||
if (!msg.id) throw new Error('Missing PTY id');
|
||||
const bufferData = this.getBuffer(msg.id);
|
||||
this.send(socket, {
|
||||
type: 'buffer',
|
||||
id: msg.id,
|
||||
data: bufferData,
|
||||
requestId: msg.requestId,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown message type: ${(msg as DaemonMessage).type}`);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||
console.error('[PTY Daemon] Error handling message:', errorMsg);
|
||||
this.sendError(socket, errorMsg, msg.requestId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new PTY
|
||||
*/
|
||||
private createPty(config: PtyConfig): string {
|
||||
const id = `pty-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
|
||||
try {
|
||||
const ptyProcess = pty.spawn(config.shell, config.shellArgs, {
|
||||
name: 'xterm-256color',
|
||||
cols: config.cols,
|
||||
rows: config.rows,
|
||||
cwd: config.cwd,
|
||||
env: config.env,
|
||||
});
|
||||
|
||||
const managed: ManagedPty = {
|
||||
id,
|
||||
process: ptyProcess,
|
||||
config,
|
||||
buffer: [],
|
||||
bufferSize: 0,
|
||||
clients: new Set(),
|
||||
createdAt: Date.now(),
|
||||
lastDataAt: Date.now(),
|
||||
isDead: false,
|
||||
};
|
||||
|
||||
// Capture all output
|
||||
ptyProcess.onData((data) => {
|
||||
managed.lastDataAt = Date.now();
|
||||
|
||||
// Add to ring buffer
|
||||
managed.buffer.push(data);
|
||||
managed.bufferSize += data.length;
|
||||
|
||||
// Enforce buffer size limit
|
||||
while (managed.bufferSize > MAX_BUFFER_SIZE && managed.buffer.length > 1) {
|
||||
const removed = managed.buffer.shift();
|
||||
if (removed) {
|
||||
managed.bufferSize -= removed.length;
|
||||
}
|
||||
}
|
||||
|
||||
// Also enforce chunk count limit (ring buffer behavior)
|
||||
while (managed.buffer.length > RING_BUFFER_MAX_CHUNKS) {
|
||||
const removed = managed.buffer.shift();
|
||||
if (removed) {
|
||||
managed.bufferSize -= removed.length;
|
||||
}
|
||||
}
|
||||
|
||||
// Broadcast to all subscribers
|
||||
managed.clients.forEach((client) => {
|
||||
this.send(client, { type: 'data', id, data });
|
||||
});
|
||||
});
|
||||
|
||||
ptyProcess.onExit(({ exitCode, signal }) => {
|
||||
console.error(`[PTY Daemon] PTY ${id} exited: code=${exitCode}, signal=${signal}`);
|
||||
managed.isDead = true;
|
||||
|
||||
// Notify all subscribers
|
||||
managed.clients.forEach((client) => {
|
||||
this.send(client, { type: 'exit', id, data: { exitCode, signal } });
|
||||
});
|
||||
|
||||
// Keep in map for buffer retrieval, will be cleaned up on explicit kill
|
||||
});
|
||||
|
||||
this.ptys.set(id, managed);
|
||||
console.error(`[PTY Daemon] Created PTY ${id} (${config.shell})`);
|
||||
|
||||
return id;
|
||||
} catch (error) {
|
||||
console.error('[PTY Daemon] Failed to create PTY:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data to a PTY
|
||||
*/
|
||||
private writeToPty(id: string, data: string): void {
|
||||
const managed = this.ptys.get(id);
|
||||
if (!managed) {
|
||||
throw new Error(`PTY ${id} not found`);
|
||||
}
|
||||
if (managed.isDead) {
|
||||
throw new Error(`PTY ${id} is dead`);
|
||||
}
|
||||
managed.process.write(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resize a PTY
|
||||
*/
|
||||
private resizePty(id: string, cols: number, rows: number): void {
|
||||
const managed = this.ptys.get(id);
|
||||
if (!managed) {
|
||||
throw new Error(`PTY ${id} not found`);
|
||||
}
|
||||
if (managed.isDead) {
|
||||
console.warn(`[PTY Daemon] Cannot resize dead PTY ${id}`);
|
||||
return;
|
||||
}
|
||||
managed.process.resize(cols, rows);
|
||||
managed.config.cols = cols;
|
||||
managed.config.rows = rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kill a PTY and remove it
|
||||
*/
|
||||
private killPty(id: string): void {
|
||||
const managed = this.ptys.get(id);
|
||||
if (!managed) {
|
||||
console.warn(`[PTY Daemon] PTY ${id} not found for kill`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!managed.isDead) {
|
||||
try {
|
||||
managed.process.kill();
|
||||
} catch (error) {
|
||||
console.error(`[PTY Daemon] Error killing PTY ${id}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
this.ptys.delete(id);
|
||||
console.error(`[PTY Daemon] Removed PTY ${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* List all PTYs
|
||||
*/
|
||||
private listPtys(): Array<{
|
||||
id: string;
|
||||
config: PtyConfig;
|
||||
createdAt: number;
|
||||
lastDataAt: number;
|
||||
isDead: boolean;
|
||||
bufferSize: number;
|
||||
}> {
|
||||
return Array.from(this.ptys.values()).map((m) => ({
|
||||
id: m.id,
|
||||
config: m.config,
|
||||
createdAt: m.createdAt,
|
||||
lastDataAt: m.lastDataAt,
|
||||
isDead: m.isDead,
|
||||
bufferSize: m.bufferSize,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe a client to PTY output
|
||||
*/
|
||||
private subscribeToPty(socket: net.Socket, id: string): void {
|
||||
const managed = this.ptys.get(id);
|
||||
if (!managed) {
|
||||
throw new Error(`PTY ${id} not found`);
|
||||
}
|
||||
managed.clients.add(socket);
|
||||
console.error(`[PTY Daemon] Client subscribed to PTY ${id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribe a client from PTY output
|
||||
*/
|
||||
private unsubscribeFromPty(socket: net.Socket, id: string): void {
|
||||
const managed = this.ptys.get(id);
|
||||
if (managed) {
|
||||
managed.clients.delete(socket);
|
||||
console.error(`[PTY Daemon] Client unsubscribed from PTY ${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the buffered output for a PTY
|
||||
*/
|
||||
private getBuffer(id: string): { buffer: string; isDead: boolean } {
|
||||
const managed = this.ptys.get(id);
|
||||
if (!managed) {
|
||||
throw new Error(`PTY ${id} not found`);
|
||||
}
|
||||
return {
|
||||
buffer: managed.buffer.join(''),
|
||||
isDead: managed.isDead,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a response to a client
|
||||
*/
|
||||
private send(socket: net.Socket, response: DaemonResponse): void {
|
||||
try {
|
||||
socket.write(JSON.stringify(response) + '\n');
|
||||
} catch {
|
||||
// Socket may be closed, ignore
|
||||
console.warn('[PTY Daemon] Failed to send response (socket closed?)');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an error response
|
||||
*/
|
||||
private sendError(socket: net.Socket, error: string, requestId?: string): void {
|
||||
this.send(socket, { type: 'error', error, requestId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup signal handlers for graceful shutdown
|
||||
*/
|
||||
private setupSignalHandlers(): void {
|
||||
const shutdown = (signal: string) => {
|
||||
console.error(`[PTY Daemon] Received ${signal}, shutting down...`);
|
||||
|
||||
// Kill all PTYs
|
||||
this.ptys.forEach((managed) => {
|
||||
if (!managed.isDead) {
|
||||
try {
|
||||
managed.process.kill();
|
||||
} catch (error) {
|
||||
console.error(`[PTY Daemon] Error killing PTY ${managed.id}:`, error);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Close server
|
||||
this.server?.close();
|
||||
|
||||
// Remove socket
|
||||
this.cleanup();
|
||||
|
||||
console.error('[PTY Daemon] Shutdown complete');
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||
|
||||
// Handle uncaught errors
|
||||
process.on('uncaughtException', (error) => {
|
||||
console.error('[PTY Daemon] Uncaught exception:', error);
|
||||
// Don't exit - daemon should be resilient
|
||||
});
|
||||
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
console.error('[PTY Daemon] Unhandled rejection:', reason);
|
||||
// Don't exit - daemon should be resilient
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Start daemon if this file is run directly
|
||||
if (require.main === module) {
|
||||
try {
|
||||
new PtyDaemon();
|
||||
console.error('[PTY Daemon] Running - PID:', process.pid);
|
||||
} catch (error) {
|
||||
console.error('[PTY Daemon] Fatal error:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
export { PtyDaemon };
|
||||
@@ -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,9 +6,10 @@
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import type { TerminalProcess, WindowGetter, SessionCaptureResult } from './types';
|
||||
import type { TerminalProcess, WindowGetter } from './types';
|
||||
import { getTerminalSessionStore, type TerminalSession } from '../terminal-session-store';
|
||||
import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import { debugLog, debugError } from '../../shared/utils/debug-logger';
|
||||
|
||||
/**
|
||||
* Get the Claude project slug from a project path.
|
||||
@@ -27,7 +28,7 @@ export function findMostRecentClaudeSession(projectPath: string): string | null
|
||||
|
||||
try {
|
||||
if (!fs.existsSync(claudeProjectDir)) {
|
||||
console.log('[SessionHandler] Claude project directory not found:', claudeProjectDir);
|
||||
debugLog('[SessionHandler] Claude project directory not found:', claudeProjectDir);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -41,15 +42,15 @@ export function findMostRecentClaudeSession(projectPath: string): string | null
|
||||
.sort((a, b) => b.mtime - a.mtime);
|
||||
|
||||
if (files.length === 0) {
|
||||
console.log('[SessionHandler] No Claude session files found in:', claudeProjectDir);
|
||||
debugLog('[SessionHandler] No Claude session files found in:', claudeProjectDir);
|
||||
return null;
|
||||
}
|
||||
|
||||
const sessionId = files[0].name.replace('.jsonl', '');
|
||||
console.log('[SessionHandler] Found most recent Claude session:', sessionId);
|
||||
debugLog('[SessionHandler] Found most recent Claude session:', sessionId);
|
||||
return sessionId;
|
||||
} catch (error) {
|
||||
console.error('[SessionHandler] Error finding Claude session:', error);
|
||||
debugError('[SessionHandler] Error finding Claude session:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -82,7 +83,7 @@ export function findClaudeSessionAfter(projectPath: string, afterTimestamp: numb
|
||||
|
||||
return files[0].name.replace('.jsonl', '');
|
||||
} catch (error) {
|
||||
console.error('[SessionHandler] Error finding Claude session:', error);
|
||||
debugError('[SessionHandler] Error finding Claude session:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -114,7 +115,7 @@ export function persistSession(terminal: TerminalProcess): void {
|
||||
* Persist all active sessions
|
||||
*/
|
||||
export function persistAllSessions(terminals: Map<string, TerminalProcess>): void {
|
||||
const store = getTerminalSessionStore();
|
||||
const _store = getTerminalSessionStore();
|
||||
|
||||
terminals.forEach((terminal) => {
|
||||
if (terminal.projectPath) {
|
||||
@@ -210,7 +211,7 @@ export function captureClaudeSessionId(
|
||||
|
||||
if (sessionId) {
|
||||
terminal.claudeSessionId = sessionId;
|
||||
console.log('[SessionHandler] Captured Claude session ID from directory:', sessionId);
|
||||
debugLog('[SessionHandler] Captured Claude session ID from directory:', sessionId);
|
||||
|
||||
if (terminal.projectPath) {
|
||||
updateClaudeSessionId(terminal.projectPath, terminalId, sessionId);
|
||||
@@ -223,7 +224,7 @@ export function captureClaudeSessionId(
|
||||
} else if (attempts < maxAttempts) {
|
||||
setTimeout(checkForSession, 1000);
|
||||
} else {
|
||||
console.log('[SessionHandler] Could not capture Claude session ID after', maxAttempts, 'attempts');
|
||||
debugLog('[SessionHandler] Could not capture Claude session ID after', maxAttempts, 'attempts');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
/**
|
||||
* Terminal Session Persistence
|
||||
*
|
||||
* Handles saving and loading terminal session state to disk.
|
||||
* This is the fallback recovery layer when the PTY daemon is not available.
|
||||
*/
|
||||
|
||||
import { app } from 'electron';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import type {
|
||||
TerminalSessionState,
|
||||
TerminalSessionsFile,
|
||||
TerminalRecoveryInfo,
|
||||
} from '../../shared/types/terminal-session';
|
||||
|
||||
const SESSIONS_FILE = path.join(app.getPath('userData'), 'terminal-sessions.json');
|
||||
const BUFFERS_DIR = path.join(app.getPath('userData'), 'terminal-buffers');
|
||||
|
||||
// Session age limit: 7 days
|
||||
const MAX_SESSION_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
class SessionPersistence {
|
||||
private sessions: Map<string, TerminalSessionState> = new Map();
|
||||
private saveTimeout: NodeJS.Timeout | null = null;
|
||||
private isInitialized = false;
|
||||
|
||||
constructor() {
|
||||
this.ensureDirectories();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure required directories exist
|
||||
*/
|
||||
private ensureDirectories(): void {
|
||||
if (!fs.existsSync(BUFFERS_DIR)) {
|
||||
fs.mkdirSync(BUFFERS_DIR, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize and load sessions on app start
|
||||
*/
|
||||
initialize(): TerminalRecoveryInfo {
|
||||
if (this.isInitialized) {
|
||||
return this.getRecoveryInfo();
|
||||
}
|
||||
|
||||
const sessions = this.loadSessions();
|
||||
this.isInitialized = true;
|
||||
|
||||
console.warn(`[SessionPersistence] Initialized with ${sessions.length} sessions`);
|
||||
return this.getRecoveryInfo();
|
||||
}
|
||||
|
||||
/**
|
||||
* Load sessions from disk
|
||||
*/
|
||||
loadSessions(): TerminalSessionState[] {
|
||||
if (!fs.existsSync(SESSIONS_FILE)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const data: TerminalSessionsFile = JSON.parse(
|
||||
fs.readFileSync(SESSIONS_FILE, 'utf8')
|
||||
);
|
||||
|
||||
// Validate version
|
||||
if (data.version !== 2) {
|
||||
console.warn('[SessionPersistence] Incompatible version, starting fresh');
|
||||
return [];
|
||||
}
|
||||
|
||||
// Filter out stale sessions (older than 7 days)
|
||||
const now = Date.now();
|
||||
const validSessions = data.sessions.filter(
|
||||
(s) => now - s.lastActiveAt < MAX_SESSION_AGE_MS
|
||||
);
|
||||
|
||||
// Clean up buffers for stale sessions
|
||||
const staleSessions = data.sessions.filter(
|
||||
(s) => now - s.lastActiveAt >= MAX_SESSION_AGE_MS
|
||||
);
|
||||
staleSessions.forEach((s) => {
|
||||
if (s.bufferFile) {
|
||||
this.deleteBufferFile(s.bufferFile);
|
||||
}
|
||||
});
|
||||
|
||||
validSessions.forEach((s) => this.sessions.set(s.id, s));
|
||||
|
||||
console.warn(
|
||||
`[SessionPersistence] Loaded ${validSessions.length} valid sessions, cleaned ${staleSessions.length} stale sessions`
|
||||
);
|
||||
return validSessions;
|
||||
} catch (error) {
|
||||
console.error('[SessionPersistence] Failed to load sessions:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recovery information for UI
|
||||
*/
|
||||
getRecoveryInfo(): TerminalRecoveryInfo {
|
||||
const sessions = Array.from(this.sessions.values());
|
||||
|
||||
return {
|
||||
totalSessions: sessions.length,
|
||||
recoverableSessions: sessions.filter((s) => s.bufferFile || s.daemonPtyId).length,
|
||||
recoveryMethod: sessions.some((s) => s.daemonPtyId) ? 'daemon' : 'state',
|
||||
sessions: sessions.map((s) => ({
|
||||
id: s.id,
|
||||
title: s.title,
|
||||
isClaudeMode: s.isClaudeMode,
|
||||
lastActiveAt: s.lastActiveAt,
|
||||
hasBuffer: !!s.bufferFile,
|
||||
hasDaemonPty: !!s.daemonPtyId,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Save a session (debounced)
|
||||
*/
|
||||
saveSession(session: TerminalSessionState): void {
|
||||
session.lastActiveAt = Date.now();
|
||||
this.sessions.set(session.id, session);
|
||||
this.scheduleSave();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update session metadata without triggering full save
|
||||
*/
|
||||
updateSessionMetadata(
|
||||
id: string,
|
||||
updates: Partial<Pick<TerminalSessionState, 'title' | 'isClaudeMode' | 'claudeSessionId' | 'daemonPtyId'>>
|
||||
): void {
|
||||
const session = this.sessions.get(id);
|
||||
if (!session) return;
|
||||
|
||||
Object.assign(session, updates);
|
||||
session.lastActiveAt = Date.now();
|
||||
this.scheduleSave();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a session by ID
|
||||
*/
|
||||
getSession(id: string): TerminalSessionState | undefined {
|
||||
return this.sessions.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all sessions
|
||||
*/
|
||||
getAllSessions(): TerminalSessionState[] {
|
||||
return Array.from(this.sessions.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a session
|
||||
*/
|
||||
removeSession(id: string): void {
|
||||
const session = this.sessions.get(id);
|
||||
if (session?.bufferFile) {
|
||||
this.deleteBufferFile(session.bufferFile);
|
||||
}
|
||||
this.sessions.delete(id);
|
||||
this.scheduleSave();
|
||||
}
|
||||
|
||||
/**
|
||||
* Save buffer content to disk
|
||||
*/
|
||||
saveBuffer(sessionId: string, serializedBuffer: string): void {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) {
|
||||
console.warn(`[SessionPersistence] Cannot save buffer - session ${sessionId} not found`);
|
||||
return;
|
||||
}
|
||||
|
||||
const bufferFile = `buffer-${sessionId}.txt`;
|
||||
const bufferPath = path.join(BUFFERS_DIR, bufferFile);
|
||||
|
||||
try {
|
||||
fs.writeFileSync(bufferPath, serializedBuffer, 'utf8');
|
||||
session.bufferFile = bufferFile;
|
||||
this.saveSession(session);
|
||||
console.warn(`[SessionPersistence] Saved buffer for session ${sessionId} (${serializedBuffer.length} bytes)`);
|
||||
} catch (error) {
|
||||
console.error(`[SessionPersistence] Failed to save buffer for ${sessionId}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load buffer content from disk
|
||||
*/
|
||||
loadBuffer(sessionId: string): string | null {
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session?.bufferFile) return null;
|
||||
|
||||
const bufferPath = path.join(BUFFERS_DIR, session.bufferFile);
|
||||
if (!fs.existsSync(bufferPath)) {
|
||||
console.warn(`[SessionPersistence] Buffer file missing: ${session.bufferFile}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return fs.readFileSync(bufferPath, 'utf8');
|
||||
} catch (error) {
|
||||
console.error(`[SessionPersistence] Failed to load buffer for ${sessionId}:`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a buffer file
|
||||
*/
|
||||
private deleteBufferFile(bufferFile: string): void {
|
||||
const bufferPath = path.join(BUFFERS_DIR, bufferFile);
|
||||
if (fs.existsSync(bufferPath)) {
|
||||
try {
|
||||
fs.unlinkSync(bufferPath);
|
||||
console.warn(`[SessionPersistence] Deleted buffer file: ${bufferFile}`);
|
||||
} catch (error) {
|
||||
console.error(`[SessionPersistence] Failed to delete buffer file ${bufferFile}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Debounced save to prevent excessive disk I/O
|
||||
*/
|
||||
private scheduleSave(): void {
|
||||
if (this.saveTimeout) {
|
||||
clearTimeout(this.saveTimeout);
|
||||
}
|
||||
|
||||
this.saveTimeout = setTimeout(() => {
|
||||
this.saveToDisk();
|
||||
}, 1000); // 1 second debounce
|
||||
}
|
||||
|
||||
/**
|
||||
* Immediate save (call before app quit)
|
||||
*/
|
||||
saveNow(): void {
|
||||
if (this.saveTimeout) {
|
||||
clearTimeout(this.saveTimeout);
|
||||
this.saveTimeout = null;
|
||||
}
|
||||
this.saveToDisk();
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform the actual disk write
|
||||
*/
|
||||
private saveToDisk(): void {
|
||||
const data: TerminalSessionsFile = {
|
||||
version: 2,
|
||||
savedAt: Date.now(),
|
||||
sessions: Array.from(this.sessions.values()),
|
||||
};
|
||||
|
||||
try {
|
||||
fs.writeFileSync(SESSIONS_FILE, JSON.stringify(data, null, 2), 'utf8');
|
||||
console.warn(`[SessionPersistence] Saved ${data.sessions.length} sessions to disk`);
|
||||
} catch (error) {
|
||||
console.error('[SessionPersistence] Failed to save sessions:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up old buffer files not referenced by any session
|
||||
*/
|
||||
cleanupOrphanedBuffers(): void {
|
||||
if (!fs.existsSync(BUFFERS_DIR)) return;
|
||||
|
||||
try {
|
||||
const bufferFiles = fs.readdirSync(BUFFERS_DIR);
|
||||
const referencedBuffers = new Set(
|
||||
Array.from(this.sessions.values())
|
||||
.map((s) => s.bufferFile)
|
||||
.filter((f): f is string => !!f)
|
||||
);
|
||||
|
||||
let cleanedCount = 0;
|
||||
for (const file of bufferFiles) {
|
||||
if (!referencedBuffers.has(file)) {
|
||||
const filePath = path.join(BUFFERS_DIR, file);
|
||||
fs.unlinkSync(filePath);
|
||||
cleanedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if (cleanedCount > 0) {
|
||||
console.warn(`[SessionPersistence] Cleaned up ${cleanedCount} orphaned buffer files`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[SessionPersistence] Failed to cleanup orphaned buffers:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton instance
|
||||
export const sessionPersistence = new SessionPersistence();
|
||||
|
||||
// Hook into app lifecycle
|
||||
app.on('before-quit', () => {
|
||||
console.warn('[SessionPersistence] App quitting, saving sessions...');
|
||||
sessionPersistence.saveNow();
|
||||
});
|
||||
|
||||
app.on('will-quit', () => {
|
||||
sessionPersistence.saveNow();
|
||||
});
|
||||
|
||||
// Cleanup orphaned buffers on startup (after initial load)
|
||||
app.whenReady().then(() => {
|
||||
setTimeout(() => {
|
||||
sessionPersistence.cleanupOrphanedBuffers();
|
||||
}, 5000); // Wait 5 seconds after app ready
|
||||
});
|
||||
@@ -9,12 +9,12 @@ import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import type { TerminalSession } from '../terminal-session-store';
|
||||
import * as PtyManager from './pty-manager';
|
||||
import * as SessionHandler from './session-handler';
|
||||
import * as TerminalEventHandler from './terminal-event-handler';
|
||||
import type {
|
||||
TerminalProcess,
|
||||
WindowGetter,
|
||||
TerminalOperationResult
|
||||
} from './types';
|
||||
import { debugLog, debugError } from '../../shared/utils/debug-logger';
|
||||
|
||||
/**
|
||||
* Options for terminal restoration
|
||||
@@ -40,10 +40,10 @@ export async function createTerminal(
|
||||
): Promise<TerminalOperationResult> {
|
||||
const { id, cwd, cols = 80, rows = 24, projectPath } = options;
|
||||
|
||||
console.log('[TerminalLifecycle] Creating terminal:', { id, cwd, cols, rows, projectPath });
|
||||
debugLog('[TerminalLifecycle] Creating terminal:', { id, cwd, cols, rows, projectPath });
|
||||
|
||||
if (terminals.has(id)) {
|
||||
console.log('[TerminalLifecycle] Terminal already exists, returning success:', id);
|
||||
debugLog('[TerminalLifecycle] Terminal already exists, returning success:', id);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ export async function createTerminal(
|
||||
const profileEnv = PtyManager.getActiveProfileEnv();
|
||||
|
||||
if (profileEnv.CLAUDE_CODE_OAUTH_TOKEN) {
|
||||
console.log('[TerminalLifecycle] Injecting OAuth token from active profile');
|
||||
debugLog('[TerminalLifecycle] Injecting OAuth token from active profile');
|
||||
}
|
||||
|
||||
const ptyProcess = PtyManager.spawnPtyProcess(
|
||||
@@ -61,7 +61,7 @@ export async function createTerminal(
|
||||
profileEnv
|
||||
);
|
||||
|
||||
console.log('[TerminalLifecycle] PTY process spawned, pid:', ptyProcess.pid);
|
||||
debugLog('[TerminalLifecycle] PTY process spawned, pid:', ptyProcess.pid);
|
||||
|
||||
const terminalCwd = cwd || os.homedir();
|
||||
const terminal: TerminalProcess = {
|
||||
@@ -88,10 +88,10 @@ export async function createTerminal(
|
||||
SessionHandler.persistSession(terminal);
|
||||
}
|
||||
|
||||
console.log('[TerminalLifecycle] Terminal created successfully:', id);
|
||||
debugLog('[TerminalLifecycle] Terminal created successfully:', id);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('[TerminalLifecycle] Error creating terminal:', error);
|
||||
debugError('[TerminalLifecycle] Error creating terminal:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to create terminal',
|
||||
@@ -111,7 +111,7 @@ export async function restoreTerminal(
|
||||
cols = 80,
|
||||
rows = 24
|
||||
): Promise<TerminalOperationResult> {
|
||||
console.log('[TerminalLifecycle] Restoring terminal session:', session.id, 'Claude mode:', session.isClaudeMode);
|
||||
debugLog('[TerminalLifecycle] Restoring terminal session:', session.id, 'Claude mode:', session.isClaudeMode);
|
||||
|
||||
const result = await createTerminal(
|
||||
{
|
||||
@@ -137,34 +137,17 @@ export async function restoreTerminal(
|
||||
|
||||
terminal.title = session.title;
|
||||
|
||||
if (session.isClaudeMode && options.resumeClaudeSession) {
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
// Restore Claude mode state without sending resume commands
|
||||
// The PTY daemon keeps processes alive, so we just need to reconnect to the existing session
|
||||
if (session.isClaudeMode) {
|
||||
terminal.isClaudeMode = true;
|
||||
terminal.claudeSessionId = session.claudeSessionId;
|
||||
|
||||
const projectDir = session.cwd || session.projectPath;
|
||||
const startTime = Date.now();
|
||||
const clearCmd = process.platform === 'win32' ? 'cls' : 'clear';
|
||||
|
||||
let resumeCommand: string;
|
||||
if (session.claudeSessionId) {
|
||||
resumeCommand = `${clearCmd} && cd "${projectDir}" && claude --resume "${session.claudeSessionId}"`;
|
||||
console.log('[TerminalLifecycle] Resuming Claude with session ID:', session.claudeSessionId, 'in', projectDir);
|
||||
} else {
|
||||
resumeCommand = `${clearCmd} && cd "${projectDir}" && claude --resume`;
|
||||
console.log('[TerminalLifecycle] Opening Claude session picker in', projectDir);
|
||||
}
|
||||
|
||||
terminal.pty.write(`${resumeCommand}\r`);
|
||||
debugLog('[TerminalLifecycle] Restored Claude mode state for session:', session.id, 'sessionId:', session.claudeSessionId);
|
||||
|
||||
const win = getWindow();
|
||||
if (win) {
|
||||
win.webContents.send(IPC_CHANNELS.TERMINAL_TITLE_CHANGE, session.id, 'Claude');
|
||||
}
|
||||
|
||||
if (!session.claudeSessionId && projectDir) {
|
||||
options.captureSessionId(session.id, projectDir, startTime);
|
||||
win.webContents.send(IPC_CHANNELS.TERMINAL_TITLE_CHANGE, session.id, session.title);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,12 +221,14 @@ export async function destroyAllTerminals(
|
||||
|
||||
/**
|
||||
* Handle terminal exit event
|
||||
* Note: We don't remove sessions here because terminal exit might be due to app shutdown.
|
||||
* Sessions are only removed when explicitly destroyed by user action via destroyTerminal().
|
||||
*/
|
||||
function handleTerminalExit(
|
||||
terminal: TerminalProcess,
|
||||
terminals: Map<string, TerminalProcess>
|
||||
_terminal: TerminalProcess,
|
||||
_terminals: Map<string, TerminalProcess>
|
||||
): void {
|
||||
SessionHandler.removePersistedSession(terminal);
|
||||
// Don't remove session - let it persist for restoration
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,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'));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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,7 @@ 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 { AppUpdateAPI, createAppUpdateAPI } from './app-update-api';
|
||||
|
||||
export interface ElectronAPI extends
|
||||
ProjectAPI,
|
||||
@@ -13,7 +14,8 @@ export interface ElectronAPI extends
|
||||
SettingsAPI,
|
||||
FileAPI,
|
||||
AgentAPI,
|
||||
IdeationAPI {}
|
||||
IdeationAPI,
|
||||
AppUpdateAPI {}
|
||||
|
||||
export const createElectronAPI = (): ElectronAPI => ({
|
||||
...createProjectAPI(),
|
||||
@@ -22,7 +24,8 @@ export const createElectronAPI = (): ElectronAPI => ({
|
||||
...createSettingsAPI(),
|
||||
...createFileAPI(),
|
||||
...createAgentAPI(),
|
||||
...createIdeationAPI()
|
||||
...createIdeationAPI(),
|
||||
...createAppUpdateAPI()
|
||||
});
|
||||
|
||||
// Export individual API creators for potential use in tests or specialized contexts
|
||||
@@ -33,7 +36,8 @@ export {
|
||||
createSettingsAPI,
|
||||
createFileAPI,
|
||||
createAgentAPI,
|
||||
createIdeationAPI
|
||||
createIdeationAPI,
|
||||
createAppUpdateAPI
|
||||
};
|
||||
|
||||
export type {
|
||||
@@ -43,5 +47,6 @@ export type {
|
||||
SettingsAPI,
|
||||
FileAPI,
|
||||
AgentAPI,
|
||||
IdeationAPI
|
||||
IdeationAPI,
|
||||
AppUpdateAPI
|
||||
};
|
||||
|
||||
@@ -32,6 +32,10 @@ export interface ChangelogAPI {
|
||||
projectId: string,
|
||||
taskIds: string[]
|
||||
) => Promise<IPCResult<{ version: string; reason: string }>>;
|
||||
suggestChangelogVersionFromCommits: (
|
||||
projectId: string,
|
||||
commits: GitCommit[]
|
||||
) => Promise<IPCResult<{ version: string; reason: string }>>;
|
||||
getChangelogBranches: (projectId: string) => Promise<IPCResult<GitBranchInfo[]>>;
|
||||
getChangelogTags: (projectId: string) => Promise<IPCResult<GitTagInfo[]>>;
|
||||
getChangelogCommitsPreview: (
|
||||
@@ -83,6 +87,12 @@ export const createChangelogAPI = (): ChangelogAPI => ({
|
||||
): Promise<IPCResult<{ version: string; reason: string }>> =>
|
||||
invokeIpc(IPC_CHANNELS.CHANGELOG_SUGGEST_VERSION, projectId, taskIds),
|
||||
|
||||
suggestChangelogVersionFromCommits: (
|
||||
projectId: string,
|
||||
commits: GitCommit[]
|
||||
): Promise<IPCResult<{ version: string; reason: string }>> =>
|
||||
invokeIpc(IPC_CHANNELS.CHANGELOG_SUGGEST_VERSION_FROM_COMMITS, projectId, commits),
|
||||
|
||||
getChangelogBranches: (projectId: string): Promise<IPCResult<GitBranchInfo[]>> =>
|
||||
invokeIpc(IPC_CHANNELS.CHANGELOG_GET_BRANCHES, projectId),
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@ import type {
|
||||
GitHubImportResult,
|
||||
GitHubInvestigationStatus,
|
||||
GitHubInvestigationResult,
|
||||
IPCResult
|
||||
IPCResult,
|
||||
VersionSuggestion
|
||||
} from '../../../shared/types';
|
||||
import { createIpcListener, invokeIpc, sendIpc, IpcListenerCleanup } from './ipc-utils';
|
||||
|
||||
@@ -28,6 +29,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 }>>;
|
||||
@@ -79,6 +83,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),
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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>>;
|
||||
@@ -67,6 +63,13 @@ export interface ProjectAPI {
|
||||
falkorDbUri: string,
|
||||
openAiApiKey: string
|
||||
) => Promise<IPCResult<GraphitiConnectionTestResult>>;
|
||||
|
||||
// Git Operations
|
||||
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 => ({
|
||||
@@ -165,5 +168,21 @@ export const createProjectAPI = (): ProjectAPI => ({
|
||||
falkorDbUri: string,
|
||||
openAiApiKey: string
|
||||
): Promise<IPCResult<GraphitiConnectionTestResult>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GRAPHITI_TEST_CONNECTION, falkorDbUri, openAiApiKey)
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GRAPHITI_TEST_CONNECTION, falkorDbUri, openAiApiKey),
|
||||
|
||||
// Git Operations
|
||||
getGitBranches: (projectPath: string): Promise<IPCResult<string[]>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_GET_BRANCHES, projectPath),
|
||||
|
||||
getCurrentGitBranch: (projectPath: string): Promise<IPCResult<string | null>> =>
|
||||
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),
|
||||
|
||||
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>;
|
||||
@@ -63,6 +72,11 @@ export interface TerminalAPI {
|
||||
getBestAvailableProfile: (excludeProfileId?: string) => Promise<IPCResult<import('../../shared/types').ClaudeProfile | null>>;
|
||||
onSDKRateLimit: (callback: (info: import('../../shared/types').SDKRateLimitInfo) => void) => () => void;
|
||||
retryWithProfile: (request: import('../../shared/types').RetryWithProfileRequest) => Promise<IPCResult>;
|
||||
|
||||
// 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: ProactiveSwapNotification) => void) => () => void;
|
||||
}
|
||||
|
||||
export const createTerminalAPI = (): TerminalAPI => ({
|
||||
@@ -267,5 +281,36 @@ export const createTerminalAPI = (): TerminalAPI => ({
|
||||
},
|
||||
|
||||
retryWithProfile: (request: import('../../shared/types').RetryWithProfileRequest): Promise<IPCResult> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.CLAUDE_RETRY_WITH_PROFILE, request)
|
||||
ipcRenderer.invoke(IPC_CHANNELS.CLAUDE_RETRY_WITH_PROFILE, request),
|
||||
|
||||
// Usage Monitoring (Proactive Account Switching)
|
||||
requestUsageUpdate: (): Promise<IPCResult<import('../../shared/types').ClaudeUsageSnapshot | null>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.USAGE_REQUEST),
|
||||
|
||||
onUsageUpdated: (
|
||||
callback: (usage: import('../../shared/types').ClaudeUsageSnapshot) => void
|
||||
): (() => void) => {
|
||||
const handler = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
usage: import('../../shared/types').ClaudeUsageSnapshot
|
||||
): void => {
|
||||
callback(usage);
|
||||
};
|
||||
ipcRenderer.on(IPC_CHANNELS.USAGE_UPDATED, handler);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(IPC_CHANNELS.USAGE_UPDATED, handler);
|
||||
};
|
||||
},
|
||||
|
||||
onProactiveSwapNotification: (
|
||||
callback: (notification: ProactiveSwapNotification) => void
|
||||
): (() => void) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, notification: ProactiveSwapNotification): void => {
|
||||
callback(notification);
|
||||
};
|
||||
ipcRenderer.on(IPC_CHANNELS.PROACTIVE_SWAP_NOTIFICATION, handler);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(IPC_CHANNELS.PROACTIVE_SWAP_NOTIFICATION, handler);
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -34,6 +34,9 @@ import { WelcomeScreen } from './components/WelcomeScreen';
|
||||
import { RateLimitModal } from './components/RateLimitModal';
|
||||
import { SDKRateLimitModal } from './components/SDKRateLimitModal';
|
||||
import { OnboardingWizard } from './components/onboarding';
|
||||
import { AppUpdateNotification } from './components/AppUpdateNotification';
|
||||
import { UsageIndicator } from './components/UsageIndicator';
|
||||
import { ProactiveSwapListener } from './components/ProactiveSwapListener';
|
||||
import { useProjectStore, loadProjects, addProject, initializeProject } from './stores/project-store';
|
||||
import { useTaskStore, loadTasks } from './stores/task-store';
|
||||
import { useSettingsStore, loadSettings } from './stores/settings-store';
|
||||
@@ -111,14 +114,28 @@ export function App() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Listen for app updates - auto-open settings to 'updates' section when update is ready
|
||||
useEffect(() => {
|
||||
// When an update is downloaded and ready to install, open settings to updates section
|
||||
const cleanupDownloaded = window.electronAPI.onAppUpdateDownloaded(() => {
|
||||
console.warn('[App] Update downloaded, opening settings to updates section');
|
||||
setSettingsInitialSection('updates');
|
||||
setIsSettingsDialogOpen(true);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cleanupDownloaded();
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Check if selected project needs initialization (e.g., .auto-claude folder was deleted)
|
||||
useEffect(() => {
|
||||
if (selectedProject && !selectedProject.autoBuildPath && !showInitDialog && skippedInitProjectId !== selectedProject.id) {
|
||||
if (selectedProject && !selectedProject.autoBuildPath && skippedInitProjectId !== selectedProject.id) {
|
||||
// Project exists but isn't initialized - show init dialog
|
||||
setPendingProject(selectedProject);
|
||||
setShowInitDialog(true);
|
||||
}
|
||||
}, [selectedProject, showInitDialog, skippedInitProjectId]);
|
||||
}, [selectedProject, skippedInitProjectId]);
|
||||
|
||||
// Load tasks when project changes
|
||||
useEffect(() => {
|
||||
@@ -189,7 +206,7 @@ export function App() {
|
||||
setSelectedTask(updatedTask);
|
||||
}
|
||||
}
|
||||
}, [tasks, selectedTask?.id, selectedTask?.specId]);
|
||||
}, [tasks, selectedTask?.id, selectedTask?.specId, selectedTask]);
|
||||
|
||||
const handleTaskClick = (task: Task) => {
|
||||
setSelectedTask(task);
|
||||
@@ -250,6 +267,7 @@ export function App() {
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<ProactiveSwapListener />
|
||||
<div className="flex h-screen bg-background">
|
||||
{/* Sidebar */}
|
||||
<Sidebar
|
||||
@@ -273,7 +291,8 @@ export function App() {
|
||||
)}
|
||||
</div>
|
||||
{selectedProject && (
|
||||
<div className="electron-no-drag">
|
||||
<div className="electron-no-drag flex items-center gap-3">
|
||||
<UsageIndicator />
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
@@ -397,8 +416,6 @@ export function App() {
|
||||
<Dialog open={showInitDialog} onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
handleSkipInit();
|
||||
} else {
|
||||
setShowInitDialog(true);
|
||||
}
|
||||
}}>
|
||||
<DialogContent>
|
||||
@@ -477,6 +494,9 @@ export function App() {
|
||||
setIsSettingsDialogOpen(true);
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* App Update Notification - shows when new app version is available */}
|
||||
<AppUpdateNotification />
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
/**
|
||||
* Unit tests for OAuthStep component
|
||||
* Tests profile management, authentication state display, and user interactions
|
||||
*
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import type { ClaudeProfile, ClaudeProfileSettings, ElectronAPI } from '../../shared/types';
|
||||
|
||||
// Import browser mock to get full ElectronAPI structure
|
||||
import '../lib/browser-mock';
|
||||
|
||||
// Helper to create test profiles
|
||||
function createTestProfile(overrides: Partial<ClaudeProfile> = {}): ClaudeProfile {
|
||||
return {
|
||||
id: `profile-${Date.now()}-${Math.random().toString(36).substring(7)}`,
|
||||
name: 'Test Profile',
|
||||
isDefault: false,
|
||||
createdAt: new Date(),
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
// Mock functions
|
||||
const mockGetClaudeProfiles = vi.fn();
|
||||
const mockSaveClaudeProfile = vi.fn();
|
||||
const mockDeleteClaudeProfile = vi.fn();
|
||||
const mockRenameClaudeProfile = vi.fn();
|
||||
const mockSetActiveClaudeProfile = vi.fn();
|
||||
const mockInitializeClaudeProfile = vi.fn();
|
||||
const mockSetClaudeProfileToken = vi.fn();
|
||||
const mockOnTerminalOAuthToken = vi.fn();
|
||||
|
||||
describe('OAuthStep Profile Management Logic', () => {
|
||||
beforeEach(() => {
|
||||
// Reset all mocks
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Setup window.electronAPI mocks
|
||||
if (window.electronAPI) {
|
||||
window.electronAPI.getClaudeProfiles = mockGetClaudeProfiles;
|
||||
window.electronAPI.saveClaudeProfile = mockSaveClaudeProfile;
|
||||
window.electronAPI.deleteClaudeProfile = mockDeleteClaudeProfile;
|
||||
window.electronAPI.renameClaudeProfile = mockRenameClaudeProfile;
|
||||
window.electronAPI.setActiveClaudeProfile = mockSetActiveClaudeProfile;
|
||||
window.electronAPI.initializeClaudeProfile = mockInitializeClaudeProfile;
|
||||
window.electronAPI.setClaudeProfileToken = mockSetClaudeProfileToken;
|
||||
window.electronAPI.onTerminalOAuthToken = mockOnTerminalOAuthToken;
|
||||
}
|
||||
|
||||
// Default mock implementations
|
||||
mockGetClaudeProfiles.mockResolvedValue({
|
||||
success: true,
|
||||
data: { profiles: [], activeProfileId: 'default' }
|
||||
});
|
||||
mockOnTerminalOAuthToken.mockReturnValue(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Profile List Display', () => {
|
||||
it('should handle empty profile list', async () => {
|
||||
mockGetClaudeProfiles.mockResolvedValue({
|
||||
success: true,
|
||||
data: { profiles: [], activeProfileId: null }
|
||||
});
|
||||
|
||||
const result = await window.electronAPI.getClaudeProfiles();
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.data?.profiles).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should handle profile list with multiple profiles', async () => {
|
||||
const profiles = [
|
||||
createTestProfile({ id: 'profile-1', name: 'Work' }),
|
||||
createTestProfile({ id: 'profile-2', name: 'Personal', oauthToken: 'sk-ant-oat01-test' })
|
||||
];
|
||||
|
||||
mockGetClaudeProfiles.mockResolvedValue({
|
||||
success: true,
|
||||
data: { profiles, activeProfileId: 'profile-1' }
|
||||
});
|
||||
|
||||
const result = await window.electronAPI.getClaudeProfiles();
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.data?.profiles).toHaveLength(2);
|
||||
expect(result.data?.activeProfileId).toBe('profile-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Authentication State Display', () => {
|
||||
it('should identify profile as authenticated when oauthToken is present', () => {
|
||||
const profile = createTestProfile({ oauthToken: 'sk-ant-oat01-test-token' });
|
||||
const isAuthenticated = !!(profile.oauthToken || (profile.isDefault && profile.configDir));
|
||||
expect(isAuthenticated).toBe(true);
|
||||
});
|
||||
|
||||
it('should identify profile as authenticated when it is default with configDir', () => {
|
||||
const profile = createTestProfile({ isDefault: true, configDir: '~/.claude' });
|
||||
const isAuthenticated = !!(profile.oauthToken || (profile.isDefault && profile.configDir));
|
||||
expect(isAuthenticated).toBe(true);
|
||||
});
|
||||
|
||||
it('should identify profile as needing auth when no token and not default', () => {
|
||||
const profile = createTestProfile({ isDefault: false, oauthToken: undefined });
|
||||
const isAuthenticated = !!(profile.oauthToken || (profile.isDefault && profile.configDir));
|
||||
expect(isAuthenticated).toBe(false);
|
||||
});
|
||||
|
||||
it('should identify profile as needing auth when default but no configDir', () => {
|
||||
const profile = createTestProfile({ isDefault: true, configDir: undefined });
|
||||
const isAuthenticated = !!(profile.oauthToken || (profile.isDefault && profile.configDir));
|
||||
expect(isAuthenticated).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Add Profile Flow', () => {
|
||||
it('should call saveClaudeProfile with correct parameters', async () => {
|
||||
const newProfile = {
|
||||
id: 'profile-new',
|
||||
name: 'New Profile',
|
||||
configDir: '~/.claude-profiles/new-profile',
|
||||
isDefault: false,
|
||||
createdAt: new Date()
|
||||
};
|
||||
|
||||
mockSaveClaudeProfile.mockResolvedValue({
|
||||
success: true,
|
||||
data: newProfile
|
||||
});
|
||||
|
||||
const result = await window.electronAPI.saveClaudeProfile(newProfile);
|
||||
expect(mockSaveClaudeProfile).toHaveBeenCalledWith(newProfile);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should call initializeClaudeProfile after saving profile', async () => {
|
||||
const newProfile = {
|
||||
id: 'profile-new',
|
||||
name: 'New Profile',
|
||||
configDir: '~/.claude-profiles/new-profile',
|
||||
isDefault: false,
|
||||
createdAt: new Date()
|
||||
};
|
||||
|
||||
mockSaveClaudeProfile.mockResolvedValue({
|
||||
success: true,
|
||||
data: newProfile
|
||||
});
|
||||
|
||||
mockInitializeClaudeProfile.mockResolvedValue({ success: true });
|
||||
|
||||
await window.electronAPI.saveClaudeProfile(newProfile);
|
||||
await window.electronAPI.initializeClaudeProfile(newProfile.id);
|
||||
|
||||
expect(mockSaveClaudeProfile).toHaveBeenCalled();
|
||||
expect(mockInitializeClaudeProfile).toHaveBeenCalledWith(newProfile.id);
|
||||
});
|
||||
|
||||
it('should generate profile slug from name', () => {
|
||||
const profileName = 'Work Account';
|
||||
const profileSlug = profileName.toLowerCase().replace(/\s+/g, '-');
|
||||
expect(profileSlug).toBe('work-account');
|
||||
});
|
||||
|
||||
it('should handle saveClaudeProfile failure', async () => {
|
||||
mockSaveClaudeProfile.mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Failed to save profile'
|
||||
});
|
||||
|
||||
const result = await window.electronAPI.saveClaudeProfile({
|
||||
id: 'profile-fail',
|
||||
name: 'Failing Profile',
|
||||
isDefault: false,
|
||||
createdAt: new Date()
|
||||
});
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('Failed to save profile');
|
||||
});
|
||||
});
|
||||
|
||||
describe('OAuth Authentication Flow', () => {
|
||||
it('should call initializeClaudeProfile to trigger OAuth flow', async () => {
|
||||
mockInitializeClaudeProfile.mockResolvedValue({ success: true });
|
||||
|
||||
const profileId = 'profile-1';
|
||||
const result = await window.electronAPI.initializeClaudeProfile(profileId);
|
||||
|
||||
expect(mockInitializeClaudeProfile).toHaveBeenCalledWith(profileId);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle initializeClaudeProfile failure', async () => {
|
||||
mockInitializeClaudeProfile.mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Browser failed to open'
|
||||
});
|
||||
|
||||
const result = await window.electronAPI.initializeClaudeProfile('profile-1');
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('should register OAuth token callback', () => {
|
||||
const callback = vi.fn();
|
||||
mockOnTerminalOAuthToken.mockReturnValue(() => {});
|
||||
|
||||
const unsubscribe = window.electronAPI.onTerminalOAuthToken(callback);
|
||||
expect(mockOnTerminalOAuthToken).toHaveBeenCalledWith(callback);
|
||||
expect(typeof unsubscribe).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Set Active Profile', () => {
|
||||
it('should call setActiveClaudeProfile with correct profileId', async () => {
|
||||
mockSetActiveClaudeProfile.mockResolvedValue({ success: true });
|
||||
|
||||
const profileId = 'profile-2';
|
||||
const result = await window.electronAPI.setActiveClaudeProfile(profileId);
|
||||
|
||||
expect(mockSetActiveClaudeProfile).toHaveBeenCalledWith(profileId);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle setActiveClaudeProfile failure', async () => {
|
||||
mockSetActiveClaudeProfile.mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Profile not found'
|
||||
});
|
||||
|
||||
const result = await window.electronAPI.setActiveClaudeProfile('invalid-id');
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Delete Profile', () => {
|
||||
it('should call deleteClaudeProfile with correct profileId', async () => {
|
||||
mockDeleteClaudeProfile.mockResolvedValue({ success: true });
|
||||
|
||||
const profileId = 'profile-to-delete';
|
||||
const result = await window.electronAPI.deleteClaudeProfile(profileId);
|
||||
|
||||
expect(mockDeleteClaudeProfile).toHaveBeenCalledWith(profileId);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Rename Profile', () => {
|
||||
it('should call renameClaudeProfile with correct parameters', async () => {
|
||||
mockRenameClaudeProfile.mockResolvedValue({ success: true });
|
||||
|
||||
const profileId = 'profile-1';
|
||||
const newName = 'Updated Profile Name';
|
||||
const result = await window.electronAPI.renameClaudeProfile(profileId, newName);
|
||||
|
||||
expect(mockRenameClaudeProfile).toHaveBeenCalledWith(profileId, newName);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Manual Token Entry', () => {
|
||||
it('should call setClaudeProfileToken with token and email', async () => {
|
||||
mockSetClaudeProfileToken.mockResolvedValue({ success: true });
|
||||
|
||||
const profileId = 'profile-1';
|
||||
const token = 'sk-ant-oat01-manual-token';
|
||||
const email = 'user@example.com';
|
||||
|
||||
const result = await window.electronAPI.setClaudeProfileToken(profileId, token, email);
|
||||
|
||||
expect(mockSetClaudeProfileToken).toHaveBeenCalledWith(profileId, token, email);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should call setClaudeProfileToken with token only (no email)', async () => {
|
||||
mockSetClaudeProfileToken.mockResolvedValue({ success: true });
|
||||
|
||||
const profileId = 'profile-1';
|
||||
const token = 'sk-ant-oat01-manual-token';
|
||||
|
||||
const result = await window.electronAPI.setClaudeProfileToken(profileId, token, undefined);
|
||||
|
||||
expect(mockSetClaudeProfileToken).toHaveBeenCalledWith(profileId, token, undefined);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle setClaudeProfileToken failure', async () => {
|
||||
mockSetClaudeProfileToken.mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Invalid token format'
|
||||
});
|
||||
|
||||
const result = await window.electronAPI.setClaudeProfileToken(
|
||||
'profile-1',
|
||||
'invalid-token',
|
||||
undefined
|
||||
);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('Invalid token format');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Continue Button State', () => {
|
||||
it('should enable Continue when at least one profile is authenticated', () => {
|
||||
const profiles: ClaudeProfile[] = [
|
||||
createTestProfile({ id: 'p1', oauthToken: undefined }),
|
||||
createTestProfile({ id: 'p2', oauthToken: 'sk-ant-oat01-token' })
|
||||
];
|
||||
|
||||
const hasAuthenticatedProfile = profiles.some(
|
||||
(profile) => profile.oauthToken || (profile.isDefault && profile.configDir)
|
||||
);
|
||||
|
||||
expect(hasAuthenticatedProfile).toBe(true);
|
||||
});
|
||||
|
||||
it('should disable Continue when no profiles are authenticated', () => {
|
||||
const profiles: ClaudeProfile[] = [
|
||||
createTestProfile({ id: 'p1', oauthToken: undefined }),
|
||||
createTestProfile({ id: 'p2', oauthToken: undefined })
|
||||
];
|
||||
|
||||
const hasAuthenticatedProfile = profiles.some(
|
||||
(profile) => profile.oauthToken || (profile.isDefault && profile.configDir)
|
||||
);
|
||||
|
||||
expect(hasAuthenticatedProfile).toBe(false);
|
||||
});
|
||||
|
||||
it('should disable Continue when no profiles exist', () => {
|
||||
const profiles: ClaudeProfile[] = [];
|
||||
|
||||
const hasAuthenticatedProfile = profiles.some(
|
||||
(profile) => profile.oauthToken || (profile.isDefault && profile.configDir)
|
||||
);
|
||||
|
||||
expect(hasAuthenticatedProfile).toBe(false);
|
||||
});
|
||||
|
||||
it('should enable Continue with default profile with configDir', () => {
|
||||
const profiles: ClaudeProfile[] = [
|
||||
createTestProfile({ id: 'default', isDefault: true, configDir: '~/.claude' })
|
||||
];
|
||||
|
||||
const hasAuthenticatedProfile = profiles.some(
|
||||
(profile) => profile.oauthToken || (profile.isDefault && profile.configDir)
|
||||
);
|
||||
|
||||
expect(hasAuthenticatedProfile).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Profile Name Validation', () => {
|
||||
it('should require non-empty profile name', () => {
|
||||
const newProfileName = '';
|
||||
const isValid = newProfileName.trim().length > 0;
|
||||
expect(isValid).toBe(false);
|
||||
});
|
||||
|
||||
it('should trim whitespace from profile name', () => {
|
||||
const newProfileName = ' Work ';
|
||||
const isValid = newProfileName.trim().length > 0;
|
||||
expect(isValid).toBe(true);
|
||||
expect(newProfileName.trim()).toBe('Work');
|
||||
});
|
||||
|
||||
it('should reject whitespace-only profile name', () => {
|
||||
const newProfileName = ' ';
|
||||
const isValid = newProfileName.trim().length > 0;
|
||||
expect(isValid).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
it('should handle getClaudeProfiles failure gracefully', async () => {
|
||||
mockGetClaudeProfiles.mockRejectedValue(new Error('Network error'));
|
||||
|
||||
await expect(window.electronAPI.getClaudeProfiles()).rejects.toThrow('Network error');
|
||||
});
|
||||
|
||||
it('should handle API returning unsuccessful response', async () => {
|
||||
mockGetClaudeProfiles.mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Database connection failed'
|
||||
});
|
||||
|
||||
const result = await window.electronAPI.getClaudeProfiles();
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('Database connection failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Active Profile Highlighting', () => {
|
||||
it('should identify active profile correctly', () => {
|
||||
const profiles: ClaudeProfile[] = [
|
||||
createTestProfile({ id: 'p1', name: 'Work' }),
|
||||
createTestProfile({ id: 'p2', name: 'Personal' })
|
||||
];
|
||||
const activeProfileId = 'p2';
|
||||
|
||||
const activeProfile = profiles.find((p) => p.id === activeProfileId);
|
||||
expect(activeProfile?.name).toBe('Personal');
|
||||
});
|
||||
|
||||
it('should handle when no profile is active', () => {
|
||||
const profiles: ClaudeProfile[] = [
|
||||
createTestProfile({ id: 'p1', name: 'Work' })
|
||||
];
|
||||
const activeProfileId: string | null = null;
|
||||
|
||||
const activeProfile = activeProfileId
|
||||
? profiles.find((p) => p.id === activeProfileId)
|
||||
: undefined;
|
||||
expect(activeProfile).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Profile Badge Display Logic', () => {
|
||||
it('should show "Default" badge for default profile', () => {
|
||||
const profile = createTestProfile({ isDefault: true });
|
||||
expect(profile.isDefault).toBe(true);
|
||||
});
|
||||
|
||||
it('should show "Active" badge for active profile', () => {
|
||||
const profiles: ClaudeProfile[] = [
|
||||
createTestProfile({ id: 'p1' }),
|
||||
createTestProfile({ id: 'p2' })
|
||||
];
|
||||
const activeProfileId = 'p1';
|
||||
|
||||
const isActive = (profileId: string) => profileId === activeProfileId;
|
||||
expect(isActive('p1')).toBe(true);
|
||||
expect(isActive('p2')).toBe(false);
|
||||
});
|
||||
|
||||
it('should show "Authenticated" badge when profile has token', () => {
|
||||
const profile = createTestProfile({ oauthToken: 'sk-ant-oat01-token' });
|
||||
const isAuthenticated = !!profile.oauthToken;
|
||||
expect(isAuthenticated).toBe(true);
|
||||
});
|
||||
|
||||
it('should show "Needs Auth" badge when profile needs authentication', () => {
|
||||
const profile = createTestProfile({ oauthToken: undefined, isDefault: false });
|
||||
const needsAuth = !(profile.oauthToken || (profile.isDefault && profile.configDir));
|
||||
expect(needsAuth).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Profile Email Display', () => {
|
||||
it('should display email when present on profile', () => {
|
||||
const profile = createTestProfile({ email: 'user@example.com' });
|
||||
expect(profile.email).toBe('user@example.com');
|
||||
});
|
||||
|
||||
it('should handle profile without email', () => {
|
||||
const profile = createTestProfile({ email: undefined });
|
||||
expect(profile.email).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { useTaskStore, persistUpdateTask } from '../stores/task-store';
|
||||
import type { Task, TaskStatus, ElectronAPI } from '../../shared/types';
|
||||
import type { Task, TaskStatus } from '../../shared/types';
|
||||
|
||||
// Helper to create test tasks
|
||||
function createTestTask(overrides: Partial<Task> = {}): Task {
|
||||
|
||||
@@ -43,9 +43,7 @@ import {
|
||||
} from './ui/select';
|
||||
import { useRoadmapStore } from '../stores/roadmap-store';
|
||||
import {
|
||||
ROADMAP_PRIORITY_LABELS,
|
||||
ROADMAP_COMPLEXITY_COLORS,
|
||||
ROADMAP_IMPACT_COLORS
|
||||
ROADMAP_PRIORITY_LABELS
|
||||
} from '../../shared/constants';
|
||||
import type {
|
||||
RoadmapPhase,
|
||||
|
||||
@@ -63,6 +63,17 @@ export function AddProjectModal({ open, onOpenChange, onProjectAdded }: AddProje
|
||||
if (path) {
|
||||
const project = await addProject(path);
|
||||
if (project) {
|
||||
// Auto-detect and save the main branch for the project
|
||||
try {
|
||||
const mainBranchResult = await window.electronAPI.detectMainBranch(path);
|
||||
if (mainBranchResult.success && mainBranchResult.data) {
|
||||
await window.electronAPI.updateProjectSettings(project.id, {
|
||||
mainBranch: mainBranchResult.data
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Non-fatal - main branch can be set later in settings
|
||||
}
|
||||
onProjectAdded?.(project, !project.autoBuildPath);
|
||||
onOpenChange(false);
|
||||
}
|
||||
@@ -112,6 +123,20 @@ export function AddProjectModal({ open, onOpenChange, onProjectAdded }: AddProje
|
||||
// Add the project to our store
|
||||
const project = await addProject(result.data.path);
|
||||
if (project) {
|
||||
// For new projects with git init, set main branch
|
||||
// Git init creates 'main' branch by default on modern git
|
||||
if (initGit) {
|
||||
try {
|
||||
const mainBranchResult = await window.electronAPI.detectMainBranch(result.data.path);
|
||||
if (mainBranchResult.success && mainBranchResult.data) {
|
||||
await window.electronAPI.updateProjectSettings(project.id, {
|
||||
mainBranch: mainBranchResult.data
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Non-fatal - main branch can be set later in settings
|
||||
}
|
||||
}
|
||||
onProjectAdded?.(project, true); // New projects always need init
|
||||
onOpenChange(false);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import {
|
||||
Download,
|
||||
RefreshCw,
|
||||
CheckCircle2,
|
||||
AlertCircle
|
||||
} from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
import { Progress } from './ui/progress';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from './ui/dialog';
|
||||
import type {
|
||||
AppUpdateAvailableEvent,
|
||||
AppUpdateProgress
|
||||
} from '../../shared/types';
|
||||
|
||||
/**
|
||||
* Simple markdown renderer for release notes
|
||||
* Handles: headers, bold, lists, line breaks
|
||||
*/
|
||||
function ReleaseNotesRenderer({ markdown }: { markdown: string }) {
|
||||
const html = useMemo(() => {
|
||||
const result = markdown
|
||||
// Escape HTML
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
// Headers (### Header -> <h3>)
|
||||
.replace(/^### (.+)$/gm, '<h4 class="text-sm font-semibold text-foreground mt-3 mb-1.5 first:mt-0">$1</h4>')
|
||||
.replace(/^## (.+)$/gm, '<h3 class="text-sm font-semibold text-foreground mt-3 mb-1.5 first:mt-0">$1</h3>')
|
||||
// Bold (**text** -> <strong>)
|
||||
.replace(/\*\*([^*]+)\*\*/g, '<strong class="text-foreground font-medium">$1</strong>')
|
||||
// Inline code (`code` -> <code>)
|
||||
.replace(/`([^`]+)`/g, '<code class="px-1 py-0.5 bg-muted rounded text-xs">$1</code>')
|
||||
// List items (- item -> <li>)
|
||||
.replace(/^- (.+)$/gm, '<li class="ml-4 text-muted-foreground before:content-[\'•\'] before:mr-2 before:text-muted-foreground/60">$1</li>')
|
||||
// Wrap consecutive list items
|
||||
.replace(/(<li[^>]*>.*?<\/li>\n?)+/g, '<ul class="space-y-1 my-2">$&</ul>')
|
||||
// Line breaks for remaining lines
|
||||
.replace(/\n\n/g, '<div class="h-2"></div>')
|
||||
.replace(/\n/g, '<br/>');
|
||||
|
||||
return result;
|
||||
}, [markdown]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="text-sm text-muted-foreground leading-relaxed"
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* App Update Notification Dialog
|
||||
* Shows when a new app version is available and handles download/install workflow
|
||||
*/
|
||||
export function AppUpdateNotification() {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [updateInfo, setUpdateInfo] = useState<AppUpdateAvailableEvent | null>(null);
|
||||
const [downloadProgress, setDownloadProgress] = useState<AppUpdateProgress | null>(null);
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
const [isDownloaded, setIsDownloaded] = useState(false);
|
||||
const [downloadError, setDownloadError] = useState<string | null>(null);
|
||||
|
||||
// Listen for update available event
|
||||
useEffect(() => {
|
||||
const cleanup = window.electronAPI.onAppUpdateAvailable((info) => {
|
||||
setUpdateInfo(info);
|
||||
setIsOpen(true);
|
||||
setIsDownloading(false);
|
||||
setIsDownloaded(false);
|
||||
setDownloadProgress(null);
|
||||
setDownloadError(null);
|
||||
});
|
||||
|
||||
return cleanup;
|
||||
}, []);
|
||||
|
||||
// Listen for update downloaded event
|
||||
useEffect(() => {
|
||||
const cleanup = window.electronAPI.onAppUpdateDownloaded((_info) => {
|
||||
setIsDownloading(false);
|
||||
setIsDownloaded(true);
|
||||
setDownloadProgress(null);
|
||||
});
|
||||
|
||||
return cleanup;
|
||||
}, []);
|
||||
|
||||
// Listen for download progress
|
||||
useEffect(() => {
|
||||
const cleanup = window.electronAPI.onAppUpdateProgress((progress) => {
|
||||
setDownloadProgress(progress);
|
||||
});
|
||||
|
||||
return cleanup;
|
||||
}, []);
|
||||
|
||||
const handleDownload = async () => {
|
||||
setIsDownloading(true);
|
||||
setDownloadError(null);
|
||||
try {
|
||||
const result = await window.electronAPI.downloadAppUpdate();
|
||||
if (!result.success) {
|
||||
setDownloadError(result.error || 'Failed to download update');
|
||||
setIsDownloading(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to download app update:', error);
|
||||
setDownloadError('Failed to download update');
|
||||
setIsDownloading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleInstall = () => {
|
||||
window.electronAPI.installAppUpdate();
|
||||
};
|
||||
|
||||
const handleDismiss = () => {
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
if (!updateInfo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Download className="h-5 w-5" />
|
||||
App Update Available
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
A new version of Auto Claude is ready to download
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Version Info */}
|
||||
<div className="rounded-lg border border-border bg-muted/50 p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground uppercase tracking-wider mb-1">
|
||||
New Version
|
||||
</p>
|
||||
<p className="text-base font-medium text-foreground">
|
||||
{updateInfo.version}
|
||||
</p>
|
||||
{updateInfo.releaseDate && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Released {new Date(updateInfo.releaseDate).toLocaleDateString()}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{isDownloaded ? (
|
||||
<CheckCircle2 className="h-6 w-6 text-success" />
|
||||
) : isDownloading ? (
|
||||
<RefreshCw className="h-6 w-6 animate-spin text-info" />
|
||||
) : (
|
||||
<Download className="h-6 w-6 text-info" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Release Notes */}
|
||||
{updateInfo.releaseNotes && (
|
||||
<div className="bg-background rounded-lg p-4 max-h-64 overflow-y-auto border border-border/50">
|
||||
<ReleaseNotesRenderer markdown={updateInfo.releaseNotes} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Download Progress */}
|
||||
{isDownloading && downloadProgress && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">Downloading...</span>
|
||||
<span className="text-foreground font-medium">
|
||||
{Math.round(downloadProgress.percent)}%
|
||||
</span>
|
||||
</div>
|
||||
<Progress value={downloadProgress.percent} className="h-2" />
|
||||
<p className="text-xs text-muted-foreground text-right">
|
||||
{(downloadProgress.transferred / 1024 / 1024).toFixed(2)} MB / {(downloadProgress.total / 1024 / 1024).toFixed(2)} MB
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Download Error */}
|
||||
{downloadError && (
|
||||
<div className="flex items-center gap-3 text-sm text-destructive bg-destructive/10 border border-destructive/30 rounded-lg p-3">
|
||||
<AlertCircle className="h-5 w-5 shrink-0" />
|
||||
<span>{downloadError}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Downloaded Success */}
|
||||
{isDownloaded && (
|
||||
<div className="flex items-center gap-3 text-sm text-success bg-success/10 border border-success/30 rounded-lg p-3">
|
||||
<CheckCircle2 className="h-5 w-5 shrink-0" />
|
||||
<span>Update downloaded successfully! Click Install to restart and apply the update.</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="flex flex-col sm:flex-row gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleDismiss}
|
||||
disabled={isDownloading}
|
||||
>
|
||||
{isDownloaded ? 'Install Later' : 'Remind Me Later'}
|
||||
</Button>
|
||||
|
||||
{isDownloaded ? (
|
||||
<Button onClick={handleInstall}>
|
||||
<RefreshCw className="mr-2 h-4 w-4" />
|
||||
Install and Restart
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleDownload}
|
||||
disabled={isDownloading}
|
||||
>
|
||||
{isDownloading ? (
|
||||
<>
|
||||
<RefreshCw className="mr-2 h-4 w-4 animate-spin" />
|
||||
Downloading...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
Download Update
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -44,7 +44,7 @@ export function EnvConfigModal({
|
||||
}: EnvConfigModalProps) {
|
||||
const [token, setToken] = useState('');
|
||||
const [showToken, setShowToken] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [_isLoading, _setIsLoading] = useState(false);
|
||||
const [isChecking, setIsChecking] = useState(true);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import { useState } from 'react';
|
||||
import { GitBranch, Terminal, CheckCircle2, AlertCircle, Loader2, FolderGit2 } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from './ui/dialog';
|
||||
import type { Project, GitStatus } from '../../shared/types';
|
||||
|
||||
interface GitSetupModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
project: Project | null;
|
||||
gitStatus: GitStatus | null;
|
||||
onGitInitialized: () => void;
|
||||
onSkip?: () => void;
|
||||
}
|
||||
|
||||
export function GitSetupModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
project,
|
||||
gitStatus,
|
||||
onGitInitialized,
|
||||
onSkip
|
||||
}: GitSetupModalProps) {
|
||||
const [isInitializing, setIsInitializing] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [step, setStep] = useState<'info' | 'initializing' | 'success'>('info');
|
||||
|
||||
const needsGitInit = gitStatus && !gitStatus.isGitRepo;
|
||||
const _needsCommit = gitStatus && gitStatus.isGitRepo && !gitStatus.hasCommits;
|
||||
|
||||
const handleInitializeGit = async () => {
|
||||
if (!project) return;
|
||||
|
||||
setIsInitializing(true);
|
||||
setError(null);
|
||||
setStep('initializing');
|
||||
|
||||
try {
|
||||
// Call the backend to initialize git
|
||||
const result = await window.electronAPI.initializeGit(project.path);
|
||||
|
||||
if (result.success) {
|
||||
setStep('success');
|
||||
// Wait a moment to show success, then trigger callback
|
||||
setTimeout(() => {
|
||||
onGitInitialized();
|
||||
onOpenChange(false);
|
||||
setStep('info');
|
||||
}, 1500);
|
||||
} else {
|
||||
setError(result.error || 'Failed to initialize git');
|
||||
setStep('info');
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to initialize git');
|
||||
setStep('info');
|
||||
} finally {
|
||||
setIsInitializing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSkip = () => {
|
||||
onSkip?.();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const renderInfoStep = () => (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<FolderGit2 className="h-5 w-5 text-primary" />
|
||||
Git Repository Required
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Auto Claude uses git to safely build features in isolated workspaces
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="py-4 space-y-4">
|
||||
{/* Status indicator */}
|
||||
<div className="rounded-lg bg-muted p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertCircle className="h-5 w-5 text-warning mt-0.5 shrink-0" />
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium text-sm">
|
||||
{needsGitInit
|
||||
? 'This folder is not a git repository'
|
||||
: 'Git repository has no commits'}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{needsGitInit
|
||||
? 'Git needs to be initialized before Auto Claude can manage your code.'
|
||||
: 'At least one commit is required for Auto Claude to create worktrees.'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* What will happen */}
|
||||
<div className="rounded-lg border border-border p-4">
|
||||
<p className="font-medium text-sm mb-3">We'll set up git for you:</p>
|
||||
<ul className="space-y-2">
|
||||
{needsGitInit && (
|
||||
<li className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<GitBranch className="h-4 w-4 text-primary" />
|
||||
Initialize a new git repository
|
||||
</li>
|
||||
)}
|
||||
<li className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<CheckCircle2 className="h-4 w-4 text-primary" />
|
||||
Create an initial commit with your current files
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Manual instructions for advanced users */}
|
||||
<details className="text-sm">
|
||||
<summary className="cursor-pointer text-muted-foreground hover:text-foreground">
|
||||
Prefer to do it manually?
|
||||
</summary>
|
||||
<div className="mt-3 rounded-lg bg-muted/50 p-3 font-mono text-xs space-y-1">
|
||||
<p className="text-muted-foreground">Open a terminal in your project folder and run:</p>
|
||||
{needsGitInit && <p>git init</p>}
|
||||
<p>git add .</p>
|
||||
<p>git commit -m "Initial commit"</p>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg bg-destructive/10 border border-destructive/20 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleSkip}>
|
||||
Skip for now
|
||||
</Button>
|
||||
<Button onClick={handleInitializeGit} disabled={isInitializing}>
|
||||
<GitBranch className="mr-2 h-4 w-4" />
|
||||
Initialize Git
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
|
||||
const renderInitializingStep = () => (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-primary" />
|
||||
Setting up Git
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="py-8 flex flex-col items-center justify-center">
|
||||
<div className="space-y-3 text-center">
|
||||
<Terminal className="h-12 w-12 text-muted-foreground mx-auto" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Initializing git repository and creating initial commit...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
const renderSuccessStep = () => (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<CheckCircle2 className="h-5 w-5 text-success" />
|
||||
Git Initialized
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="py-8 flex flex-col items-center justify-center">
|
||||
<div className="space-y-3 text-center">
|
||||
<div className="h-16 w-16 rounded-full bg-success/10 flex items-center justify-center mx-auto">
|
||||
<CheckCircle2 className="h-8 w-8 text-success" />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Your project is now ready to use with Auto Claude!
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
{step === 'info' && renderInfoStep()}
|
||||
{step === 'initializing' && renderInitializingStep()}
|
||||
{step === 'success' && renderSuccessStep()}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,7 @@ import { TaskCard } from './TaskCard';
|
||||
import { SortableTaskCard } from './SortableTaskCard';
|
||||
import { TASK_STATUS_COLUMNS, TASK_STATUS_LABELS } from '../../shared/constants';
|
||||
import { cn } from '../lib/utils';
|
||||
import { persistTaskStatus } from '../stores/task-store';
|
||||
import { persistTaskStatus, archiveTasks } from '../stores/task-store';
|
||||
import type { Task, TaskStatus } from '../../shared/types';
|
||||
|
||||
interface KanbanBoardProps {
|
||||
@@ -41,6 +41,7 @@ interface DroppableColumnProps {
|
||||
onTaskClick: (task: Task) => void;
|
||||
isOver: boolean;
|
||||
onAddClick?: () => void;
|
||||
onArchiveAll?: () => void;
|
||||
}
|
||||
|
||||
// Empty state content for each column
|
||||
@@ -84,7 +85,7 @@ const getEmptyStateContent = (status: TaskStatus): { icon: React.ReactNode; mess
|
||||
}
|
||||
};
|
||||
|
||||
function DroppableColumn({ status, tasks, onTaskClick, isOver, onAddClick }: DroppableColumnProps) {
|
||||
function DroppableColumn({ status, tasks, onTaskClick, isOver, onAddClick, onArchiveAll }: DroppableColumnProps) {
|
||||
const { setNodeRef } = useDroppable({
|
||||
id: status
|
||||
});
|
||||
@@ -130,16 +131,29 @@ function DroppableColumn({ status, tasks, onTaskClick, isOver, onAddClick }: Dro
|
||||
{tasks.length}
|
||||
</span>
|
||||
</div>
|
||||
{status === 'backlog' && onAddClick && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 hover:bg-primary/10 hover:text-primary transition-colors"
|
||||
onClick={onAddClick}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<div className="flex items-center gap-1">
|
||||
{status === 'backlog' && onAddClick && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 hover:bg-primary/10 hover:text-primary transition-colors"
|
||||
onClick={onAddClick}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{status === 'done' && onArchiveAll && tasks.length > 0 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 hover:bg-muted-foreground/10 hover:text-muted-foreground transition-colors"
|
||||
onClick={onArchiveAll}
|
||||
title="Archive all done tasks"
|
||||
>
|
||||
<Archive className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Task list */}
|
||||
@@ -242,6 +256,20 @@ export function KanbanBoard({ tasks, onTaskClick, onNewTaskClick }: KanbanBoardP
|
||||
return grouped;
|
||||
}, [filteredTasks]);
|
||||
|
||||
const handleArchiveAll = async () => {
|
||||
// Get projectId from the first task (all tasks should have the same projectId)
|
||||
const projectId = tasks[0]?.projectId;
|
||||
if (!projectId) {
|
||||
console.error('No projectId found');
|
||||
return;
|
||||
}
|
||||
|
||||
const doneTaskIds = tasksByStatus.done.map((t) => t.id);
|
||||
if (doneTaskIds.length === 0) return;
|
||||
|
||||
await archiveTasks(projectId, doneTaskIds);
|
||||
};
|
||||
|
||||
const handleDragStart = (event: DragStartEvent) => {
|
||||
const { active } = event;
|
||||
const task = tasks.find((t) => t.id === active.id);
|
||||
@@ -348,6 +376,7 @@ export function KanbanBoard({ tasks, onTaskClick, onNewTaskClick }: KanbanBoardP
|
||||
onTaskClick={onTaskClick}
|
||||
isOver={overColumnId === status}
|
||||
onAddClick={status === 'backlog' ? onNewTaskClick : undefined}
|
||||
onArchiveAll={status === 'done' ? handleArchiveAll : undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user