Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a20b8cf12a | |||
| 0ed6afb805 | |||
| 914a09d0da | |||
| e44202a066 | |||
| 42496446bc | |||
| b0fc497583 | |||
| 462edcdd93 | |||
| affbc48cbe | |||
| d7fd1a24da | |||
| 96dd04d411 | |||
| 1d0566fce7 | |||
| 7f3cd5969d | |||
| 0ef0e1588b | |||
| efc112a313 | |||
| d33a0aaff6 | |||
| 2fa3c51659 | |||
| 59b091a79f | |||
| a0c775f690 | |||
| 9babdc23c1 | |||
| dc886dce44 |
@@ -1,3 +1,32 @@
|
||||
## 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
|
||||
|
||||
@@ -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
@@ -55,10 +55,11 @@
|
||||
"chokidar": "^5.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"electron-updater": "^6.6.2",
|
||||
"ioredis": "^5.8.2",
|
||||
"lucide-react": "^0.560.0",
|
||||
"motion": "^12.23.26",
|
||||
"node-pty": "^1.0.0",
|
||||
"node-pty": "^1.1.0-beta42",
|
||||
"react": "^19.2.3",
|
||||
"react-dom": "^19.2.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
@@ -114,12 +115,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",
|
||||
@@ -130,7 +149,7 @@
|
||||
]
|
||||
},
|
||||
"win": {
|
||||
"icon": "resources/icon-256.png",
|
||||
"icon": "resources/icon.ico",
|
||||
"target": [
|
||||
"nsis",
|
||||
"zip"
|
||||
|
||||
Generated
+46
-11
@@ -96,6 +96,9 @@ importers:
|
||||
clsx:
|
||||
specifier: ^2.1.1
|
||||
version: 2.1.1
|
||||
electron-updater:
|
||||
specifier: ^6.6.2
|
||||
version: 6.6.2
|
||||
ioredis:
|
||||
specifier: ^5.8.2
|
||||
version: 5.8.2
|
||||
@@ -106,8 +109,8 @@ importers:
|
||||
specifier: ^12.23.26
|
||||
version: 12.23.26(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
node-pty:
|
||||
specifier: ^1.0.0
|
||||
version: 1.0.0
|
||||
specifier: ^1.1.0-beta42
|
||||
version: 1.1.0-beta9
|
||||
react:
|
||||
specifier: ^19.2.3
|
||||
version: 19.2.3
|
||||
@@ -2204,6 +2207,9 @@ packages:
|
||||
electron-to-chromium@1.5.267:
|
||||
resolution: {integrity: sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==}
|
||||
|
||||
electron-updater@6.6.2:
|
||||
resolution: {integrity: sha512-Cr4GDOkbAUqRHP5/oeOmH/L2Bn6+FQPxVLZtPbcmKZC63a1F3uu5EefYOssgZXG3u/zBlubbJ5PJdITdMVggbw==}
|
||||
|
||||
electron-vite@5.0.0:
|
||||
resolution: {integrity: sha512-OHp/vjdlubNlhNkPkL/+3JD34ii5ov7M0GpuXEVdQeqdQ3ulvVR7Dg/rNBLfS5XPIFwgoBLDf9sjjrL+CuDyRQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
@@ -3048,9 +3054,16 @@ packages:
|
||||
lodash.defaults@4.2.0:
|
||||
resolution: {integrity: sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==}
|
||||
|
||||
lodash.escaperegexp@4.1.2:
|
||||
resolution: {integrity: sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==}
|
||||
|
||||
lodash.isarguments@3.1.0:
|
||||
resolution: {integrity: sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==}
|
||||
|
||||
lodash.isequal@4.5.0:
|
||||
resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==}
|
||||
deprecated: This package is deprecated. Use require('node:util').isDeepStrictEqual instead.
|
||||
|
||||
lodash.merge@4.6.2:
|
||||
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}
|
||||
|
||||
@@ -3365,9 +3378,6 @@ packages:
|
||||
ms@2.1.3:
|
||||
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
||||
|
||||
nan@2.24.0:
|
||||
resolution: {integrity: sha512-Vpf9qnVW1RaDkoNKFUvfxqAbtI8ncb8OJlqZ9wwpXzWPEsvsB1nvdUi6oYrHIkQ1Y/tMDnr1h4nczS0VB9Xykg==}
|
||||
|
||||
nano-spawn@2.0.0:
|
||||
resolution: {integrity: sha512-tacvGzUY5o2D8CBh2rrwxyNojUsZNU2zjNTzKQrkgGJQTbGAfArVWXSKMBokBeeg6C7OLRGUEyoFlYbfeWQIqw==}
|
||||
engines: {node: '>=20.17'}
|
||||
@@ -3391,11 +3401,14 @@ packages:
|
||||
node-addon-api@1.7.2:
|
||||
resolution: {integrity: sha512-ibPK3iA+vaY1eEjESkQkM0BbCqFOaZMiXRTtdB0u7b4djtY6JnsjvPdUHVMg6xQt3B8fpTTWHI9A+ADjM9frzg==}
|
||||
|
||||
node-addon-api@7.1.1:
|
||||
resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==}
|
||||
|
||||
node-api-version@0.2.1:
|
||||
resolution: {integrity: sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==}
|
||||
|
||||
node-pty@1.0.0:
|
||||
resolution: {integrity: sha512-wtBMWWS7dFZm/VgqElrTvtfMq4GzJ6+edFI0Y0zyzygUSZMgZdraDUMUhCIvkjhJjme15qWmbyJbtAx4ot4uZA==}
|
||||
node-pty@1.1.0-beta9:
|
||||
resolution: {integrity: sha512-/Ue38pvXJdgRZ3+me1FgfglLd301GhJN0NStiotdt61tm43N5htUyR/IXOUzOKuNaFmCwIhy6nwb77Ky41LMbw==}
|
||||
|
||||
node-releases@2.0.27:
|
||||
resolution: {integrity: sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==}
|
||||
@@ -4044,6 +4057,9 @@ packages:
|
||||
tiny-async-pool@1.3.0:
|
||||
resolution: {integrity: sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==}
|
||||
|
||||
tiny-typed-emitter@2.1.0:
|
||||
resolution: {integrity: sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==}
|
||||
|
||||
tinybench@2.9.0:
|
||||
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
|
||||
|
||||
@@ -6585,6 +6601,19 @@ snapshots:
|
||||
|
||||
electron-to-chromium@1.5.267: {}
|
||||
|
||||
electron-updater@6.6.2:
|
||||
dependencies:
|
||||
builder-util-runtime: 9.3.1
|
||||
fs-extra: 10.1.0
|
||||
js-yaml: 4.1.1
|
||||
lazy-val: 1.0.5
|
||||
lodash.escaperegexp: 4.1.2
|
||||
lodash.isequal: 4.5.0
|
||||
semver: 7.7.3
|
||||
tiny-typed-emitter: 2.1.0
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
electron-vite@5.0.0(vite@7.2.7(@types/node@25.0.0)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)):
|
||||
dependencies:
|
||||
'@babel/core': 7.28.5
|
||||
@@ -7621,8 +7650,12 @@ snapshots:
|
||||
|
||||
lodash.defaults@4.2.0: {}
|
||||
|
||||
lodash.escaperegexp@4.1.2: {}
|
||||
|
||||
lodash.isarguments@3.1.0: {}
|
||||
|
||||
lodash.isequal@4.5.0: {}
|
||||
|
||||
lodash.merge@4.6.2: {}
|
||||
|
||||
lodash@4.17.21: {}
|
||||
@@ -8143,8 +8176,6 @@ snapshots:
|
||||
|
||||
ms@2.1.3: {}
|
||||
|
||||
nan@2.24.0: {}
|
||||
|
||||
nano-spawn@2.0.0: {}
|
||||
|
||||
nanoid@3.3.11: {}
|
||||
@@ -8160,13 +8191,15 @@ snapshots:
|
||||
node-addon-api@1.7.2:
|
||||
optional: true
|
||||
|
||||
node-addon-api@7.1.1: {}
|
||||
|
||||
node-api-version@0.2.1:
|
||||
dependencies:
|
||||
semver: 7.7.3
|
||||
|
||||
node-pty@1.0.0:
|
||||
node-pty@1.1.0-beta9:
|
||||
dependencies:
|
||||
nan: 2.24.0
|
||||
node-addon-api: 7.1.1
|
||||
|
||||
node-releases@2.0.27: {}
|
||||
|
||||
@@ -8919,6 +8952,8 @@ snapshots:
|
||||
dependencies:
|
||||
semver: 5.7.2
|
||||
|
||||
tiny-typed-emitter@2.1.0: {}
|
||||
|
||||
tinybench@2.9.0: {}
|
||||
|
||||
tinyexec@1.0.2: {}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 74 KiB |
@@ -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,8 +39,8 @@ function setupTestDirs(): void {
|
||||
// Create auto-claude source directory that getAutoBuildSourcePath looks for
|
||||
mkdirSync(AUTO_CLAUDE_SOURCE, { recursive: true });
|
||||
|
||||
// Create VERSION file (required by getAutoBuildSourcePath)
|
||||
writeFileSync(path.join(AUTO_CLAUDE_SOURCE, 'VERSION'), '1.0.0');
|
||||
// Create requirements.txt file (used as marker by getAutoBuildSourcePath)
|
||||
writeFileSync(path.join(AUTO_CLAUDE_SOURCE, 'requirements.txt'), '# Mock requirements');
|
||||
|
||||
// Create runners subdirectory (where spec_runner.py lives after restructure)
|
||||
mkdirSync(path.join(AUTO_CLAUDE_SOURCE, 'runners'), { recursive: true });
|
||||
|
||||
@@ -12,7 +12,7 @@ export const TEST_DATA_DIR = '/tmp/auto-claude-ui-tests';
|
||||
beforeEach(() => {
|
||||
// Use a unique subdirectory per test to avoid race conditions in parallel tests
|
||||
const testId = `test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
const testDir = path.join(TEST_DATA_DIR, testId);
|
||||
const _testDir = path.join(TEST_DATA_DIR, testId);
|
||||
|
||||
try {
|
||||
if (existsSync(TEST_DATA_DIR)) {
|
||||
|
||||
@@ -11,6 +11,34 @@ import path from 'path';
|
||||
const TEST_DIR = '/tmp/ipc-handlers-test';
|
||||
const TEST_PROJECT_PATH = path.join(TEST_DIR, 'test-project');
|
||||
|
||||
// Mock electron-updater before importing
|
||||
vi.mock('electron-updater', () => ({
|
||||
autoUpdater: {
|
||||
autoDownload: true,
|
||||
autoInstallOnAppQuit: true,
|
||||
on: vi.fn(),
|
||||
checkForUpdates: vi.fn(() => Promise.resolve(null)),
|
||||
downloadUpdate: vi.fn(() => Promise.resolve()),
|
||||
quitAndInstall: vi.fn()
|
||||
}
|
||||
}));
|
||||
|
||||
// Mock @electron-toolkit/utils before importing
|
||||
vi.mock('@electron-toolkit/utils', () => ({
|
||||
is: {
|
||||
dev: true,
|
||||
windows: process.platform === 'win32',
|
||||
macos: process.platform === 'darwin',
|
||||
linux: process.platform === 'linux'
|
||||
},
|
||||
electronApp: {
|
||||
setAppUserModelId: vi.fn()
|
||||
},
|
||||
optimizer: {
|
||||
watchWindowShortcuts: vi.fn()
|
||||
}
|
||||
}));
|
||||
|
||||
// Mock modules before importing
|
||||
vi.mock('electron', () => {
|
||||
const mockIpcMain = new (class extends EventEmitter {
|
||||
|
||||
@@ -1,463 +0,0 @@
|
||||
/**
|
||||
* Unit tests for IPC handlers
|
||||
* Tests all IPC communication patterns between main and renderer processes
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { mkdirSync, writeFileSync, rmSync, existsSync } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
// Test data directory
|
||||
const TEST_DIR = '/tmp/ipc-handlers-test';
|
||||
const TEST_PROJECT_PATH = path.join(TEST_DIR, 'test-project');
|
||||
|
||||
// Mock modules before importing
|
||||
vi.mock('electron', () => {
|
||||
const mockIpcMain = new (class extends EventEmitter {
|
||||
private handlers: Map<string, Function> = new Map();
|
||||
|
||||
handle(channel: string, handler: Function): void {
|
||||
this.handlers.set(channel, handler);
|
||||
}
|
||||
|
||||
removeHandler(channel: string): void {
|
||||
this.handlers.delete(channel);
|
||||
}
|
||||
|
||||
async invokeHandler(channel: string, event: unknown, ...args: unknown[]): Promise<unknown> {
|
||||
const handler = this.handlers.get(channel);
|
||||
if (handler) {
|
||||
return handler(event, ...args);
|
||||
}
|
||||
throw new Error(`No handler for channel: ${channel}`);
|
||||
}
|
||||
|
||||
getHandler(channel: string): Function | undefined {
|
||||
return this.handlers.get(channel);
|
||||
}
|
||||
})();
|
||||
|
||||
return {
|
||||
app: {
|
||||
getPath: vi.fn((name: string) => {
|
||||
if (name === 'userData') return path.join(TEST_DIR, 'userData');
|
||||
return TEST_DIR;
|
||||
}),
|
||||
getVersion: vi.fn(() => '0.1.0'),
|
||||
isPackaged: false
|
||||
},
|
||||
ipcMain: mockIpcMain,
|
||||
dialog: {
|
||||
showOpenDialog: vi.fn(() => Promise.resolve({ canceled: false, filePaths: [TEST_PROJECT_PATH] }))
|
||||
},
|
||||
BrowserWindow: class {
|
||||
webContents = { send: vi.fn() };
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
// Setup test project structure
|
||||
function setupTestProject(): void {
|
||||
mkdirSync(TEST_PROJECT_PATH, { recursive: true });
|
||||
mkdirSync(path.join(TEST_PROJECT_PATH, 'auto-claude', 'specs'), { recursive: true });
|
||||
}
|
||||
|
||||
// Cleanup test directories
|
||||
function cleanupTestDirs(): void {
|
||||
if (existsSync(TEST_DIR)) {
|
||||
rmSync(TEST_DIR, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
describe('IPC Handlers', () => {
|
||||
let ipcMain: EventEmitter & {
|
||||
handlers: Map<string, Function>;
|
||||
invokeHandler: (channel: string, event: unknown, ...args: unknown[]) => Promise<unknown>;
|
||||
getHandler: (channel: string) => Function | undefined;
|
||||
};
|
||||
let mockMainWindow: { webContents: { send: ReturnType<typeof vi.fn> } };
|
||||
let mockAgentManager: EventEmitter & {
|
||||
startSpecCreation: ReturnType<typeof vi.fn>;
|
||||
startTaskExecution: ReturnType<typeof vi.fn>;
|
||||
startQAProcess: ReturnType<typeof vi.fn>;
|
||||
killTask: ReturnType<typeof vi.fn>;
|
||||
configure: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let mockTerminalManager: {
|
||||
create: ReturnType<typeof vi.fn>;
|
||||
destroy: ReturnType<typeof vi.fn>;
|
||||
write: ReturnType<typeof vi.fn>;
|
||||
resize: ReturnType<typeof vi.fn>;
|
||||
invokeClaude: ReturnType<typeof vi.fn>;
|
||||
killAll: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
cleanupTestDirs();
|
||||
setupTestProject();
|
||||
mkdirSync(path.join(TEST_DIR, 'userData', 'store'), { recursive: true });
|
||||
|
||||
// Get mocked ipcMain
|
||||
const electron = await import('electron');
|
||||
ipcMain = electron.ipcMain as unknown as typeof ipcMain;
|
||||
|
||||
// Create mock window
|
||||
mockMainWindow = {
|
||||
webContents: { send: vi.fn() }
|
||||
};
|
||||
|
||||
// Create mock agent manager
|
||||
mockAgentManager = Object.assign(new EventEmitter(), {
|
||||
startSpecCreation: vi.fn(),
|
||||
startTaskExecution: vi.fn(),
|
||||
startQAProcess: vi.fn(),
|
||||
killTask: vi.fn(),
|
||||
configure: vi.fn()
|
||||
});
|
||||
|
||||
// Create mock terminal manager
|
||||
mockTerminalManager = {
|
||||
create: vi.fn(() => Promise.resolve({ success: true })),
|
||||
destroy: vi.fn(() => Promise.resolve({ success: true })),
|
||||
write: vi.fn(),
|
||||
resize: vi.fn(),
|
||||
invokeClaude: vi.fn(),
|
||||
killAll: vi.fn(() => Promise.resolve())
|
||||
};
|
||||
|
||||
// Need to reset modules to re-register handlers
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDirs();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('project:add handler', () => {
|
||||
it('should return error for non-existent path', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler('project:add', {}, '/nonexistent/path');
|
||||
|
||||
expect(result).toEqual({
|
||||
success: false,
|
||||
error: 'Directory does not exist'
|
||||
});
|
||||
});
|
||||
|
||||
it('should successfully add an existing project', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
expect(result).toHaveProperty('data');
|
||||
const data = (result as { data: { path: string; name: string } }).data;
|
||||
expect(data.path).toBe(TEST_PROJECT_PATH);
|
||||
expect(data.name).toBe('test-project');
|
||||
});
|
||||
|
||||
it('should return existing project if already added', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add project twice
|
||||
const result1 = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
const result2 = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
|
||||
const data1 = (result1 as { data: { id: string } }).data;
|
||||
const data2 = (result2 as { data: { id: string } }).data;
|
||||
expect(data1.id).toBe(data2.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('project:list handler', () => {
|
||||
it('should return empty array when no projects', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler('project:list', {});
|
||||
|
||||
expect(result).toEqual({
|
||||
success: true,
|
||||
data: []
|
||||
});
|
||||
});
|
||||
|
||||
it('should return all added projects', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add a project
|
||||
await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
|
||||
const result = await ipcMain.invokeHandler('project:list', {});
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: unknown[] }).data;
|
||||
expect(data).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('project:remove handler', () => {
|
||||
it('should return false for non-existent project', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler('project:remove', {}, 'nonexistent-id');
|
||||
|
||||
expect(result).toEqual({ success: false });
|
||||
});
|
||||
|
||||
it('should successfully remove an existing project', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add a project first
|
||||
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
const projectId = (addResult as { data: { id: string } }).data.id;
|
||||
|
||||
// Remove it
|
||||
const removeResult = await ipcMain.invokeHandler('project:remove', {}, projectId);
|
||||
|
||||
expect(removeResult).toEqual({ success: true });
|
||||
|
||||
// Verify it's gone
|
||||
const listResult = await ipcMain.invokeHandler('project:list', {});
|
||||
const data = (listResult as { data: unknown[] }).data;
|
||||
expect(data).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('project:updateSettings handler', () => {
|
||||
it('should return error for non-existent project', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler(
|
||||
'project:updateSettings',
|
||||
{},
|
||||
'nonexistent-id',
|
||||
{ parallelEnabled: true }
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
success: false,
|
||||
error: 'Project not found'
|
||||
});
|
||||
});
|
||||
|
||||
it('should successfully update project settings', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add a project first
|
||||
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
const projectId = (addResult as { data: { id: string } }).data.id;
|
||||
|
||||
// Update settings
|
||||
const result = await ipcMain.invokeHandler(
|
||||
'project:updateSettings',
|
||||
{},
|
||||
projectId,
|
||||
{ parallelEnabled: true, maxWorkers: 4 }
|
||||
);
|
||||
|
||||
expect(result).toEqual({ success: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('task:list handler', () => {
|
||||
it('should return empty array for project with no specs', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add a project first
|
||||
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
const projectId = (addResult as { data: { id: string } }).data.id;
|
||||
|
||||
const result = await ipcMain.invokeHandler('task:list', {}, projectId);
|
||||
|
||||
expect(result).toEqual({
|
||||
success: true,
|
||||
data: []
|
||||
});
|
||||
});
|
||||
|
||||
it('should return tasks when specs exist', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add a project first
|
||||
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
const projectId = (addResult as { data: { id: string } }).data.id;
|
||||
|
||||
// Create a spec directory with implementation plan
|
||||
const specDir = path.join(TEST_PROJECT_PATH, 'auto-claude', 'specs', '001-test-feature');
|
||||
mkdirSync(specDir, { recursive: true });
|
||||
writeFileSync(path.join(specDir, 'implementation_plan.json'), JSON.stringify({
|
||||
feature: 'Test Feature',
|
||||
workflow_type: 'feature',
|
||||
services_involved: [],
|
||||
phases: [{
|
||||
phase: 1,
|
||||
name: 'Test Phase',
|
||||
type: 'implementation',
|
||||
subtasks: [{ id: 'subtask-1', description: 'Test subtask', status: 'pending' }]
|
||||
}],
|
||||
final_acceptance: [],
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
spec_file: ''
|
||||
}));
|
||||
|
||||
const result = await ipcMain.invokeHandler('task:list', {}, projectId);
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: unknown[] }).data;
|
||||
expect(data).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('task:create handler', () => {
|
||||
it('should return error for non-existent project', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler(
|
||||
'task:create',
|
||||
{},
|
||||
'nonexistent-id',
|
||||
'Test Task',
|
||||
'Test description'
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
success: false,
|
||||
error: 'Project not found'
|
||||
});
|
||||
});
|
||||
|
||||
it('should create task and start spec creation', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add a project first
|
||||
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
const projectId = (addResult as { data: { id: string } }).data.id;
|
||||
|
||||
const result = await ipcMain.invokeHandler(
|
||||
'task:create',
|
||||
{},
|
||||
projectId,
|
||||
'Test Task',
|
||||
'Test description'
|
||||
);
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
expect(mockAgentManager.startSpecCreation).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('settings:get handler', () => {
|
||||
it('should return default settings when no settings file exists', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler('settings:get', {});
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { theme: string } }).data;
|
||||
expect(data).toHaveProperty('theme', 'system');
|
||||
});
|
||||
});
|
||||
|
||||
describe('settings:save handler', () => {
|
||||
it('should save settings successfully', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler(
|
||||
'settings:save',
|
||||
{},
|
||||
{ theme: 'dark', defaultModel: 'opus' }
|
||||
);
|
||||
|
||||
expect(result).toEqual({ success: true });
|
||||
|
||||
// Verify settings were saved
|
||||
const getResult = await ipcMain.invokeHandler('settings:get', {});
|
||||
const data = (getResult as { data: { theme: string; defaultModel: string } }).data;
|
||||
expect(data.theme).toBe('dark');
|
||||
expect(data.defaultModel).toBe('opus');
|
||||
});
|
||||
|
||||
it('should configure agent manager when paths change', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
await ipcMain.invokeHandler(
|
||||
'settings:save',
|
||||
{},
|
||||
{ pythonPath: '/usr/bin/python3' }
|
||||
);
|
||||
|
||||
expect(mockAgentManager.configure).toHaveBeenCalledWith('/usr/bin/python3', undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('app:version handler', () => {
|
||||
it('should return app version', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler('app:version', {});
|
||||
|
||||
expect(result).toBe('0.1.0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Agent Manager event forwarding', () => {
|
||||
it('should forward log events to renderer', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
mockAgentManager.emit('log', 'task-1', 'Test log message');
|
||||
|
||||
expect(mockMainWindow.webContents.send).toHaveBeenCalledWith(
|
||||
'task:log',
|
||||
'task-1',
|
||||
'Test log message'
|
||||
);
|
||||
});
|
||||
|
||||
it('should forward error events to renderer', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
mockAgentManager.emit('error', 'task-1', 'Test error message');
|
||||
|
||||
expect(mockMainWindow.webContents.send).toHaveBeenCalledWith(
|
||||
'task:error',
|
||||
'task-1',
|
||||
'Test error message'
|
||||
);
|
||||
});
|
||||
|
||||
it('should forward exit events with status change', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
mockAgentManager.emit('exit', 'task-1', 0);
|
||||
|
||||
expect(mockMainWindow.webContents.send).toHaveBeenCalledWith(
|
||||
'task:statusChange',
|
||||
'task-1',
|
||||
'ai_review'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
@@ -44,8 +41,7 @@ export class AgentManager extends EventEmitter {
|
||||
this.queueManager = new AgentQueueManager(this.state, this.events, this.processManager, this);
|
||||
|
||||
// Listen for auto-swap restart events
|
||||
this.on('auto-swap-restart-task', (taskId: string, newProfileId: string) => {
|
||||
console.log('[AgentManager] Auto-swap restart:', taskId, newProfileId);
|
||||
this.on('auto-swap-restart-task', (taskId: string, _newProfileId: string) => {
|
||||
this.restartTask(taskId);
|
||||
});
|
||||
|
||||
@@ -64,14 +60,12 @@ export class AgentManager extends EventEmitter {
|
||||
// If task completed successfully, always clean up
|
||||
if (code === 0) {
|
||||
this.taskExecutionContext.delete(taskId);
|
||||
console.log('[AgentManager] Cleaned up context for completed task:', taskId);
|
||||
return;
|
||||
}
|
||||
|
||||
// If task failed and hit max retries, clean up
|
||||
if (context.swapCount >= 2) {
|
||||
this.taskExecutionContext.delete(taskId);
|
||||
console.log('[AgentManager] Cleaned up context for max-retry task:', taskId);
|
||||
}
|
||||
// Otherwise keep context for potential restart
|
||||
}, 1000); // Delay to allow restart logic to run first
|
||||
@@ -142,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;
|
||||
}
|
||||
@@ -183,7 +172,6 @@ export class AgentManager extends EventEmitter {
|
||||
// Store context for potential restart
|
||||
this.storeTaskContext(taskId, projectPath, specId, options, false);
|
||||
|
||||
console.log('[AgentManager] Spawning process with args:', args);
|
||||
this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution');
|
||||
}
|
||||
|
||||
@@ -329,7 +317,6 @@ export class AgentManager extends EventEmitter {
|
||||
}
|
||||
|
||||
context.swapCount++;
|
||||
console.log('[AgentManager] Restarting task:', taskId, 'swap count:', context.swapCount);
|
||||
|
||||
// Kill current process
|
||||
this.killTask(taskId);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { spawn, ChildProcess } from 'child_process';
|
||||
import { spawn } from 'child_process';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { app } from 'electron';
|
||||
@@ -65,7 +65,8 @@ export class AgentProcessManager {
|
||||
];
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
|
||||
// Use requirements.txt as marker - it always exists in auto-claude source
|
||||
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -99,14 +100,11 @@ export class AgentProcessManager {
|
||||
loadAutoBuildEnv(): Record<string, string> {
|
||||
const autoBuildSource = this.getAutoBuildSourcePath();
|
||||
if (!autoBuildSource) {
|
||||
console.log('[loadAutoBuildEnv] No auto-build source path found');
|
||||
return {};
|
||||
}
|
||||
|
||||
const envPath = path.join(autoBuildSource, '.env');
|
||||
console.log('[loadAutoBuildEnv] Looking for .env at:', envPath);
|
||||
if (!existsSync(envPath)) {
|
||||
console.log('[loadAutoBuildEnv] .env file does not exist');
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -160,11 +158,6 @@ export class AgentProcessManager {
|
||||
// Generate unique spawn ID for this process instance
|
||||
const spawnId = this.state.generateSpawnId();
|
||||
|
||||
console.log('[spawnProcess] Spawning with pythonPath:', this.pythonPath);
|
||||
console.log('[spawnProcess] cwd:', cwd);
|
||||
console.log('[spawnProcess] processType:', processType);
|
||||
console.log('[spawnProcess] spawnId:', spawnId);
|
||||
|
||||
// Get active Claude profile environment (CLAUDE_CONFIG_DIR if not default)
|
||||
const profileEnv = getProfileEnv();
|
||||
|
||||
@@ -174,12 +167,12 @@ export class AgentProcessManager {
|
||||
...process.env,
|
||||
...extraEnv,
|
||||
...profileEnv, // Include active Claude profile config
|
||||
PYTHONUNBUFFERED: '1' // Ensure real-time output
|
||||
PYTHONUNBUFFERED: '1', // Ensure real-time output
|
||||
PYTHONIOENCODING: 'utf-8', // Ensure UTF-8 encoding on Windows
|
||||
PYTHONUTF8: '1' // Force Python UTF-8 mode on Windows (Python 3.7+)
|
||||
}
|
||||
});
|
||||
|
||||
console.log('[spawnProcess] Process spawned, pid:', childProcess.pid);
|
||||
|
||||
this.state.addProcess(taskId, {
|
||||
taskId,
|
||||
process: childProcess,
|
||||
@@ -239,18 +232,16 @@ export class AgentProcessManager {
|
||||
}
|
||||
};
|
||||
|
||||
// Handle stdout
|
||||
// Handle stdout - explicitly decode as UTF-8 for cross-platform Unicode support
|
||||
childProcess.stdout?.on('data', (data: Buffer) => {
|
||||
const log = data.toString();
|
||||
console.log('[spawnProcess] stdout:', log.substring(0, 200));
|
||||
const log = data.toString('utf8');
|
||||
this.emitter.emit('log', taskId, log);
|
||||
processLog(log);
|
||||
});
|
||||
|
||||
// Handle stderr
|
||||
// Handle stderr - explicitly decode as UTF-8 for cross-platform Unicode support
|
||||
childProcess.stderr?.on('data', (data: Buffer) => {
|
||||
const log = data.toString();
|
||||
console.log('[spawnProcess] stderr:', log.substring(0, 200));
|
||||
const log = data.toString('utf8');
|
||||
// Some Python output goes to stderr (like progress bars)
|
||||
// so we treat it as log, not error
|
||||
this.emitter.emit('log', taskId, log);
|
||||
@@ -259,13 +250,11 @@ export class AgentProcessManager {
|
||||
|
||||
// Handle process exit
|
||||
childProcess.on('exit', (code: number | null) => {
|
||||
console.log('[spawnProcess] Process exited with code:', code, 'spawnId:', spawnId);
|
||||
this.state.deleteProcess(taskId);
|
||||
|
||||
// Check if this specific spawn was killed (vs exited naturally)
|
||||
// If killed, don't emit exit event to prevent race condition with new process
|
||||
if (this.state.wasSpawnKilled(spawnId)) {
|
||||
console.log('[spawnProcess] Process was killed, skipping exit event for spawnId:', spawnId);
|
||||
this.state.clearKilledSpawn(spawnId);
|
||||
return;
|
||||
}
|
||||
@@ -274,26 +263,15 @@ export class AgentProcessManager {
|
||||
if (code !== 0) {
|
||||
const rateLimitDetection = detectRateLimit(allOutput);
|
||||
if (rateLimitDetection.isRateLimited) {
|
||||
console.log('[spawnProcess] Rate limit detected in task output:', {
|
||||
taskId,
|
||||
resetTime: rateLimitDetection.resetTime,
|
||||
limitType: rateLimitDetection.limitType,
|
||||
suggestedProfile: rateLimitDetection.suggestedProfile?.name
|
||||
});
|
||||
|
||||
// Check if auto-swap is enabled
|
||||
const profileManager = getClaudeProfileManager();
|
||||
const autoSwitchSettings = profileManager.getAutoSwitchSettings();
|
||||
|
||||
if (autoSwitchSettings.enabled && autoSwitchSettings.autoSwitchOnRateLimit) {
|
||||
console.log('[spawnProcess] Reactive auto-swap enabled');
|
||||
|
||||
const currentProfileId = rateLimitDetection.profileId;
|
||||
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
|
||||
|
||||
if (bestProfile) {
|
||||
console.log('[spawnProcess] Reactive swap to:', bestProfile.name);
|
||||
|
||||
// Switch active profile
|
||||
profileManager.setActiveProfile(bestProfile.id);
|
||||
|
||||
@@ -339,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}`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
/**
|
||||
* Electron App Auto-Updater
|
||||
*
|
||||
* Manages automatic updates for the packaged Electron application using electron-updater.
|
||||
* Updates are published through GitHub Releases and automatically downloaded and installed.
|
||||
*
|
||||
* Update flow:
|
||||
* 1. Check for updates 3 seconds after app launch
|
||||
* 2. Download updates automatically when available
|
||||
* 3. Notify user when update is downloaded
|
||||
* 4. Install and restart when user confirms
|
||||
*
|
||||
* Events sent to renderer:
|
||||
* - APP_UPDATE_AVAILABLE: New update available (with version info)
|
||||
* - APP_UPDATE_DOWNLOADED: Update downloaded and ready to install
|
||||
* - APP_UPDATE_PROGRESS: Download progress updates
|
||||
* - APP_UPDATE_ERROR: Error during update process
|
||||
*/
|
||||
|
||||
import { autoUpdater } from 'electron-updater';
|
||||
import { app } from 'electron';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import { IPC_CHANNELS } from '../shared/constants';
|
||||
import type { AppUpdateInfo } from '../shared/types';
|
||||
|
||||
// Debug mode - set via environment variable
|
||||
const DEBUG_UPDATER = process.env.DEBUG_UPDATER === 'true' || process.env.DEBUG === 'true';
|
||||
|
||||
// Configure electron-updater
|
||||
autoUpdater.autoDownload = true; // Automatically download updates when available
|
||||
autoUpdater.autoInstallOnAppQuit = true; // Automatically install on app quit
|
||||
|
||||
// Enable more verbose logging in debug mode
|
||||
if (DEBUG_UPDATER) {
|
||||
autoUpdater.logger = {
|
||||
info: (msg: string) => console.warn('[app-updater:debug]', msg),
|
||||
warn: (msg: string) => console.warn('[app-updater:debug]', msg),
|
||||
error: (msg: string) => console.error('[app-updater:debug]', msg),
|
||||
debug: (msg: string) => console.warn('[app-updater:debug]', msg)
|
||||
};
|
||||
}
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
|
||||
/**
|
||||
* Initialize the app updater system
|
||||
*
|
||||
* Sets up event handlers and starts periodic update checks.
|
||||
* Should only be called in production (app.isPackaged).
|
||||
*
|
||||
* @param window - The main BrowserWindow for sending update events
|
||||
*/
|
||||
export function initializeAppUpdater(window: BrowserWindow): void {
|
||||
mainWindow = window;
|
||||
|
||||
// Log updater configuration
|
||||
console.warn('[app-updater] ========================================');
|
||||
console.warn('[app-updater] Initializing app auto-updater');
|
||||
console.warn('[app-updater] App packaged:', app.isPackaged);
|
||||
console.warn('[app-updater] Current version:', autoUpdater.currentVersion.version);
|
||||
console.warn('[app-updater] Auto-download enabled:', autoUpdater.autoDownload);
|
||||
console.warn('[app-updater] Debug mode:', DEBUG_UPDATER);
|
||||
console.warn('[app-updater] ========================================');
|
||||
|
||||
// ============================================
|
||||
// Event Handlers
|
||||
// ============================================
|
||||
|
||||
// Update available - new version found
|
||||
autoUpdater.on('update-available', (info) => {
|
||||
console.warn('[app-updater] Update available:', info.version);
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_AVAILABLE, {
|
||||
version: info.version,
|
||||
releaseNotes: info.releaseNotes,
|
||||
releaseDate: info.releaseDate
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Update downloaded - ready to install
|
||||
autoUpdater.on('update-downloaded', (info) => {
|
||||
console.warn('[app-updater] Update downloaded:', info.version);
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_DOWNLOADED, {
|
||||
version: info.version,
|
||||
releaseNotes: info.releaseNotes,
|
||||
releaseDate: info.releaseDate
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Download progress
|
||||
autoUpdater.on('download-progress', (progress) => {
|
||||
console.warn(`[app-updater] Download progress: ${progress.percent.toFixed(2)}%`);
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_PROGRESS, {
|
||||
percent: progress.percent,
|
||||
bytesPerSecond: progress.bytesPerSecond,
|
||||
transferred: progress.transferred,
|
||||
total: progress.total
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Error handling
|
||||
autoUpdater.on('error', (error) => {
|
||||
console.error('[app-updater] Update error:', error);
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_ERROR, {
|
||||
message: error.message,
|
||||
stack: error.stack
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// No update available
|
||||
autoUpdater.on('update-not-available', (info) => {
|
||||
console.warn('[app-updater] No updates available - you are on the latest version');
|
||||
console.warn('[app-updater] Current version:', info.version);
|
||||
if (DEBUG_UPDATER) {
|
||||
console.warn('[app-updater:debug] Full info:', JSON.stringify(info, null, 2));
|
||||
}
|
||||
});
|
||||
|
||||
// Checking for updates
|
||||
autoUpdater.on('checking-for-update', () => {
|
||||
console.warn('[app-updater] Checking for updates...');
|
||||
});
|
||||
|
||||
// ============================================
|
||||
// Update Check Schedule
|
||||
// ============================================
|
||||
|
||||
// Check for updates 3 seconds after launch
|
||||
const INITIAL_DELAY = 3000;
|
||||
console.warn(`[app-updater] Will check for updates in ${INITIAL_DELAY / 1000} seconds...`);
|
||||
|
||||
setTimeout(() => {
|
||||
console.warn('[app-updater] Performing initial update check');
|
||||
autoUpdater.checkForUpdates().catch((error) => {
|
||||
console.error('[app-updater] ❌ Initial update check failed:', error.message);
|
||||
if (DEBUG_UPDATER) {
|
||||
console.error('[app-updater:debug] Full error:', error);
|
||||
}
|
||||
});
|
||||
}, INITIAL_DELAY);
|
||||
|
||||
// Check for updates every 4 hours
|
||||
const FOUR_HOURS = 4 * 60 * 60 * 1000;
|
||||
console.warn(`[app-updater] Periodic checks scheduled every ${FOUR_HOURS / 1000 / 60 / 60} hours`);
|
||||
|
||||
setInterval(() => {
|
||||
console.warn('[app-updater] Performing periodic update check');
|
||||
autoUpdater.checkForUpdates().catch((error) => {
|
||||
console.error('[app-updater] ❌ Periodic update check failed:', error.message);
|
||||
if (DEBUG_UPDATER) {
|
||||
console.error('[app-updater:debug] Full error:', error);
|
||||
}
|
||||
});
|
||||
}, FOUR_HOURS);
|
||||
|
||||
console.warn('[app-updater] Auto-updater initialized successfully');
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually check for updates
|
||||
* Called from IPC handler when user requests manual check
|
||||
*/
|
||||
export async function checkForUpdates(): Promise<AppUpdateInfo | null> {
|
||||
try {
|
||||
console.warn('[app-updater] Manual update check requested');
|
||||
const result = await autoUpdater.checkForUpdates();
|
||||
|
||||
if (!result) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const updateAvailable = result.updateInfo.version !== autoUpdater.currentVersion.version;
|
||||
|
||||
if (!updateAvailable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
version: result.updateInfo.version,
|
||||
releaseNotes: result.updateInfo.releaseNotes as string | undefined,
|
||||
releaseDate: result.updateInfo.releaseDate
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[app-updater] Manual update check failed:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually download update
|
||||
* Called from IPC handler when user requests manual download
|
||||
*/
|
||||
export async function downloadUpdate(): Promise<void> {
|
||||
try {
|
||||
console.warn('[app-updater] Manual update download requested');
|
||||
await autoUpdater.downloadUpdate();
|
||||
} catch (error) {
|
||||
console.error('[app-updater] Manual update download failed:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Quit and install update
|
||||
* Called from IPC handler when user confirms installation
|
||||
*/
|
||||
export function quitAndInstall(): void {
|
||||
console.warn('[app-updater] Quitting and installing update');
|
||||
autoUpdater.quitAndInstall(false, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current app version
|
||||
*/
|
||||
export function getCurrentVersion(): string {
|
||||
return autoUpdater.currentVersion.version;
|
||||
}
|
||||
@@ -119,7 +119,7 @@ export class ChangelogService extends EventEmitter {
|
||||
*/
|
||||
private debug(...args: unknown[]): void {
|
||||
if (this.isDebugEnabled()) {
|
||||
console.log('[ChangelogService]', ...args);
|
||||
console.warn('[ChangelogService]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +150,8 @@ export class ChangelogService extends EventEmitter {
|
||||
];
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
|
||||
// Use requirements.txt as marker - it always exists in auto-claude source
|
||||
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ export class ChangelogGenerator extends EventEmitter {
|
||||
|
||||
private debug(...args: unknown[]): void {
|
||||
if (this.debugEnabled) {
|
||||
console.log('[ChangelogGenerator]', ...args);
|
||||
console.warn('[ChangelogGenerator]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,7 +277,9 @@ export class ChangelogGenerator extends EventEmitter {
|
||||
USER: process.env.USER || process.env.USERNAME || 'user',
|
||||
// Add common binary locations to PATH for claude CLI
|
||||
PATH: [process.env.PATH || '', ...pathAdditions].filter(Boolean).join(path.delimiter),
|
||||
PYTHONUNBUFFERED: '1'
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
};
|
||||
|
||||
this.debug('Spawn environment', {
|
||||
|
||||
@@ -13,7 +13,7 @@ import { parseGitLogOutput } from './parser';
|
||||
*/
|
||||
function debug(enabled: boolean, ...args: unknown[]): void {
|
||||
if (enabled) {
|
||||
console.log('[GitIntegration]', ...args);
|
||||
console.warn('[GitIntegration]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export function extractSpecOverview(spec: string): string {
|
||||
// Handle both Unix (\n) and Windows (\r\n) line endings
|
||||
const lines = spec.split(/\r?\n/);
|
||||
let inOverview = false;
|
||||
let overview: string[] = [];
|
||||
const overview: string[] = [];
|
||||
|
||||
for (const line of lines) {
|
||||
// Start capturing at Overview heading
|
||||
|
||||
@@ -28,7 +28,7 @@ export class VersionSuggester {
|
||||
|
||||
private debug(...args: unknown[]): void {
|
||||
if (this.debugEnabled) {
|
||||
console.log('[VersionSuggester]', ...args);
|
||||
console.warn('[VersionSuggester]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ export class VersionSuggester {
|
||||
// Build environment
|
||||
const spawnEnv = this.buildSpawnEnvironment();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
return new Promise((resolve, _reject) => {
|
||||
const childProcess = spawn(this.pythonPath, ['-c', script], {
|
||||
cwd: this.autoBuildSourcePath,
|
||||
env: spawnEnv
|
||||
@@ -237,7 +237,9 @@ except Exception as e:
|
||||
...(isWindows ? { USERPROFILE: homeDir } : { HOME: homeDir }),
|
||||
USER: process.env.USER || process.env.USERNAME || 'user',
|
||||
PATH: [process.env.PATH || '', ...pathAdditions].filter(Boolean).join(path.delimiter),
|
||||
PYTHONUNBUFFERED: '1'
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
};
|
||||
|
||||
return spawnEnv;
|
||||
|
||||
@@ -240,7 +240,7 @@ export class ClaudeProfileManager {
|
||||
|
||||
profile.name = newName.trim();
|
||||
this.save();
|
||||
console.log('[ClaudeProfileManager] Renamed profile:', profileId, 'to:', newName);
|
||||
console.warn('[ClaudeProfileManager] Renamed profile:', profileId, 'to:', newName);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -317,7 +317,7 @@ export class ClaudeProfileManager {
|
||||
this.save();
|
||||
|
||||
const isEncrypted = profile.oauthToken.startsWith('enc:');
|
||||
console.log('[ClaudeProfileManager] Set OAuth token for profile:', profile.name, {
|
||||
console.warn('[ClaudeProfileManager] Set OAuth token for profile:', profile.name, {
|
||||
email: email || '(not captured)',
|
||||
encrypted: isEncrypted,
|
||||
tokenLength: token.length
|
||||
@@ -350,14 +350,14 @@ export class ClaudeProfileManager {
|
||||
const decryptedToken = decryptToken(profile.oauthToken);
|
||||
if (decryptedToken) {
|
||||
env.CLAUDE_CODE_OAUTH_TOKEN = decryptedToken;
|
||||
console.log('[ClaudeProfileManager] Using OAuth token for profile:', profile.name);
|
||||
console.warn('[ClaudeProfileManager] Using OAuth token for profile:', profile.name);
|
||||
} else {
|
||||
console.warn('[ClaudeProfileManager] Failed to decrypt token for profile:', profile.name);
|
||||
}
|
||||
} else if (profile?.configDir && !profile.isDefault) {
|
||||
// Fallback to configDir for backward compatibility
|
||||
env.CLAUDE_CONFIG_DIR = profile.configDir;
|
||||
console.log('[ClaudeProfileManager] Using configDir for profile:', profile.name);
|
||||
console.warn('[ClaudeProfileManager] Using configDir for profile:', profile.name);
|
||||
}
|
||||
|
||||
return env;
|
||||
@@ -376,7 +376,7 @@ export class ClaudeProfileManager {
|
||||
profile.usage = usage;
|
||||
this.save();
|
||||
|
||||
console.log('[ClaudeProfileManager] Updated usage for', profile.name, ':', usage);
|
||||
console.warn('[ClaudeProfileManager] Updated usage for', profile.name, ':', usage);
|
||||
return usage;
|
||||
}
|
||||
|
||||
@@ -392,7 +392,7 @@ export class ClaudeProfileManager {
|
||||
const event = recordRateLimitEventImpl(profile, resetTimeStr);
|
||||
this.save();
|
||||
|
||||
console.log('[ClaudeProfileManager] Recorded rate limit event for', profile.name, ':', event);
|
||||
console.warn('[ClaudeProfileManager] Recorded rate limit event for', profile.name, ':', event);
|
||||
return event;
|
||||
}
|
||||
|
||||
|
||||
@@ -86,12 +86,12 @@ export function getBestAvailableProfile(
|
||||
// Return the best candidate if it has a positive score
|
||||
const best = scoredProfiles[0];
|
||||
if (best && best.score > 0) {
|
||||
console.log('[ProfileScorer] Best available profile:', best.profile.name, 'score:', best.score);
|
||||
console.warn('[ProfileScorer] Best available profile:', best.profile.name, 'score:', best.score);
|
||||
return best.profile;
|
||||
}
|
||||
|
||||
// All profiles are rate-limited or have issues
|
||||
console.log('[ProfileScorer] No good profile available, all are rate-limited or have issues');
|
||||
console.warn('[ProfileScorer] No good profile available, all are rate-limited or have issues');
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -143,7 +143,7 @@ export function shouldProactivelySwitch(
|
||||
* Get profiles sorted by availability (best first)
|
||||
*/
|
||||
export function getProfilesSortedByAvailability(profiles: ClaudeProfile[]): ClaudeProfile[] {
|
||||
const now = new Date();
|
||||
const _now = new Date();
|
||||
|
||||
return [...profiles].sort((a, b) => {
|
||||
// Not rate-limited profiles first
|
||||
|
||||
@@ -117,7 +117,7 @@ export function hasValidToken(profile: ClaudeProfile): boolean {
|
||||
const oneYearAgo = new Date();
|
||||
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
|
||||
if (new Date(profile.tokenCreatedAt) < oneYearAgo) {
|
||||
console.log('[ProfileUtils] Token expired for profile:', profile.name);
|
||||
console.warn('[ProfileUtils] Token expired for profile:', profile.name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
|
||||
private constructor() {
|
||||
super();
|
||||
console.log('[UsageMonitor] Initialized');
|
||||
console.warn('[UsageMonitor] Initialized');
|
||||
}
|
||||
|
||||
static getInstance(): UsageMonitor {
|
||||
@@ -40,17 +40,17 @@ export class UsageMonitor extends EventEmitter {
|
||||
const settings = profileManager.getAutoSwitchSettings();
|
||||
|
||||
if (!settings.enabled || !settings.proactiveSwapEnabled) {
|
||||
console.log('[UsageMonitor] Proactive monitoring disabled');
|
||||
console.warn('[UsageMonitor] Proactive monitoring disabled');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.intervalId) {
|
||||
console.log('[UsageMonitor] Already running');
|
||||
console.warn('[UsageMonitor] Already running');
|
||||
return;
|
||||
}
|
||||
|
||||
const interval = settings.usageCheckInterval || 30000;
|
||||
console.log('[UsageMonitor] Starting with interval:', interval, 'ms');
|
||||
console.warn('[UsageMonitor] Starting with interval:', interval, 'ms');
|
||||
|
||||
// Check immediately
|
||||
this.checkUsageAndSwap();
|
||||
@@ -68,7 +68,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
if (this.intervalId) {
|
||||
clearInterval(this.intervalId);
|
||||
this.intervalId = null;
|
||||
console.log('[UsageMonitor] Stopped');
|
||||
console.warn('[UsageMonitor] Stopped');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,14 +94,14 @@ export class UsageMonitor extends EventEmitter {
|
||||
const activeProfile = profileManager.getActiveProfile();
|
||||
|
||||
if (!activeProfile) {
|
||||
console.log('[UsageMonitor] No active profile');
|
||||
console.warn('[UsageMonitor] No active profile');
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch current usage (hybrid approach)
|
||||
const usage = await this.fetchUsage(activeProfile.id, activeProfile.oauthToken);
|
||||
if (!usage) {
|
||||
console.log('[UsageMonitor] Failed to fetch usage');
|
||||
console.warn('[UsageMonitor] Failed to fetch usage');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
const weeklyExceeded = usage.weeklyPercent >= settings.weeklyThreshold;
|
||||
|
||||
if (sessionExceeded || weeklyExceeded) {
|
||||
console.log('[UsageMonitor] Threshold exceeded:', {
|
||||
console.warn('[UsageMonitor] Threshold exceeded:', {
|
||||
sessionPercent: usage.sessionPercent,
|
||||
sessionThreshold: settings.sessionThreshold,
|
||||
weeklyPercent: usage.weeklyPercent,
|
||||
@@ -154,12 +154,12 @@ export class UsageMonitor extends EventEmitter {
|
||||
if (this.useApiMethod && oauthToken) {
|
||||
const apiUsage = await this.fetchUsageViaAPI(oauthToken, profileId, profile.name);
|
||||
if (apiUsage) {
|
||||
console.log('[UsageMonitor] Successfully fetched via API');
|
||||
console.warn('[UsageMonitor] Successfully fetched via API');
|
||||
return apiUsage;
|
||||
}
|
||||
|
||||
// API failed - switch to CLI method for future calls
|
||||
console.log('[UsageMonitor] API method failed, falling back to CLI');
|
||||
console.warn('[UsageMonitor] API method failed, falling back to CLI');
|
||||
this.useApiMethod = false;
|
||||
}
|
||||
|
||||
@@ -191,7 +191,12 @@ export class UsageMonitor extends EventEmitter {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data: any = await response.json();
|
||||
const data = await response.json() as {
|
||||
five_hour_utilization?: number;
|
||||
seven_day_utilization?: number;
|
||||
five_hour_reset_at?: string;
|
||||
seven_day_reset_at?: string;
|
||||
};
|
||||
|
||||
// Expected response format:
|
||||
// {
|
||||
@@ -232,7 +237,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
// CLI-based usage fetching is not implemented yet.
|
||||
// The API method should handle most cases. If we need CLI fallback,
|
||||
// we would need to spawn a Claude process with /usage command and parse the output.
|
||||
console.log('[UsageMonitor] CLI fallback not implemented, API method should be used');
|
||||
console.warn('[UsageMonitor] CLI fallback not implemented, API method should be used');
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -256,7 +261,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
const remainingHours = diffHours % 24;
|
||||
return `${diffDays}d ${remainingHours}h`;
|
||||
} catch (error) {
|
||||
} catch (_error) {
|
||||
return isoTimestamp;
|
||||
}
|
||||
}
|
||||
@@ -272,7 +277,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
|
||||
|
||||
if (!bestProfile) {
|
||||
console.log('[UsageMonitor] No alternative profile for proactive swap');
|
||||
console.warn('[UsageMonitor] No alternative profile for proactive swap');
|
||||
this.emit('proactive-swap-failed', {
|
||||
reason: 'no_alternative',
|
||||
currentProfile: currentProfileId
|
||||
@@ -280,7 +285,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[UsageMonitor] Proactive swap:', {
|
||||
console.warn('[UsageMonitor] Proactive swap:', {
|
||||
from: currentProfileId,
|
||||
to: bestProfile.id,
|
||||
reason: limitType
|
||||
|
||||
@@ -158,7 +158,7 @@ export async function checkFalkorDBStatus(port: number = FALKORDB_DEFAULT_PORT):
|
||||
/**
|
||||
* Check if FalkorDB is responding to connections
|
||||
*/
|
||||
async function checkFalkorDBHealth(port: number): Promise<boolean> {
|
||||
async function checkFalkorDBHealth(_port: number): Promise<boolean> {
|
||||
try {
|
||||
// Try to ping FalkorDB using redis-cli (FalkorDB uses Redis protocol)
|
||||
// Since we may not have redis-cli, we'll check if the port is listening
|
||||
@@ -482,10 +482,10 @@ export async function validateOpenAIApiKey(
|
||||
timeout: 15000,
|
||||
};
|
||||
|
||||
const req = https.request(options, (res: any) => {
|
||||
const req = https.request(options, (res: { statusCode: number; on: (event: string, callback: (chunk: Buffer) => void) => void }) => {
|
||||
let data = '';
|
||||
|
||||
res.on('data', (chunk: any) => {
|
||||
res.on('data', (chunk: Buffer) => {
|
||||
data += chunk;
|
||||
});
|
||||
|
||||
@@ -533,7 +533,7 @@ export async function validateOpenAIApiKey(
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (error: any) => {
|
||||
req.on('error', (error: Error) => {
|
||||
resolve({
|
||||
success: false,
|
||||
message: `Connection error: ${error.message}`,
|
||||
|
||||
@@ -7,6 +7,7 @@ import { TerminalManager } from './terminal-manager';
|
||||
import { pythonEnvManager } from './python-env-manager';
|
||||
import { getUsageMonitor } from './claude-profile/usage-monitor';
|
||||
import { initializeUsageMonitorForwarding } from './ipc-handlers/terminal-handlers';
|
||||
import { initializeAppUpdater } from './app-updater';
|
||||
|
||||
// Get icon path based on platform
|
||||
function getIconPath(): string {
|
||||
@@ -21,7 +22,7 @@ function getIconPath(): string {
|
||||
// Use PNG in dev mode (works better), ICNS in production
|
||||
iconName = is.dev ? 'icon-256.png' : 'icon.icns';
|
||||
} else if (process.platform === 'win32') {
|
||||
iconName = 'icon-256.png';
|
||||
iconName = 'icon.ico';
|
||||
} else {
|
||||
iconName = 'icon.png';
|
||||
}
|
||||
@@ -136,7 +137,24 @@ app.whenReady().then(() => {
|
||||
// Start the usage monitor
|
||||
const usageMonitor = getUsageMonitor();
|
||||
usageMonitor.start();
|
||||
console.log('[main] Usage monitor initialized and started');
|
||||
console.warn('[main] Usage monitor initialized and started');
|
||||
|
||||
// Initialize app auto-updater (only in production, or when DEBUG_UPDATER is set)
|
||||
const forceUpdater = process.env.DEBUG_UPDATER === 'true';
|
||||
if (app.isPackaged || forceUpdater) {
|
||||
initializeAppUpdater(mainWindow);
|
||||
console.warn('[main] App auto-updater initialized');
|
||||
if (forceUpdater && !app.isPackaged) {
|
||||
console.warn('[main] Updater forced in dev mode via DEBUG_UPDATER=true');
|
||||
console.warn('[main] Note: Updates won\'t actually work in dev mode');
|
||||
}
|
||||
} else {
|
||||
console.warn('[main] ========================================');
|
||||
console.warn('[main] App auto-updater DISABLED (development mode)');
|
||||
console.warn('[main] To test updater logging, set DEBUG_UPDATER=true');
|
||||
console.warn('[main] Note: Actual updates only work in packaged builds');
|
||||
console.warn('[main] ========================================');
|
||||
}
|
||||
}
|
||||
|
||||
// macOS: re-create window when dock icon is clicked
|
||||
@@ -159,7 +177,7 @@ app.on('before-quit', async () => {
|
||||
// Stop usage monitor
|
||||
const usageMonitor = getUsageMonitor();
|
||||
usageMonitor.stop();
|
||||
console.log('[main] Usage monitor stopped');
|
||||
console.warn('[main] Usage monitor stopped');
|
||||
|
||||
// Kill all running agent processes
|
||||
if (agentManager) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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, `
|
||||
|
||||
@@ -2,19 +2,23 @@ import { ipcMain, app } from 'electron';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { execSync } from 'child_process';
|
||||
import { is } from '@electron-toolkit/utils';
|
||||
import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import type {
|
||||
Project,
|
||||
ProjectSettings,
|
||||
IPCResult,
|
||||
InitializationResult,
|
||||
AutoBuildVersionInfo
|
||||
AutoBuildVersionInfo,
|
||||
GitStatus
|
||||
} from '../../shared/types';
|
||||
import { projectStore } from '../project-store';
|
||||
import {
|
||||
initializeProject,
|
||||
isInitialized,
|
||||
hasLocalSource
|
||||
hasLocalSource,
|
||||
checkGitStatus,
|
||||
initializeGit
|
||||
} from '../project-initializer';
|
||||
import { PythonEnvManager, type PythonEnvStatus } from '../python-env-manager';
|
||||
import { AgentManager } from '../agent';
|
||||
@@ -99,29 +103,68 @@ function detectMainBranch(projectPath: string): string | null {
|
||||
const settingsPath = path.join(app.getPath('userData'), 'settings.json');
|
||||
|
||||
/**
|
||||
* Auto-detect the auto-claude source path relative to the app location
|
||||
* In dev: auto-claude-ui/../auto-claude
|
||||
* In prod: Could be bundled or configured
|
||||
* Auto-detect the auto-claude source path relative to the app location.
|
||||
* Works across platforms (macOS, Windows, Linux) in both dev and production modes.
|
||||
*/
|
||||
const detectAutoBuildSourcePath = (): string | null => {
|
||||
// Try relative to app directory (works in dev and if repo structure is maintained)
|
||||
// __dirname in main process points to out/main in dev
|
||||
const possiblePaths = [
|
||||
// Dev mode: from out/main -> ../../../auto-claude (sibling to auto-claude-ui)
|
||||
path.resolve(__dirname, '..', '..', '..', 'auto-claude'),
|
||||
// Alternative: from app root (useful in some packaged scenarios)
|
||||
path.resolve(app.getAppPath(), '..', 'auto-claude'),
|
||||
// If running from repo root
|
||||
path.resolve(process.cwd(), 'auto-claude'),
|
||||
// Try one more level up (in case of different build output structure)
|
||||
path.resolve(__dirname, '..', '..', 'auto-claude')
|
||||
];
|
||||
const possiblePaths: string[] = [];
|
||||
|
||||
// Development mode paths
|
||||
if (is.dev) {
|
||||
// In dev, __dirname is typically auto-claude-ui/out/main
|
||||
// We need to go up to the project root to find auto-claude/
|
||||
possiblePaths.push(
|
||||
path.resolve(__dirname, '..', '..', '..', 'auto-claude'), // From out/main up 3 levels
|
||||
path.resolve(__dirname, '..', '..', 'auto-claude'), // From out/main up 2 levels
|
||||
path.resolve(process.cwd(), 'auto-claude'), // From cwd (project root)
|
||||
path.resolve(process.cwd(), '..', 'auto-claude') // From cwd parent (if running from auto-claude-ui/)
|
||||
);
|
||||
} else {
|
||||
// Production mode paths (packaged app)
|
||||
// On Windows/Linux/macOS, the app might be installed anywhere
|
||||
// We check common locations relative to the app bundle
|
||||
const appPath = app.getAppPath();
|
||||
possiblePaths.push(
|
||||
path.resolve(appPath, '..', 'auto-claude'), // Sibling to app
|
||||
path.resolve(appPath, '..', '..', 'auto-claude'), // Up 2 from app
|
||||
path.resolve(appPath, '..', '..', '..', 'auto-claude'), // Up 3 from app
|
||||
path.resolve(process.resourcesPath, '..', 'auto-claude'), // Relative to resources
|
||||
path.resolve(process.resourcesPath, '..', '..', 'auto-claude')
|
||||
);
|
||||
}
|
||||
|
||||
// Add process.cwd() as last resort on all platforms
|
||||
possiblePaths.push(path.resolve(process.cwd(), 'auto-claude'));
|
||||
|
||||
// Enable debug logging with AUTO_CLAUDE_DEBUG=1
|
||||
const debug = process.env.AUTO_CLAUDE_DEBUG === '1' || process.env.AUTO_CLAUDE_DEBUG === 'true';
|
||||
|
||||
if (debug) {
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] Platform:', process.platform);
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] Is dev:', is.dev);
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] __dirname:', __dirname);
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] app.getAppPath():', app.getAppPath());
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] process.cwd():', process.cwd());
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] Checking paths:', possiblePaths);
|
||||
}
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
|
||||
// Use requirements.txt as marker - it always exists in auto-claude source
|
||||
const markerPath = path.join(p, 'requirements.txt');
|
||||
const exists = existsSync(p) && existsSync(markerPath);
|
||||
|
||||
if (debug) {
|
||||
console.warn(`[project-handlers:detectAutoBuildSourcePath] Checking ${p}: ${exists ? '✓ FOUND' : '✗ not found'}`);
|
||||
}
|
||||
|
||||
if (exists) {
|
||||
console.warn(`[project-handlers:detectAutoBuildSourcePath] Auto-detected source path: ${p}`);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] Could not auto-detect Auto Claude source path.');
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] Set AUTO_CLAUDE_DEBUG=1 environment variable for detailed path checking.');
|
||||
return null;
|
||||
};
|
||||
|
||||
@@ -154,7 +197,7 @@ const configureServicesWithPython = (
|
||||
autoBuildPath: string,
|
||||
agentManager: AgentManager
|
||||
): void => {
|
||||
console.log('[IPC] Configuring services with Python:', pythonPath);
|
||||
console.warn('[IPC] Configuring services with Python:', pythonPath);
|
||||
agentManager.configure(pythonPath, autoBuildPath);
|
||||
changelogService.configure(pythonPath, autoBuildPath);
|
||||
insightsService.configure(pythonPath, autoBuildPath);
|
||||
@@ -170,7 +213,7 @@ const initializePythonEnvironment = async (
|
||||
): Promise<PythonEnvStatus> => {
|
||||
const autoBuildSource = getAutoBuildSourcePath();
|
||||
if (!autoBuildSource) {
|
||||
console.log('[IPC] Auto-build source not found, skipping Python env init');
|
||||
console.warn('[IPC] Auto-build source not found, skipping Python env init');
|
||||
return {
|
||||
ready: false,
|
||||
pythonPath: null,
|
||||
@@ -180,7 +223,7 @@ const initializePythonEnvironment = async (
|
||||
};
|
||||
}
|
||||
|
||||
console.log('[IPC] Initializing Python environment...');
|
||||
console.warn('[IPC] Initializing Python environment...');
|
||||
const status = await pythonEnvManager.initialize(autoBuildSource);
|
||||
|
||||
if (status.ready && status.pythonPath) {
|
||||
@@ -237,11 +280,11 @@ export function registerProjectHandlers(
|
||||
// If a folder was deleted, reset autoBuildPath so UI prompts for reinitialization
|
||||
const resetIds = projectStore.validateProjects();
|
||||
if (resetIds.length > 0) {
|
||||
console.log('[IPC] PROJECT_LIST: Detected missing .auto-claude folders for', resetIds.length, 'project(s)');
|
||||
console.warn('[IPC] PROJECT_LIST: Detected missing .auto-claude folders for', resetIds.length, 'project(s)');
|
||||
}
|
||||
|
||||
const projects = projectStore.getProjects();
|
||||
console.log('[IPC] PROJECT_LIST returning', projects.length, 'projects');
|
||||
console.warn('[IPC] PROJECT_LIST returning', projects.length, 'projects');
|
||||
return { success: true, data: projects };
|
||||
}
|
||||
);
|
||||
@@ -289,7 +332,7 @@ export function registerProjectHandlers(
|
||||
|
||||
// Initialize Python environment on startup (non-blocking)
|
||||
initializePythonEnvironment(pythonEnvManager, agentManager).then((status) => {
|
||||
console.log('[IPC] Python environment initialized:', status);
|
||||
console.warn('[IPC] Python environment initialized:', status);
|
||||
});
|
||||
|
||||
// IPC handler to get Python environment status
|
||||
@@ -465,4 +508,42 @@ export function registerProjectHandlers(
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Check git status for a project (is it a repo? has commits?)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GIT_CHECK_STATUS,
|
||||
async (_, projectPath: string): Promise<IPCResult<GitStatus>> => {
|
||||
try {
|
||||
if (!existsSync(projectPath)) {
|
||||
return { success: false, error: 'Directory does not exist' };
|
||||
}
|
||||
const gitStatus = checkGitStatus(projectPath);
|
||||
return { success: true, data: gitStatus };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Initialize git in a project (run git init and create initial commit)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GIT_INITIALIZE,
|
||||
async (_, projectPath: string): Promise<IPCResult<InitializationResult>> => {
|
||||
try {
|
||||
if (!existsSync(projectPath)) {
|
||||
return { success: false, error: 'Directory does not exist' };
|
||||
}
|
||||
const result = initializeGit(projectPath);
|
||||
return { success: result.success, data: result, error: result.error };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,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;
|
||||
};
|
||||
|
||||
|
||||
@@ -18,12 +18,12 @@ export function registerTaskArchiveHandlers(): void {
|
||||
taskIds: string[],
|
||||
version?: string
|
||||
): Promise<IPCResult<boolean>> => {
|
||||
console.log('[IPC] TASK_ARCHIVE called with projectId:', projectId, 'taskIds:', taskIds);
|
||||
console.warn('[IPC] TASK_ARCHIVE called with projectId:', projectId, 'taskIds:', taskIds);
|
||||
|
||||
const result = projectStore.archiveTasks(projectId, taskIds, version);
|
||||
|
||||
if (result) {
|
||||
console.log('[IPC] TASK_ARCHIVE success');
|
||||
console.warn('[IPC] TASK_ARCHIVE success');
|
||||
return { success: true, data: true };
|
||||
} else {
|
||||
console.error('[IPC] TASK_ARCHIVE failed');
|
||||
@@ -38,12 +38,12 @@ export function registerTaskArchiveHandlers(): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.TASK_UNARCHIVE,
|
||||
async (_, projectId: string, taskIds: string[]): Promise<IPCResult<boolean>> => {
|
||||
console.log('[IPC] TASK_UNARCHIVE called with projectId:', projectId, 'taskIds:', taskIds);
|
||||
console.warn('[IPC] TASK_UNARCHIVE called with projectId:', projectId, 'taskIds:', taskIds);
|
||||
|
||||
const result = projectStore.unarchiveTasks(projectId, taskIds);
|
||||
|
||||
if (result) {
|
||||
console.log('[IPC] TASK_UNARCHIVE success');
|
||||
console.warn('[IPC] TASK_UNARCHIVE success');
|
||||
return { success: true, data: true };
|
||||
} else {
|
||||
console.error('[IPC] TASK_UNARCHIVE failed');
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ipcMain } from 'electron';
|
||||
import { IPC_CHANNELS, AUTO_BUILD_PATHS, getSpecsDir } from '../../../shared/constants';
|
||||
import type { IPCResult, Task, TaskMetadata, Project } from '../../../shared/types';
|
||||
import type { IPCResult, Task, TaskMetadata } from '../../../shared/types';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync, writeFileSync, readdirSync, mkdirSync } from 'fs';
|
||||
import { projectStore } from '../../project-store';
|
||||
@@ -18,9 +18,9 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.TASK_LIST,
|
||||
async (_, projectId: string): Promise<IPCResult<Task[]>> => {
|
||||
console.log('[IPC] TASK_LIST called with projectId:', projectId);
|
||||
console.warn('[IPC] TASK_LIST called with projectId:', projectId);
|
||||
const tasks = projectStore.getTasks(projectId);
|
||||
console.log('[IPC] TASK_LIST returning', tasks.length, 'tasks');
|
||||
console.warn('[IPC] TASK_LIST returning', tasks.length, 'tasks');
|
||||
return { success: true, data: tasks };
|
||||
}
|
||||
);
|
||||
@@ -45,17 +45,17 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
|
||||
// Auto-generate title if empty using Claude AI
|
||||
let finalTitle = title;
|
||||
if (!title || !title.trim()) {
|
||||
console.log('[TASK_CREATE] Title is empty, generating with Claude AI...');
|
||||
console.warn('[TASK_CREATE] Title is empty, generating with Claude AI...');
|
||||
try {
|
||||
const generatedTitle = await titleGenerator.generateTitle(description);
|
||||
if (generatedTitle) {
|
||||
finalTitle = generatedTitle;
|
||||
console.log('[TASK_CREATE] Generated title:', finalTitle);
|
||||
console.warn('[TASK_CREATE] Generated title:', finalTitle);
|
||||
} else {
|
||||
// Fallback: create title from first line of description
|
||||
finalTitle = description.split('\n')[0].substring(0, 60);
|
||||
if (finalTitle.length === 60) finalTitle += '...';
|
||||
console.log('[TASK_CREATE] AI generation failed, using fallback:', finalTitle);
|
||||
console.warn('[TASK_CREATE] AI generation failed, using fallback:', finalTitle);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[TASK_CREATE] Title generation error:', err);
|
||||
@@ -226,7 +226,7 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
|
||||
try {
|
||||
if (existsSync(specDir)) {
|
||||
await rm(specDir, { recursive: true, force: true });
|
||||
console.log(`[TASK_DELETE] Deleted spec directory: ${specDir}`);
|
||||
console.warn(`[TASK_DELETE] Deleted spec directory: ${specDir}`);
|
||||
}
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
@@ -269,17 +269,17 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
|
||||
if (updates.title !== undefined && !updates.title.trim()) {
|
||||
// Get description to use for title generation
|
||||
const descriptionToUse = updates.description ?? task.description;
|
||||
console.log('[TASK_UPDATE] Title is empty, generating with Claude AI...');
|
||||
console.warn('[TASK_UPDATE] Title is empty, generating with Claude AI...');
|
||||
try {
|
||||
const generatedTitle = await titleGenerator.generateTitle(descriptionToUse);
|
||||
if (generatedTitle) {
|
||||
finalTitle = generatedTitle;
|
||||
console.log('[TASK_UPDATE] Generated title:', finalTitle);
|
||||
console.warn('[TASK_UPDATE] Generated title:', finalTitle);
|
||||
} else {
|
||||
// Fallback: create title from first line of description
|
||||
finalTitle = descriptionToUse.split('\n')[0].substring(0, 60);
|
||||
if (finalTitle.length === 60) finalTitle += '...';
|
||||
console.log('[TASK_UPDATE] AI generation failed, using fallback:', finalTitle);
|
||||
console.warn('[TASK_UPDATE] AI generation failed, using fallback:', finalTitle);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[TASK_UPDATE] Title generation error:', err);
|
||||
|
||||
@@ -6,6 +6,7 @@ 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)
|
||||
@@ -20,10 +21,10 @@ export function registerTaskExecutionHandlers(
|
||||
ipcMain.on(
|
||||
IPC_CHANNELS.TASK_START,
|
||||
(_, taskId: string, _options?: TaskStartOptions) => {
|
||||
console.log('[TASK_START] Received request for taskId:', taskId);
|
||||
console.warn('[TASK_START] Received request for taskId:', taskId);
|
||||
const mainWindow = getMainWindow();
|
||||
if (!mainWindow) {
|
||||
console.log('[TASK_START] No main window found');
|
||||
console.warn('[TASK_START] No main window found');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -31,7 +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,7 +82,7 @@ export function registerTaskExecutionHandlers(
|
||||
const needsSpecCreation = !hasSpec;
|
||||
const needsImplementation = hasSpec && task.subtasks.length === 0;
|
||||
|
||||
console.log('[TASK_START] hasSpec:', hasSpec, 'needsSpecCreation:', needsSpecCreation, 'needsImplementation:', needsImplementation);
|
||||
console.warn('[TASK_START] hasSpec:', hasSpec, 'needsSpecCreation:', needsSpecCreation, 'needsImplementation:', needsImplementation);
|
||||
|
||||
// Get base branch from project settings for worktree creation
|
||||
const baseBranch = project.settings?.mainBranch;
|
||||
@@ -68,7 +90,7 @@ export function registerTaskExecutionHandlers(
|
||||
if (needsSpecCreation) {
|
||||
// No spec file - need to run spec_runner.py to create the spec
|
||||
const taskDescription = task.description || task.title;
|
||||
console.log('[TASK_START] Starting spec creation for:', task.specId, 'in:', specDir);
|
||||
console.warn('[TASK_START] Starting spec creation for:', task.specId, 'in:', specDir);
|
||||
|
||||
// Start spec creation process - pass the existing spec directory
|
||||
// so spec_runner uses it instead of creating a new one
|
||||
@@ -83,7 +105,7 @@ export function registerTaskExecutionHandlers(
|
||||
// Use default description
|
||||
}
|
||||
|
||||
console.log('[TASK_START] Starting task execution (no subtasks) for:', task.specId);
|
||||
console.warn('[TASK_START] Starting task execution (no subtasks) for:', task.specId);
|
||||
// Start task execution which will create the implementation plan
|
||||
// Note: No parallel mode for planning phase - parallel only makes sense with multiple subtasks
|
||||
agentManager.startTaskExecution(
|
||||
@@ -99,7 +121,7 @@ export function registerTaskExecutionHandlers(
|
||||
} else {
|
||||
// Task has subtasks, start normal execution
|
||||
// Note: Parallel execution is handled internally by the agent, not via CLI flags
|
||||
console.log('[TASK_START] Starting task execution (has subtasks) for:', task.specId);
|
||||
console.warn('[TASK_START] Starting task execution (has subtasks) for:', task.specId);
|
||||
|
||||
agentManager.startTaskExecution(
|
||||
taskId,
|
||||
@@ -216,23 +238,33 @@ export function registerTaskExecutionHandlers(
|
||||
taskId: string,
|
||||
status: TaskStatus
|
||||
): Promise<IPCResult> => {
|
||||
// Validate status transition - 'done' can only be set through merge handler
|
||||
// This prevents AI agents from bypassing the human review workflow
|
||||
if (status === 'done') {
|
||||
console.warn(`[TASK_UPDATE_STATUS] Blocked attempt to set status 'done' directly for task ${taskId}. Use merge workflow instead.`);
|
||||
return {
|
||||
success: false,
|
||||
error: "Cannot set status to 'done' directly. Complete the human review and merge the worktree changes instead."
|
||||
};
|
||||
}
|
||||
|
||||
// Find task and project
|
||||
// Find task and project first (needed for worktree check)
|
||||
const { task, project } = findTaskAndProject(taskId);
|
||||
|
||||
if (!task || !project) {
|
||||
return { success: false, error: 'Task not found' };
|
||||
}
|
||||
|
||||
// Validate status transition - 'done' can only be set through merge handler
|
||||
// UNLESS there's no worktree (limbo state - already merged/discarded or failed)
|
||||
if (status === 'done') {
|
||||
// Check if worktree exists
|
||||
const worktreePath = path.join(project.path, '.worktrees', taskId);
|
||||
const hasWorktree = existsSync(worktreePath);
|
||||
|
||||
if (hasWorktree) {
|
||||
// Worktree exists - must use merge workflow
|
||||
console.warn(`[TASK_UPDATE_STATUS] Blocked attempt to set status 'done' directly for task ${taskId}. Use merge workflow instead.`);
|
||||
return {
|
||||
success: false,
|
||||
error: "Cannot set status to 'done' directly. Complete the human review and merge the worktree changes instead."
|
||||
};
|
||||
} else {
|
||||
// No worktree - allow marking as done (limbo state recovery)
|
||||
console.log(`[TASK_UPDATE_STATUS] Allowing status 'done' for task ${taskId} (no worktree found - limbo state)`);
|
||||
}
|
||||
}
|
||||
|
||||
// Get the spec directory
|
||||
const specsBaseDir = getSpecsDir(project.autoBuildPath);
|
||||
const specDir = path.join(
|
||||
@@ -252,17 +284,16 @@ export function registerTaskExecutionHandlers(
|
||||
// Store the exact UI status - project-store.ts will map it back
|
||||
plan.status = status;
|
||||
// Also store mapped version for Python compatibility
|
||||
// Note: 'done' is blocked at the start of this handler - only set via merge workflow
|
||||
plan.planStatus = status === 'in_progress' ? 'in_progress'
|
||||
: status === 'ai_review' ? 'review'
|
||||
: status === 'human_review' ? 'review'
|
||||
: status === 'done' ? 'completed'
|
||||
: 'pending';
|
||||
plan.updated_at = new Date().toISOString();
|
||||
|
||||
writeFileSync(planPath, JSON.stringify(plan, null, 2));
|
||||
} else {
|
||||
// If no implementation plan exists yet, create a basic one
|
||||
// Note: 'done' status is blocked at the start of this handler
|
||||
const plan = {
|
||||
feature: task.title,
|
||||
description: task.description || '',
|
||||
@@ -272,6 +303,7 @@ export function registerTaskExecutionHandlers(
|
||||
planStatus: status === 'in_progress' ? 'in_progress'
|
||||
: status === 'ai_review' ? 'review'
|
||||
: status === 'human_review' ? 'review'
|
||||
: status === 'done' ? 'completed'
|
||||
: 'pending',
|
||||
phases: []
|
||||
};
|
||||
@@ -287,7 +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);
|
||||
@@ -298,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,
|
||||
@@ -320,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,
|
||||
@@ -498,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';
|
||||
@@ -523,11 +587,11 @@ export function registerTaskExecutionHandlers(
|
||||
if (needsSpecCreation) {
|
||||
// No spec file - need to run spec_runner.py to create the spec
|
||||
const taskDescription = task.description || task.title;
|
||||
console.log(`[Recovery] Starting spec creation for: ${task.specId}`);
|
||||
console.warn(`[Recovery] Starting spec creation for: ${task.specId}`);
|
||||
agentManager.startSpecCreation(task.specId, project.path, taskDescription, specDirForWatcher, task.metadata);
|
||||
} else {
|
||||
// Spec exists - run task execution
|
||||
console.log(`[Recovery] Starting task execution for: ${task.specId}`);
|
||||
console.warn(`[Recovery] Starting task execution for: ${task.specId}`);
|
||||
agentManager.startTaskExecution(
|
||||
taskId,
|
||||
project.path,
|
||||
@@ -540,7 +604,7 @@ export function registerTaskExecutionHandlers(
|
||||
}
|
||||
|
||||
autoRestarted = true;
|
||||
console.log(`[Recovery] Auto-restarted task ${taskId}`);
|
||||
console.warn(`[Recovery] Auto-restarted task ${taskId}`);
|
||||
} catch (restartError) {
|
||||
console.error('Failed to auto-restart task after recovery:', restartError);
|
||||
// Recovery succeeded but restart failed - still report success
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ipcMain, BrowserWindow } from 'electron';
|
||||
import { IPC_CHANNELS, AUTO_BUILD_PATHS, getSpecsDir } from '../../../shared/constants';
|
||||
import { IPC_CHANNELS, AUTO_BUILD_PATHS } from '../../../shared/constants';
|
||||
import type { IPCResult, WorktreeStatus, WorktreeDiff, WorktreeDiffFile, WorktreeMergeResult, WorktreeDiscardResult, WorktreeListResult, WorktreeListItem } from '../../../shared/types';
|
||||
import path from 'path';
|
||||
import { existsSync, readdirSync, statSync } from 'fs';
|
||||
@@ -226,11 +226,11 @@ export function registerWorktreeHandlers(
|
||||
async (_, taskId: string, options?: { noCommit?: boolean }): Promise<IPCResult<WorktreeMergeResult>> => {
|
||||
// Always log merge operations for debugging
|
||||
const debug = (...args: unknown[]) => {
|
||||
console.log('[MERGE DEBUG]', ...args);
|
||||
console.warn('[MERGE DEBUG]', ...args);
|
||||
};
|
||||
|
||||
try {
|
||||
console.log('[MERGE] Handler called with taskId:', taskId, 'options:', options);
|
||||
console.warn('[MERGE] Handler called with taskId:', taskId, 'options:', options);
|
||||
debug('Starting merge for taskId:', taskId, 'options:', options);
|
||||
|
||||
// Ensure Python environment is ready
|
||||
@@ -315,7 +315,9 @@ export function registerWorktreeHandlers(
|
||||
env: {
|
||||
...process.env,
|
||||
...profileEnv, // Include active Claude profile OAuth token
|
||||
PYTHONUNBUFFERED: '1'
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
},
|
||||
stdio: ['ignore', 'pipe', 'pipe'] // Don't connect stdin to avoid blocking
|
||||
});
|
||||
@@ -499,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);
|
||||
@@ -522,7 +524,7 @@ export function registerWorktreeHandlers(
|
||||
console.error('[IPC] Task not found:', taskId);
|
||||
return { success: false, error: 'Task not found' };
|
||||
}
|
||||
console.log('[IPC] Found task:', task.specId, 'project:', project.name);
|
||||
console.warn('[IPC] Found task:', task.specId, 'project:', project.name);
|
||||
|
||||
// Check for uncommitted changes in the main project
|
||||
let hasUncommittedChanges = false;
|
||||
@@ -539,7 +541,7 @@ export function registerWorktreeHandlers(
|
||||
.filter(line => line.trim())
|
||||
.map(line => line.substring(3).trim()); // Remove status prefix (e.g., "M ", " M ", "?? ")
|
||||
hasUncommittedChanges = uncommittedFiles.length > 0;
|
||||
console.log('[IPC] Uncommitted changes detected:', uncommittedFiles.length, 'files');
|
||||
console.warn('[IPC] Uncommitted changes detected:', uncommittedFiles.length, 'files');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[IPC] Failed to check git status:', e);
|
||||
@@ -560,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();
|
||||
@@ -568,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 = '';
|
||||
@@ -577,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: {
|
||||
|
||||
@@ -208,7 +208,7 @@ export function registerTerminalHandlers(
|
||||
const { mkdirSync, existsSync } = await import('fs');
|
||||
if (!existsSync(profile.configDir)) {
|
||||
mkdirSync(profile.configDir, { recursive: true });
|
||||
console.log('[IPC] Created config directory:', profile.configDir);
|
||||
console.warn('[IPC] Created config directory:', profile.configDir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,7 +217,7 @@ export function registerTerminalHandlers(
|
||||
const terminalId = `claude-login-${profileId}-${Date.now()}`;
|
||||
const homeDir = process.env.HOME || process.env.USERPROFILE || '/tmp';
|
||||
|
||||
console.log('[IPC] Initializing Claude profile:', {
|
||||
console.warn('[IPC] Initializing Claude profile:', {
|
||||
profileId,
|
||||
profileName: profile.name,
|
||||
configDir: profile.configDir,
|
||||
@@ -240,7 +240,7 @@ export function registerTerminalHandlers(
|
||||
loginCommand = 'claude setup-token';
|
||||
}
|
||||
|
||||
console.log('[IPC] Sending login command to terminal:', loginCommand);
|
||||
console.warn('[IPC] Sending login command to terminal:', loginCommand);
|
||||
|
||||
// Write the login command to the terminal
|
||||
terminalManager.write(terminalId, `${loginCommand}\r`);
|
||||
@@ -255,12 +255,12 @@ export function registerTerminalHandlers(
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
terminalId,
|
||||
message: `A terminal has been opened to authenticate "${profile.name}". Complete the OAuth flow in your browser, then copy the token shown in the terminal.`
|
||||
}
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[IPC] Failed to initialize Claude profile:', error);
|
||||
@@ -569,5 +569,5 @@ export function initializeUsageMonitorForwarding(mainWindow: BrowserWindow): voi
|
||||
mainWindow.webContents.send(IPC_CHANNELS.PROACTIVE_SWAP_NOTIFICATION, notification);
|
||||
});
|
||||
|
||||
console.log('[terminal-handlers] Usage monitor event forwarding initialized');
|
||||
console.warn('[terminal-handlers] Usage monitor event forwarding initialized');
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ export interface LogEntry {
|
||||
|
||||
/**
|
||||
* Service for persisting and retrieving task execution logs
|
||||
*
|
||||
*
|
||||
* Log files are stored in {specDir}/logs/ with format:
|
||||
* - session-{ISO-timestamp}.log - Raw log output per execution session
|
||||
* - latest.log - Copy of most recent session's logs
|
||||
@@ -26,7 +26,7 @@ export class LogService {
|
||||
private activeSessions: Map<string, { sessionId: string; logPath: string; startedAt: Date }> = new Map();
|
||||
private logBuffers: Map<string, string[]> = new Map();
|
||||
private flushIntervals: Map<string, NodeJS.Timeout> = new Map();
|
||||
|
||||
|
||||
// Flush logs to disk every 2 seconds to balance performance vs data safety
|
||||
private readonly FLUSH_INTERVAL_MS = 2000;
|
||||
// Maximum log file size before rotation (10MB)
|
||||
@@ -39,7 +39,7 @@ export class LogService {
|
||||
*/
|
||||
startSession(taskId: string, specDir: string): string {
|
||||
const logsDir = path.join(specDir, 'logs');
|
||||
|
||||
|
||||
// Ensure logs directory exists
|
||||
if (!existsSync(logsDir)) {
|
||||
mkdirSync(logsDir, { recursive: true });
|
||||
@@ -60,7 +60,7 @@ export class LogService {
|
||||
'='.repeat(80),
|
||||
''
|
||||
].join('\n');
|
||||
|
||||
|
||||
writeFileSync(logFile, header);
|
||||
|
||||
// Track active session
|
||||
@@ -82,7 +82,7 @@ export class LogService {
|
||||
// Clean up old sessions
|
||||
this.cleanupOldSessions(logsDir);
|
||||
|
||||
console.log(`[LogService] Started session ${sessionId} for task ${taskId}`);
|
||||
console.warn(`[LogService] Started session ${sessionId} for task ${taskId}`);
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ export class LogService {
|
||||
private flushBuffer(taskId: string): void {
|
||||
const session = this.activeSessions.get(taskId);
|
||||
const buffer = this.logBuffers.get(taskId);
|
||||
|
||||
|
||||
if (!session || !buffer || buffer.length === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -150,7 +150,7 @@ export class LogService {
|
||||
const now = new Date();
|
||||
const duration = now.getTime() - session.startedAt.getTime();
|
||||
const durationStr = this.formatDuration(duration);
|
||||
|
||||
|
||||
const footer = [
|
||||
'',
|
||||
'='.repeat(80),
|
||||
@@ -181,7 +181,7 @@ export class LogService {
|
||||
this.activeSessions.delete(taskId);
|
||||
this.logBuffers.delete(taskId);
|
||||
|
||||
console.log(`[LogService] Ended session for task ${taskId}, exit code: ${exitCode}`);
|
||||
console.warn(`[LogService] Ended session for task ${taskId}, exit code: ${exitCode}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -189,7 +189,7 @@ export class LogService {
|
||||
*/
|
||||
getSessions(specDir: string): LogSession[] {
|
||||
const logsDir = path.join(specDir, 'logs');
|
||||
|
||||
|
||||
if (!existsSync(logsDir)) {
|
||||
return [];
|
||||
}
|
||||
@@ -203,7 +203,7 @@ export class LogService {
|
||||
const filePath = path.join(logsDir, file);
|
||||
const stats = statSync(filePath);
|
||||
const sessionId = file.replace('session-', '').replace('.log', '');
|
||||
|
||||
|
||||
// Parse session ID back to date
|
||||
const dateStr = sessionId.replace(/-/g, (match, offset) => {
|
||||
// Replace first 2 dashes with actual dashes, rest with colons
|
||||
@@ -211,7 +211,7 @@ export class LogService {
|
||||
if (offset === 10) return 'T';
|
||||
return ':';
|
||||
}).replace(/-(\d{3})Z$/, '.$1Z');
|
||||
|
||||
|
||||
const startedAt = new Date(dateStr);
|
||||
|
||||
// Count lines (approximate)
|
||||
@@ -233,7 +233,7 @@ export class LogService {
|
||||
*/
|
||||
loadSessionLogs(specDir: string, sessionId?: string): string {
|
||||
const logsDir = path.join(specDir, 'logs');
|
||||
|
||||
|
||||
if (!existsSync(logsDir)) {
|
||||
return '';
|
||||
}
|
||||
@@ -289,17 +289,17 @@ export class LogService {
|
||||
|
||||
// Keep MAX_SESSIONS_TO_KEEP, delete the rest
|
||||
const toDelete = files.slice(this.MAX_SESSIONS_TO_KEEP);
|
||||
|
||||
|
||||
for (const file of toDelete) {
|
||||
const filePath = path.join(logsDir, file);
|
||||
try {
|
||||
require('fs').unlinkSync(filePath);
|
||||
console.log(`[LogService] Deleted old log session: ${file}`);
|
||||
} catch (e) {
|
||||
console.warn(`[LogService] Deleted old log session: ${file}`);
|
||||
} catch (_e) {
|
||||
// Ignore deletion errors
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
} catch (_error) {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
@@ -339,4 +339,3 @@ export class LogService {
|
||||
|
||||
// Singleton instance
|
||||
export const logService = new LogService();
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { existsSync, mkdirSync, writeFileSync, readFileSync, appendFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
/**
|
||||
* Debug logging - only logs when AUTO_CLAUDE_DEBUG env var is set
|
||||
@@ -9,13 +10,144 @@ const DEBUG = process.env.AUTO_CLAUDE_DEBUG === 'true' || process.env.AUTO_CLAUD
|
||||
function debug(message: string, data?: Record<string, unknown>): void {
|
||||
if (DEBUG) {
|
||||
if (data) {
|
||||
console.log(`[ProjectInitializer] ${message}`, JSON.stringify(data, null, 2));
|
||||
console.warn(`[ProjectInitializer] ${message}`, JSON.stringify(data, null, 2));
|
||||
} else {
|
||||
console.log(`[ProjectInitializer] ${message}`);
|
||||
console.warn(`[ProjectInitializer] ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Git status information for a project
|
||||
*/
|
||||
export interface GitStatus {
|
||||
isGitRepo: boolean;
|
||||
hasCommits: boolean;
|
||||
currentBranch: string | null;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a directory is a git repository and has at least one commit
|
||||
*/
|
||||
export function checkGitStatus(projectPath: string): GitStatus {
|
||||
try {
|
||||
// Check if it's a git repository
|
||||
execSync('git rev-parse --git-dir', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
});
|
||||
} catch {
|
||||
return {
|
||||
isGitRepo: false,
|
||||
hasCommits: false,
|
||||
currentBranch: null,
|
||||
error: 'Not a git repository. Please run "git init" to initialize git.'
|
||||
};
|
||||
}
|
||||
|
||||
// Check if there are any commits
|
||||
let hasCommits = false;
|
||||
try {
|
||||
execSync('git rev-parse HEAD', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
});
|
||||
hasCommits = true;
|
||||
} catch {
|
||||
// No commits yet
|
||||
hasCommits = false;
|
||||
}
|
||||
|
||||
// Get current branch
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = execSync('git rev-parse --abbrev-ref HEAD', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
}).trim();
|
||||
} catch {
|
||||
// Branch detection failed
|
||||
}
|
||||
|
||||
if (!hasCommits) {
|
||||
return {
|
||||
isGitRepo: true,
|
||||
hasCommits: false,
|
||||
currentBranch,
|
||||
error: 'Git repository has no commits. Please make an initial commit first.'
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
isGitRepo: true,
|
||||
hasCommits: true,
|
||||
currentBranch
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize git in a project directory and create an initial commit.
|
||||
* This is a user-friendly way to set up git for non-technical users.
|
||||
*/
|
||||
export function initializeGit(projectPath: string): InitializationResult {
|
||||
debug('initializeGit called', { projectPath });
|
||||
|
||||
// Check current git status
|
||||
const status = checkGitStatus(projectPath);
|
||||
|
||||
try {
|
||||
// Step 1: Initialize git if needed
|
||||
if (!status.isGitRepo) {
|
||||
debug('Initializing git repository');
|
||||
execSync('git init', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
});
|
||||
}
|
||||
|
||||
// Step 2: Check if there are files to commit
|
||||
const statusOutput = execSync('git status --porcelain', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
}).trim();
|
||||
|
||||
// Step 3: If there are untracked/modified files, add and commit them
|
||||
if (statusOutput || !status.hasCommits) {
|
||||
debug('Adding files and creating initial commit');
|
||||
|
||||
// Add all files
|
||||
execSync('git add -A', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
});
|
||||
|
||||
// Create initial commit
|
||||
execSync('git commit -m "Initial commit" --allow-empty', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
});
|
||||
}
|
||||
|
||||
debug('Git initialization complete');
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error during git initialization';
|
||||
debug('Git initialization failed', { error: errorMessage });
|
||||
return {
|
||||
success: false,
|
||||
error: errorMessage
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Entries to add to .gitignore when initializing a project
|
||||
*/
|
||||
@@ -101,8 +233,9 @@ export interface InitializationResult {
|
||||
*/
|
||||
export function hasLocalSource(projectPath: string): boolean {
|
||||
const localSourcePath = path.join(projectPath, 'auto-claude');
|
||||
const versionFile = path.join(localSourcePath, 'VERSION');
|
||||
return existsSync(localSourcePath) && existsSync(versionFile);
|
||||
// Use requirements.txt as marker - it always exists in auto-claude source
|
||||
const markerFile = path.join(localSourcePath, 'requirements.txt');
|
||||
return existsSync(localSourcePath) && existsSync(markerFile);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -129,6 +262,10 @@ export function isInitialized(projectPath: string): boolean {
|
||||
*
|
||||
* Creates .auto-claude/ with data directories (specs, ideation, insights, roadmap).
|
||||
* The framework code runs from the source repo - only data is stored here.
|
||||
*
|
||||
* Requires:
|
||||
* - Project directory must exist
|
||||
* - Project must be a git repository with at least one commit
|
||||
*/
|
||||
export function initializeProject(projectPath: string): InitializationResult {
|
||||
debug('initializeProject called', { projectPath });
|
||||
@@ -142,6 +279,16 @@ export function initializeProject(projectPath: string): InitializationResult {
|
||||
};
|
||||
}
|
||||
|
||||
// Check git status - Auto Claude requires git for worktree-based builds
|
||||
const gitStatus = checkGitStatus(projectPath);
|
||||
if (!gitStatus.isGitRepo || !gitStatus.hasCommits) {
|
||||
debug('Git check failed', { gitStatus });
|
||||
return {
|
||||
success: false,
|
||||
error: gitStatus.error || 'Git repository required. Auto Claude uses git worktrees for isolated builds.'
|
||||
};
|
||||
}
|
||||
|
||||
// Check if already initialized
|
||||
const dotAutoBuildPath = path.join(projectPath, '.auto-claude');
|
||||
|
||||
|
||||
@@ -145,13 +145,13 @@ export class ProjectStore {
|
||||
|
||||
// Check if the project path still exists
|
||||
if (!existsSync(project.path)) {
|
||||
console.log(`[ProjectStore] Project path no longer exists: ${project.path}`);
|
||||
console.warn(`[ProjectStore] Project path no longer exists: ${project.path}`);
|
||||
continue; // Don't reset - let user handle this case
|
||||
}
|
||||
|
||||
// Check if .auto-claude folder still exists
|
||||
if (!isInitialized(project.path)) {
|
||||
console.log(`[ProjectStore] .auto-claude folder missing for project "${project.name}" at ${project.path}`);
|
||||
console.warn(`[ProjectStore] .auto-claude folder missing for project "${project.name}" at ${project.path}`);
|
||||
project.autoBuildPath = '';
|
||||
project.updatedAt = new Date();
|
||||
resetProjectIds.push(project.id);
|
||||
@@ -161,7 +161,7 @@ export class ProjectStore {
|
||||
|
||||
if (hasChanges) {
|
||||
this.save();
|
||||
console.log(`[ProjectStore] Reset ${resetProjectIds.length} project(s) due to missing .auto-claude folder`);
|
||||
console.warn(`[ProjectStore] Reset ${resetProjectIds.length} project(s) due to missing .auto-claude folder`);
|
||||
}
|
||||
|
||||
return resetProjectIds;
|
||||
@@ -194,18 +194,18 @@ export class ProjectStore {
|
||||
* Get tasks for a project by scanning specs directory
|
||||
*/
|
||||
getTasks(projectId: string): Task[] {
|
||||
console.log('[ProjectStore] getTasks called with projectId:', projectId);
|
||||
console.warn('[ProjectStore] getTasks called with projectId:', projectId);
|
||||
const project = this.getProject(projectId);
|
||||
if (!project) {
|
||||
console.log('[ProjectStore] Project not found for id:', projectId);
|
||||
console.warn('[ProjectStore] Project not found for id:', projectId);
|
||||
return [];
|
||||
}
|
||||
console.log('[ProjectStore] Found project:', project.name, 'autoBuildPath:', project.autoBuildPath);
|
||||
console.warn('[ProjectStore] Found project:', project.name, 'autoBuildPath:', project.autoBuildPath);
|
||||
|
||||
// Get specs directory path
|
||||
const specsBaseDir = getSpecsDir(project.autoBuildPath);
|
||||
const specsDir = path.join(project.path, specsBaseDir);
|
||||
console.log('[ProjectStore] specsDir:', specsDir, 'exists:', existsSync(specsDir));
|
||||
console.warn('[ProjectStore] specsDir:', specsDir, 'exists:', existsSync(specsDir));
|
||||
if (!existsSync(specsDir)) return [];
|
||||
|
||||
const tasks: Task[] = [];
|
||||
@@ -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 {};
|
||||
}
|
||||
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -15,7 +15,20 @@ const SOCKET_PATH =
|
||||
? `\\\\.\\pipe\\auto-claude-pty-${process.getuid?.() || 'default'}`
|
||||
: `/tmp/auto-claude-pty-${process.getuid?.() || 'default'}.sock`;
|
||||
|
||||
type ResponseHandler = (response: any) => void;
|
||||
interface DaemonResponseData {
|
||||
exitCode?: number;
|
||||
signal?: number;
|
||||
}
|
||||
|
||||
interface DaemonResponse {
|
||||
requestId?: string;
|
||||
type: string;
|
||||
id?: string;
|
||||
data?: string | DaemonResponseData;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
type ResponseHandler = (response: DaemonResponse) => void;
|
||||
|
||||
interface PtyConfig {
|
||||
shell: string;
|
||||
@@ -62,13 +75,13 @@ class PtyDaemonClient {
|
||||
try {
|
||||
// Try to connect to existing daemon
|
||||
await this.tryConnect();
|
||||
console.log('[PtyDaemonClient] Connected to existing daemon');
|
||||
console.warn('[PtyDaemonClient] Connected to existing daemon');
|
||||
} catch {
|
||||
// Spawn daemon and connect
|
||||
console.log('[PtyDaemonClient] Spawning new daemon...');
|
||||
console.warn('[PtyDaemonClient] Spawning new daemon...');
|
||||
await this.spawnDaemon();
|
||||
await this.tryConnect();
|
||||
console.log('[PtyDaemonClient] Connected to new daemon');
|
||||
console.warn('[PtyDaemonClient] Connected to new daemon');
|
||||
} finally {
|
||||
this.isConnecting = false;
|
||||
this.reconnectAttempts = 0;
|
||||
@@ -119,7 +132,7 @@ class PtyDaemonClient {
|
||||
// Unref so parent can exit independently
|
||||
this.daemonProcess.unref();
|
||||
|
||||
console.log(`[PtyDaemonClient] Spawned daemon process (PID: ${this.daemonProcess.pid})`);
|
||||
console.warn(`[PtyDaemonClient] Spawned daemon process (PID: ${this.daemonProcess.pid})`);
|
||||
|
||||
// Wait for daemon to start listening
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
@@ -154,7 +167,7 @@ class PtyDaemonClient {
|
||||
});
|
||||
|
||||
this.socket.on('close', () => {
|
||||
console.log('[PtyDaemonClient] Disconnected from daemon');
|
||||
console.warn('[PtyDaemonClient] Disconnected from daemon');
|
||||
this.socket = null;
|
||||
if (!this.isShuttingDown) {
|
||||
this.attemptReconnect();
|
||||
@@ -169,7 +182,7 @@ class PtyDaemonClient {
|
||||
/**
|
||||
* Handle response from daemon
|
||||
*/
|
||||
private handleResponse(response: any): void {
|
||||
private handleResponse(response: DaemonResponse): void {
|
||||
// Handle request-response pattern
|
||||
if (response.requestId) {
|
||||
const handler = this.pendingRequests.get(response.requestId);
|
||||
@@ -183,7 +196,7 @@ class PtyDaemonClient {
|
||||
// Handle streaming data
|
||||
if (response.type === 'data' && response.id) {
|
||||
const handler = this.dataHandlers.get(response.id);
|
||||
if (handler) {
|
||||
if (handler && typeof response.data === 'string') {
|
||||
handler(response.data);
|
||||
}
|
||||
return;
|
||||
@@ -192,8 +205,9 @@ class PtyDaemonClient {
|
||||
// Handle exit events
|
||||
if (response.type === 'exit' && response.id) {
|
||||
const handler = this.exitHandlers.get(response.id);
|
||||
if (handler) {
|
||||
handler(response.data.exitCode, response.data.signal);
|
||||
if (handler && typeof response.data === 'object' && response.data !== null) {
|
||||
const exitData = response.data as DaemonResponseData;
|
||||
handler(exitData.exitCode ?? 0, exitData.signal);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -213,7 +227,7 @@ class PtyDaemonClient {
|
||||
this.reconnectAttempts++;
|
||||
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 10000);
|
||||
|
||||
console.log(
|
||||
console.warn(
|
||||
`[PtyDaemonClient] Reconnect attempt ${this.reconnectAttempts} in ${delay}ms...`
|
||||
);
|
||||
|
||||
@@ -227,7 +241,7 @@ class PtyDaemonClient {
|
||||
/**
|
||||
* Send a request and wait for response
|
||||
*/
|
||||
private async request<T>(msg: any): Promise<T> {
|
||||
private async request<T>(msg: Record<string, unknown>): Promise<T> {
|
||||
await this.connect();
|
||||
|
||||
if (!this.socket) {
|
||||
@@ -258,7 +272,7 @@ class PtyDaemonClient {
|
||||
/**
|
||||
* Send a message without expecting a response
|
||||
*/
|
||||
private send(msg: any): void {
|
||||
private send(msg: Record<string, unknown>): void {
|
||||
if (!this.socket) {
|
||||
console.warn('[PtyDaemonClient] Cannot send - not connected');
|
||||
return;
|
||||
|
||||
@@ -56,14 +56,14 @@ interface DaemonMessage {
|
||||
| 'get-buffer'
|
||||
| 'ping';
|
||||
id?: string;
|
||||
data?: any;
|
||||
data?: unknown;
|
||||
requestId?: string;
|
||||
}
|
||||
|
||||
interface DaemonResponse {
|
||||
type: 'created' | 'list' | 'buffer' | 'data' | 'exit' | 'error' | 'pong';
|
||||
id?: string;
|
||||
data?: any;
|
||||
data?: unknown;
|
||||
requestId?: string;
|
||||
error?: string;
|
||||
}
|
||||
@@ -102,9 +102,9 @@ class PtyDaemon {
|
||||
this.handleConnection(socket);
|
||||
});
|
||||
|
||||
this.server.on('error', (err) => {
|
||||
this.server.on('error', (err: NodeJS.ErrnoException) => {
|
||||
console.error('[PTY Daemon] Server error:', err);
|
||||
if ((err as any).code === 'EADDRINUSE') {
|
||||
if (err.code === 'EADDRINUSE') {
|
||||
console.error('[PTY Daemon] Address in use - another daemon may be running');
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -172,20 +172,22 @@ class PtyDaemon {
|
||||
break;
|
||||
|
||||
case 'create': {
|
||||
const id = this.createPty(msg.data);
|
||||
const id = this.createPty(msg.data as PtyConfig);
|
||||
this.send(socket, { type: 'created', id, requestId: msg.requestId });
|
||||
break;
|
||||
}
|
||||
|
||||
case 'write':
|
||||
if (!msg.id) throw new Error('Missing PTY id');
|
||||
this.writeToPty(msg.id, msg.data);
|
||||
this.writeToPty(msg.id, msg.data as string);
|
||||
break;
|
||||
|
||||
case 'resize':
|
||||
case 'resize': {
|
||||
if (!msg.id) throw new Error('Missing PTY id');
|
||||
this.resizePty(msg.id, msg.data.cols, msg.data.rows);
|
||||
const resizeData = msg.data as { cols: number; rows: number };
|
||||
this.resizePty(msg.id, resizeData.cols, resizeData.rows);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'kill':
|
||||
if (!msg.id) throw new Error('Missing PTY id');
|
||||
@@ -221,7 +223,7 @@ class PtyDaemon {
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown message type: ${(msg as any).type}`);
|
||||
throw new Error(`Unknown message type: ${(msg as DaemonMessage).type}`);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||
@@ -428,7 +430,7 @@ class PtyDaemon {
|
||||
socket.write(JSON.stringify(response) + '\n');
|
||||
} catch {
|
||||
// Socket may be closed, ignore
|
||||
console.debug('[PTY Daemon] Failed to send response (socket closed?)');
|
||||
console.warn('[PTY Daemon] Failed to send response (socket closed?)');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
import * as pty from 'node-pty';
|
||||
import * as os from 'os';
|
||||
import type { TerminalProcess, WindowGetter, TerminalOperationResult } from './types';
|
||||
import type { TerminalProcess, WindowGetter } from './types';
|
||||
import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import { getClaudeProfileManager } from '../claude-profile-manager';
|
||||
|
||||
@@ -24,7 +24,7 @@ export function spawnPtyProcess(
|
||||
|
||||
const shellArgs = process.platform === 'win32' ? [] : ['-l'];
|
||||
|
||||
console.log('[PtyManager] Spawning shell:', shell, shellArgs);
|
||||
console.warn('[PtyManager] Spawning shell:', shell, shellArgs);
|
||||
|
||||
return pty.spawn(shell, shellArgs, {
|
||||
name: 'xterm-256color',
|
||||
@@ -69,7 +69,7 @@ export function setupPtyHandlers(
|
||||
|
||||
// Handle terminal exit
|
||||
ptyProcess.onExit(({ exitCode }) => {
|
||||
console.log('[PtyManager] Terminal exited:', id, 'code:', exitCode);
|
||||
console.warn('[PtyManager] Terminal exited:', id, 'code:', exitCode);
|
||||
|
||||
const win = getWindow();
|
||||
if (win) {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import type { TerminalProcess, WindowGetter, SessionCaptureResult } from './types';
|
||||
import type { TerminalProcess, WindowGetter } from './types';
|
||||
import { getTerminalSessionStore, type TerminalSession } from '../terminal-session-store';
|
||||
import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import { debugLog, debugError } from '../../shared/utils/debug-logger';
|
||||
@@ -115,7 +115,7 @@ export function persistSession(terminal: TerminalProcess): void {
|
||||
* Persist all active sessions
|
||||
*/
|
||||
export function persistAllSessions(terminals: Map<string, TerminalProcess>): void {
|
||||
const store = getTerminalSessionStore();
|
||||
const _store = getTerminalSessionStore();
|
||||
|
||||
terminals.forEach((terminal) => {
|
||||
if (terminal.projectPath) {
|
||||
|
||||
@@ -49,7 +49,7 @@ class SessionPersistence {
|
||||
const sessions = this.loadSessions();
|
||||
this.isInitialized = true;
|
||||
|
||||
console.log(`[SessionPersistence] Initialized with ${sessions.length} sessions`);
|
||||
console.warn(`[SessionPersistence] Initialized with ${sessions.length} sessions`);
|
||||
return this.getRecoveryInfo();
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ class SessionPersistence {
|
||||
|
||||
validSessions.forEach((s) => this.sessions.set(s.id, s));
|
||||
|
||||
console.log(
|
||||
console.warn(
|
||||
`[SessionPersistence] Loaded ${validSessions.length} valid sessions, cleaned ${staleSessions.length} stale sessions`
|
||||
);
|
||||
return validSessions;
|
||||
@@ -188,7 +188,7 @@ class SessionPersistence {
|
||||
fs.writeFileSync(bufferPath, serializedBuffer, 'utf8');
|
||||
session.bufferFile = bufferFile;
|
||||
this.saveSession(session);
|
||||
console.debug(`[SessionPersistence] Saved buffer for session ${sessionId} (${serializedBuffer.length} bytes)`);
|
||||
console.warn(`[SessionPersistence] Saved buffer for session ${sessionId} (${serializedBuffer.length} bytes)`);
|
||||
} catch (error) {
|
||||
console.error(`[SessionPersistence] Failed to save buffer for ${sessionId}:`, error);
|
||||
}
|
||||
@@ -223,7 +223,7 @@ class SessionPersistence {
|
||||
if (fs.existsSync(bufferPath)) {
|
||||
try {
|
||||
fs.unlinkSync(bufferPath);
|
||||
console.debug(`[SessionPersistence] Deleted buffer file: ${bufferFile}`);
|
||||
console.warn(`[SessionPersistence] Deleted buffer file: ${bufferFile}`);
|
||||
} catch (error) {
|
||||
console.error(`[SessionPersistence] Failed to delete buffer file ${bufferFile}:`, error);
|
||||
}
|
||||
@@ -266,7 +266,7 @@ class SessionPersistence {
|
||||
|
||||
try {
|
||||
fs.writeFileSync(SESSIONS_FILE, JSON.stringify(data, null, 2), 'utf8');
|
||||
console.debug(`[SessionPersistence] Saved ${data.sessions.length} sessions to disk`);
|
||||
console.warn(`[SessionPersistence] Saved ${data.sessions.length} sessions to disk`);
|
||||
} catch (error) {
|
||||
console.error('[SessionPersistence] Failed to save sessions:', error);
|
||||
}
|
||||
@@ -296,7 +296,7 @@ class SessionPersistence {
|
||||
}
|
||||
|
||||
if (cleanedCount > 0) {
|
||||
console.log(`[SessionPersistence] Cleaned up ${cleanedCount} orphaned buffer files`);
|
||||
console.warn(`[SessionPersistence] Cleaned up ${cleanedCount} orphaned buffer files`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[SessionPersistence] Failed to cleanup orphaned buffers:', error);
|
||||
@@ -309,7 +309,7 @@ export const sessionPersistence = new SessionPersistence();
|
||||
|
||||
// Hook into app lifecycle
|
||||
app.on('before-quit', () => {
|
||||
console.log('[SessionPersistence] App quitting, saving sessions...');
|
||||
console.warn('[SessionPersistence] App quitting, saving sessions...');
|
||||
sessionPersistence.saveNow();
|
||||
});
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import type { TerminalSession } from '../terminal-session-store';
|
||||
import * as PtyManager from './pty-manager';
|
||||
import * as SessionHandler from './session-handler';
|
||||
import * as TerminalEventHandler from './terminal-event-handler';
|
||||
import type {
|
||||
TerminalProcess,
|
||||
WindowGetter,
|
||||
@@ -226,8 +225,8 @@ export async function destroyAllTerminals(
|
||||
* Sessions are only removed when explicitly destroyed by user action via destroyTerminal().
|
||||
*/
|
||||
function handleTerminalExit(
|
||||
terminal: TerminalProcess,
|
||||
terminals: Map<string, TerminalProcess>
|
||||
_terminal: TerminalProcess,
|
||||
_terminals: Map<string, TerminalProcess>
|
||||
): void {
|
||||
// Don't remove session - let it persist for restoration
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ const DEBUG = process.env.AUTO_CLAUDE_DEBUG === 'true' || process.env.AUTO_CLAUD
|
||||
|
||||
function debug(...args: unknown[]): void {
|
||||
if (DEBUG) {
|
||||
console.log('[TitleGenerator]', ...args);
|
||||
console.warn('[TitleGenerator]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,7 +55,8 @@ export class TitleGenerator extends EventEmitter {
|
||||
];
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
|
||||
// Use requirements.txt as marker - it always exists in auto-claude source
|
||||
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -134,14 +135,16 @@ export class TitleGenerator extends EventEmitter {
|
||||
...process.env,
|
||||
...autoBuildEnv,
|
||||
...profileEnv, // Include active Claude profile config
|
||||
PYTHONUNBUFFERED: '1'
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
}
|
||||
});
|
||||
|
||||
let output = '';
|
||||
let errorOutput = '';
|
||||
const timeout = setTimeout(() => {
|
||||
console.log('[TitleGenerator] Title generation timed out after 60s');
|
||||
console.warn('[TitleGenerator] Title generation timed out after 60s');
|
||||
childProcess.kill();
|
||||
resolve(null);
|
||||
}, 60000); // 60 second timeout for SDK initialization + API call
|
||||
@@ -166,7 +169,7 @@ export class TitleGenerator extends EventEmitter {
|
||||
const combinedOutput = `${output}\n${errorOutput}`;
|
||||
const rateLimitDetection = detectRateLimit(combinedOutput);
|
||||
if (rateLimitDetection.isRateLimited) {
|
||||
console.log('[TitleGenerator] Rate limit detected:', {
|
||||
console.warn('[TitleGenerator] Rate limit detected:', {
|
||||
resetTime: rateLimitDetection.resetTime,
|
||||
limitType: rateLimitDetection.limitType,
|
||||
suggestedProfile: rateLimitDetection.suggestedProfile?.name
|
||||
@@ -177,7 +180,7 @@ export class TitleGenerator extends EventEmitter {
|
||||
}
|
||||
|
||||
// Always log failures to help diagnose issues
|
||||
console.log('[TitleGenerator] Title generation failed', {
|
||||
console.warn('[TitleGenerator] Title generation failed', {
|
||||
code,
|
||||
errorOutput: errorOutput.substring(0, 500),
|
||||
output: output.substring(0, 200),
|
||||
@@ -189,7 +192,7 @@ export class TitleGenerator extends EventEmitter {
|
||||
|
||||
childProcess.on('error', (err) => {
|
||||
clearTimeout(timeout);
|
||||
console.log('[TitleGenerator] Process error:', err.message);
|
||||
console.warn('[TitleGenerator] Process error:', err.message);
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -75,7 +75,7 @@ export function copyDirectoryRecursive(
|
||||
const destPath = path.join(dest, entry.name);
|
||||
|
||||
// Skip certain files/directories
|
||||
if (SKIP_FILES.includes(entry.name as any)) {
|
||||
if (SKIP_FILES.includes(entry.name as (typeof SKIP_FILES)[number])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
};
|
||||
|
||||
@@ -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>>;
|
||||
@@ -72,6 +68,8 @@ export interface ProjectAPI {
|
||||
getGitBranches: (projectPath: string) => Promise<IPCResult<string[]>>;
|
||||
getCurrentGitBranch: (projectPath: string) => Promise<IPCResult<string | null>>;
|
||||
detectMainBranch: (projectPath: string) => Promise<IPCResult<string | null>>;
|
||||
checkGitStatus: (projectPath: string) => Promise<IPCResult<GitStatus>>;
|
||||
initializeGit: (projectPath: string) => Promise<IPCResult<InitializationResult>>;
|
||||
}
|
||||
|
||||
export const createProjectAPI = (): ProjectAPI => ({
|
||||
@@ -180,5 +178,11 @@ export const createProjectAPI = (): ProjectAPI => ({
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_GET_CURRENT_BRANCH, projectPath),
|
||||
|
||||
detectMainBranch: (projectPath: string): Promise<IPCResult<string | null>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_DETECT_MAIN_BRANCH, projectPath)
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_DETECT_MAIN_BRANCH, projectPath),
|
||||
|
||||
checkGitStatus: (projectPath: string): Promise<IPCResult<GitStatus>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_CHECK_STATUS, projectPath),
|
||||
|
||||
initializeGit: (projectPath: string): Promise<IPCResult<InitializationResult>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_INITIALIZE, projectPath)
|
||||
});
|
||||
|
||||
@@ -5,9 +5,18 @@ import type {
|
||||
TerminalCreateOptions,
|
||||
RateLimitInfo,
|
||||
ClaudeProfile,
|
||||
ClaudeProfileSettings
|
||||
ClaudeProfileSettings,
|
||||
ClaudeUsageSnapshot
|
||||
} from '../../shared/types';
|
||||
|
||||
/** Type for proactive swap notification events */
|
||||
interface ProactiveSwapNotification {
|
||||
fromProfile: { id: string; name: string };
|
||||
toProfile: { id: string; name: string };
|
||||
reason: string;
|
||||
usageSnapshot: ClaudeUsageSnapshot;
|
||||
}
|
||||
|
||||
export interface TerminalAPI {
|
||||
// Terminal Operations
|
||||
createTerminal: (options: TerminalCreateOptions) => Promise<IPCResult>;
|
||||
@@ -67,7 +76,7 @@ export interface TerminalAPI {
|
||||
// Usage Monitoring (Proactive Account Switching)
|
||||
requestUsageUpdate: () => Promise<IPCResult<import('../../shared/types').ClaudeUsageSnapshot | null>>;
|
||||
onUsageUpdated: (callback: (usage: import('../../shared/types').ClaudeUsageSnapshot) => void) => () => void;
|
||||
onProactiveSwapNotification: (callback: (notification: any) => void) => () => void;
|
||||
onProactiveSwapNotification: (callback: (notification: ProactiveSwapNotification) => void) => () => void;
|
||||
}
|
||||
|
||||
export const createTerminalAPI = (): TerminalAPI => ({
|
||||
@@ -294,9 +303,9 @@ export const createTerminalAPI = (): TerminalAPI => ({
|
||||
},
|
||||
|
||||
onProactiveSwapNotification: (
|
||||
callback: (notification: any) => void
|
||||
callback: (notification: ProactiveSwapNotification) => void
|
||||
): (() => void) => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, notification: any): void => {
|
||||
const handler = (_event: Electron.IpcRendererEvent, notification: ProactiveSwapNotification): void => {
|
||||
callback(notification);
|
||||
};
|
||||
ipcRenderer.on(IPC_CHANNELS.PROACTIVE_SWAP_NOTIFICATION, handler);
|
||||
|
||||
@@ -34,6 +34,7 @@ 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';
|
||||
@@ -113,6 +114,20 @@ 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 && skippedInitProjectId !== selectedProject.id) {
|
||||
@@ -191,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);
|
||||
@@ -479,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,
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -12,8 +12,7 @@ import { Button } from './ui/button';
|
||||
interface SwapNotification {
|
||||
fromProfile: string;
|
||||
toProfile: string;
|
||||
reason: 'proactive' | 'reactive';
|
||||
limitType: 'session' | 'weekly';
|
||||
reason: string;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
@@ -22,12 +21,11 @@ export function ProactiveSwapListener() {
|
||||
const [isVisible, setIsVisible] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = window.electronAPI.onProactiveSwapNotification((data: any) => {
|
||||
const unsubscribe = window.electronAPI.onProactiveSwapNotification((data) => {
|
||||
const notif: SwapNotification = {
|
||||
fromProfile: data.fromProfile,
|
||||
toProfile: data.toProfile,
|
||||
fromProfile: data.fromProfile.name,
|
||||
toProfile: data.toProfile.name,
|
||||
reason: data.reason,
|
||||
limitType: data.limitType,
|
||||
timestamp: new Date()
|
||||
};
|
||||
|
||||
@@ -69,7 +67,7 @@ export function ProactiveSwapListener() {
|
||||
<strong>{notification.toProfile}</strong>
|
||||
<br />
|
||||
<span className="text-[10px]">
|
||||
({notification.limitType} usage threshold reached)
|
||||
({notification.reason} swap)
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -53,7 +53,7 @@ export function ProjectSettings({ project, open, onOpenChange }: ProjectSettings
|
||||
updateEnvConfig,
|
||||
isLoadingEnv,
|
||||
envError,
|
||||
setEnvError,
|
||||
setEnvError: _setEnvError,
|
||||
isSavingEnv,
|
||||
} = useEnvironmentConfig(project.id, project.autoBuildPath, open);
|
||||
|
||||
@@ -313,7 +313,7 @@ export function ProjectSettings({ project, open, onOpenChange }: ProjectSettings
|
||||
onOpenChange={setShowLinearImportModal}
|
||||
onImportComplete={(result) => {
|
||||
// Optionally refresh or notify
|
||||
console.log('Import complete:', result);
|
||||
console.warn('Import complete:', result);
|
||||
}}
|
||||
/>
|
||||
</Dialog>
|
||||
|
||||
@@ -55,8 +55,9 @@ import {
|
||||
} from '../stores/project-store';
|
||||
import { useSettingsStore, saveSettings } from '../stores/settings-store';
|
||||
import { AddProjectModal } from './AddProjectModal';
|
||||
import { GitSetupModal } from './GitSetupModal';
|
||||
import { RateLimitIndicator } from './RateLimitIndicator';
|
||||
import type { Project, AutoBuildVersionInfo } from '../../shared/types';
|
||||
import type { Project, AutoBuildVersionInfo, GitStatus } from '../../shared/types';
|
||||
|
||||
export type SidebarView = 'kanban' | 'terminals' | 'roadmap' | 'context' | 'ideation' | 'github-issues' | 'changelog' | 'insights' | 'worktrees' | 'agent-tools' | 'agent-profiles';
|
||||
|
||||
@@ -104,8 +105,10 @@ export function Sidebar({
|
||||
const [showAddProjectModal, setShowAddProjectModal] = useState(false);
|
||||
const [showInitDialog, setShowInitDialog] = useState(false);
|
||||
const [showUpdateDialog, setShowUpdateDialog] = useState(false);
|
||||
const [showGitSetupModal, setShowGitSetupModal] = useState(false);
|
||||
const [gitStatus, setGitStatus] = useState<GitStatus | null>(null);
|
||||
const [pendingProject, setPendingProject] = useState<Project | null>(null);
|
||||
const [versionInfo, setVersionInfo] = useState<AutoBuildVersionInfo | null>(null);
|
||||
const [_versionInfo, setVersionInfo] = useState<AutoBuildVersionInfo | null>(null);
|
||||
const [isInitializing, setIsInitializing] = useState(false);
|
||||
|
||||
const selectedProject = projects.find((p) => p.id === selectedProjectId);
|
||||
@@ -159,6 +162,29 @@ export function Sidebar({
|
||||
checkUpdates();
|
||||
}, [selectedProjectId, settings.autoUpdateAutoBuild]);
|
||||
|
||||
// Check git status when project changes
|
||||
useEffect(() => {
|
||||
const checkGit = async () => {
|
||||
if (selectedProject) {
|
||||
try {
|
||||
const result = await window.electronAPI.checkGitStatus(selectedProject.path);
|
||||
if (result.success && result.data) {
|
||||
setGitStatus(result.data);
|
||||
// Show git setup modal if project is not a git repo or has no commits
|
||||
if (!result.data.isGitRepo || !result.data.hasCommits) {
|
||||
setShowGitSetupModal(true);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to check git status:', error);
|
||||
}
|
||||
} else {
|
||||
setGitStatus(null);
|
||||
}
|
||||
};
|
||||
checkGit();
|
||||
}, [selectedProject]);
|
||||
|
||||
const handleAddProject = () => {
|
||||
setShowAddProjectModal(true);
|
||||
};
|
||||
@@ -190,7 +216,7 @@ export function Sidebar({
|
||||
setPendingProject(null);
|
||||
};
|
||||
|
||||
const handleUpdate = async () => {
|
||||
const _handleUpdate = async () => {
|
||||
if (!selectedProjectId) return;
|
||||
|
||||
setIsInitializing(true);
|
||||
@@ -205,12 +231,26 @@ export function Sidebar({
|
||||
}
|
||||
};
|
||||
|
||||
const handleSkipUpdate = () => {
|
||||
const _handleSkipUpdate = () => {
|
||||
setShowUpdateDialog(false);
|
||||
setVersionInfo(null);
|
||||
};
|
||||
|
||||
const handleRemoveProject = async (projectId: string, e: React.MouseEvent) => {
|
||||
const handleGitInitialized = async () => {
|
||||
// Refresh git status after initialization
|
||||
if (selectedProject) {
|
||||
try {
|
||||
const result = await window.electronAPI.checkGitStatus(selectedProject.path);
|
||||
if (result.success && result.data) {
|
||||
setGitStatus(result.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh git status:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const _handleRemoveProject = async (projectId: string, e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
await removeProject(projectId);
|
||||
@@ -518,6 +558,15 @@ export function Sidebar({
|
||||
onOpenChange={setShowAddProjectModal}
|
||||
onProjectAdded={handleProjectAdded}
|
||||
/>
|
||||
|
||||
{/* Git Setup Modal */}
|
||||
<GitSetupModal
|
||||
open={showGitSetupModal}
|
||||
onOpenChange={setShowGitSetupModal}
|
||||
project={selectedProject || null}
|
||||
gitStatus={gitStatus}
|
||||
onGitInitialized={handleGitInitialized}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -64,39 +64,27 @@ export function SortableFeatureCard({
|
||||
{...listeners}
|
||||
>
|
||||
<Card
|
||||
className="p-4 hover:bg-muted/50 cursor-pointer transition-colors"
|
||||
className="p-3 hover:bg-muted/50 cursor-pointer transition-colors"
|
||||
onClick={onClick}
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
{/* Header - Title with priority badge and action button */}
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1 flex-wrap">
|
||||
<div className="flex items-center gap-1.5 mb-1">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={ROADMAP_PRIORITY_COLORS[feature.priority]}
|
||||
className={cn('text-[10px] px-1.5 py-0', ROADMAP_PRIORITY_COLORS[feature.priority])}
|
||||
>
|
||||
{ROADMAP_PRIORITY_LABELS[feature.priority]}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={`text-xs ${ROADMAP_COMPLEXITY_COLORS[feature.complexity]}`}
|
||||
>
|
||||
{feature.complexity}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={`text-xs ${ROADMAP_IMPACT_COLORS[feature.impact]}`}
|
||||
>
|
||||
{feature.impact} impact
|
||||
</Badge>
|
||||
{hasCompetitorInsight && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-xs text-primary border-primary/50"
|
||||
className="text-[10px] px-1.5 py-0 text-primary border-primary/50"
|
||||
>
|
||||
<TrendingUp className="h-3 w-3 mr-1" />
|
||||
Competitor Insight
|
||||
<TrendingUp className="h-2.5 w-2.5" />
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
@@ -105,39 +93,61 @@ export function SortableFeatureCard({
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
<h3 className="font-medium truncate">{feature.title}</h3>
|
||||
<p className="text-sm text-muted-foreground line-clamp-2">
|
||||
{feature.description}
|
||||
</p>
|
||||
<h3 className="font-medium text-sm leading-snug line-clamp-2">{feature.title}</h3>
|
||||
</div>
|
||||
{feature.linkedSpecId ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onGoToTask?.(feature.linkedSpecId!);
|
||||
}}
|
||||
>
|
||||
<ExternalLink className="h-3 w-3 mr-1" />
|
||||
Go to Task
|
||||
</Button>
|
||||
) : (
|
||||
feature.status !== 'done' &&
|
||||
onConvertToSpec && (
|
||||
<div className="shrink-0">
|
||||
{feature.linkedSpecId ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 px-2"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onConvertToSpec(feature);
|
||||
onGoToTask?.(feature.linkedSpecId!);
|
||||
}}
|
||||
>
|
||||
<Play className="h-3 w-3 mr-1" />
|
||||
Build
|
||||
<ExternalLink className="h-3 w-3 mr-1" />
|
||||
Task
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
) : (
|
||||
feature.status !== 'done' &&
|
||||
onConvertToSpec && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 px-2"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onConvertToSpec(feature);
|
||||
}}
|
||||
>
|
||||
<Play className="h-3 w-3 mr-1" />
|
||||
Build
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<p className="mt-1.5 text-xs text-muted-foreground line-clamp-2">
|
||||
{feature.description}
|
||||
</p>
|
||||
|
||||
{/* Metadata badges - compact row */}
|
||||
<div className="mt-2 flex items-center gap-1.5">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn('text-[10px] px-1.5 py-0', ROADMAP_COMPLEXITY_COLORS[feature.complexity])}
|
||||
>
|
||||
{feature.complexity}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn('text-[10px] px-1.5 py-0', ROADMAP_IMPACT_COLORS[feature.impact])}
|
||||
>
|
||||
{feature.impact}
|
||||
</Badge>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useCallback, useRef, useMemo, type ClipboardEvent } from 'react';
|
||||
import { useState, useEffect, useCallback, useRef, useMemo, type ClipboardEvent, type DragEvent } from 'react';
|
||||
import {
|
||||
DndContext,
|
||||
DragOverlay,
|
||||
@@ -124,6 +124,9 @@ export function TaskCreationWizard({
|
||||
// Ref for the textarea to handle paste events
|
||||
const descriptionRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
// Drag-and-drop state for images over textarea
|
||||
const [isDragOverTextarea, setIsDragOverTextarea] = useState(false);
|
||||
|
||||
// Setup drag sensors with distance constraint to prevent accidental drags
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, {
|
||||
@@ -277,6 +280,105 @@ export function TaskCreationWizard({
|
||||
}
|
||||
}, [images]);
|
||||
|
||||
/**
|
||||
* Handle drag over textarea for image drops
|
||||
*/
|
||||
const handleTextareaDragOver = useCallback((e: DragEvent<HTMLTextAreaElement>) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOverTextarea(true);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Handle drag leave from textarea
|
||||
*/
|
||||
const handleTextareaDragLeave = useCallback((e: DragEvent<HTMLTextAreaElement>) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOverTextarea(false);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Handle drop on textarea for image files
|
||||
*/
|
||||
const handleTextareaDrop = useCallback(
|
||||
async (e: DragEvent<HTMLTextAreaElement>) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOverTextarea(false);
|
||||
|
||||
if (isCreating) return;
|
||||
|
||||
const files = e.dataTransfer?.files;
|
||||
if (!files || files.length === 0) return;
|
||||
|
||||
// Filter for image files
|
||||
const imageFiles: File[] = [];
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const file = files[i];
|
||||
if (file.type.startsWith('image/')) {
|
||||
imageFiles.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
if (imageFiles.length === 0) return;
|
||||
|
||||
// Check if we can add more images
|
||||
const remainingSlots = MAX_IMAGES_PER_TASK - images.length;
|
||||
if (remainingSlots <= 0) {
|
||||
setError(`Maximum of ${MAX_IMAGES_PER_TASK} images allowed`);
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
|
||||
// Process image files
|
||||
const newImages: ImageAttachment[] = [];
|
||||
const existingFilenames = images.map(img => img.filename);
|
||||
|
||||
for (const file of imageFiles.slice(0, remainingSlots)) {
|
||||
// Validate image type
|
||||
if (!isValidImageMimeType(file.type)) {
|
||||
setError(`Invalid image type. Allowed: ${ALLOWED_IMAGE_TYPES_DISPLAY}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const dataUrl = await blobToBase64(file);
|
||||
const thumbnail = await createThumbnail(dataUrl);
|
||||
|
||||
// Use original filename or generate one
|
||||
const baseFilename = file.name || `dropped-image-${Date.now()}.${file.type.split('/')[1] || 'png'}`;
|
||||
const resolvedFilename = resolveFilename(baseFilename, [
|
||||
...existingFilenames,
|
||||
...newImages.map(img => img.filename)
|
||||
]);
|
||||
|
||||
newImages.push({
|
||||
id: generateImageId(),
|
||||
filename: resolvedFilename,
|
||||
mimeType: file.type,
|
||||
size: file.size,
|
||||
data: dataUrl.split(',')[1], // Store base64 without data URL prefix
|
||||
thumbnail
|
||||
});
|
||||
} catch {
|
||||
setError('Failed to process dropped image');
|
||||
}
|
||||
}
|
||||
|
||||
if (newImages.length > 0) {
|
||||
setImages(prev => [...prev, ...newImages]);
|
||||
// Auto-expand images section
|
||||
setShowImages(true);
|
||||
// Show success feedback
|
||||
setPasteSuccess(true);
|
||||
setTimeout(() => setPasteSuccess(false), 2000);
|
||||
}
|
||||
},
|
||||
[images, isCreating]
|
||||
);
|
||||
|
||||
/**
|
||||
* Handle drag start - capture file data for overlay
|
||||
*/
|
||||
@@ -499,9 +601,15 @@ export function TaskCreationWizard({
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
onPaste={handlePaste}
|
||||
onDragOver={handleTextareaDragOver}
|
||||
onDragLeave={handleTextareaDragLeave}
|
||||
onDrop={handleTextareaDrop}
|
||||
rows={5}
|
||||
disabled={isCreating}
|
||||
className="resize-y min-h-[120px] max-h-[400px]"
|
||||
className={cn(
|
||||
"resize-y min-h-[120px] max-h-[400px]",
|
||||
isDragOverTextarea && !isCreating && "border-primary bg-primary/5 ring-2 ring-primary/20"
|
||||
)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Tip: Paste screenshots directly with {navigator.platform.includes('Mac') ? '⌘V' : 'Ctrl+V'} to add reference images.
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
import { useState, useEffect, useCallback, useRef, type ClipboardEvent } from 'react';
|
||||
import { useState, useEffect, useCallback, useRef, type ClipboardEvent, type DragEvent } from 'react';
|
||||
import { Loader2, Image as ImageIcon, ChevronDown, ChevronUp, X } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
@@ -106,6 +106,9 @@ export function TaskEditDialog({ task, open, onOpenChange, onSaved }: TaskEditDi
|
||||
// Ref for the textarea to handle paste events
|
||||
const descriptionRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
// Drag-and-drop state for images over textarea
|
||||
const [isDragOverTextarea, setIsDragOverTextarea] = useState(false);
|
||||
|
||||
// Reset form when task changes or dialog opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
@@ -209,6 +212,105 @@ export function TaskEditDialog({ task, open, onOpenChange, onSaved }: TaskEditDi
|
||||
}
|
||||
}, [images]);
|
||||
|
||||
/**
|
||||
* Handle drag over textarea for image drops
|
||||
*/
|
||||
const handleTextareaDragOver = useCallback((e: DragEvent<HTMLTextAreaElement>) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOverTextarea(true);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Handle drag leave from textarea
|
||||
*/
|
||||
const handleTextareaDragLeave = useCallback((e: DragEvent<HTMLTextAreaElement>) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOverTextarea(false);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Handle drop on textarea for image files
|
||||
*/
|
||||
const handleTextareaDrop = useCallback(
|
||||
async (e: DragEvent<HTMLTextAreaElement>) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOverTextarea(false);
|
||||
|
||||
if (isSaving) return;
|
||||
|
||||
const files = e.dataTransfer?.files;
|
||||
if (!files || files.length === 0) return;
|
||||
|
||||
// Filter for image files
|
||||
const imageFiles: File[] = [];
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const file = files[i];
|
||||
if (file.type.startsWith('image/')) {
|
||||
imageFiles.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
if (imageFiles.length === 0) return;
|
||||
|
||||
// Check if we can add more images
|
||||
const remainingSlots = MAX_IMAGES_PER_TASK - images.length;
|
||||
if (remainingSlots <= 0) {
|
||||
setError(`Maximum of ${MAX_IMAGES_PER_TASK} images allowed`);
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
|
||||
// Process image files
|
||||
const newImages: ImageAttachment[] = [];
|
||||
const existingFilenames = images.map(img => img.filename);
|
||||
|
||||
for (const file of imageFiles.slice(0, remainingSlots)) {
|
||||
// Validate image type
|
||||
if (!isValidImageMimeType(file.type)) {
|
||||
setError(`Invalid image type. Allowed: ${ALLOWED_IMAGE_TYPES_DISPLAY}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const dataUrl = await blobToBase64(file);
|
||||
const thumbnail = await createThumbnail(dataUrl);
|
||||
|
||||
// Use original filename or generate one
|
||||
const baseFilename = file.name || `dropped-image-${Date.now()}.${file.type.split('/')[1] || 'png'}`;
|
||||
const resolvedFilename = resolveFilename(baseFilename, [
|
||||
...existingFilenames,
|
||||
...newImages.map(img => img.filename)
|
||||
]);
|
||||
|
||||
newImages.push({
|
||||
id: generateImageId(),
|
||||
filename: resolvedFilename,
|
||||
mimeType: file.type,
|
||||
size: file.size,
|
||||
data: dataUrl.split(',')[1], // Store base64 without data URL prefix
|
||||
thumbnail
|
||||
});
|
||||
} catch {
|
||||
setError('Failed to process dropped image');
|
||||
}
|
||||
}
|
||||
|
||||
if (newImages.length > 0) {
|
||||
setImages(prev => [...prev, ...newImages]);
|
||||
// Auto-expand images section
|
||||
setShowImages(true);
|
||||
// Show success feedback
|
||||
setPasteSuccess(true);
|
||||
setTimeout(() => setPasteSuccess(false), 2000);
|
||||
}
|
||||
},
|
||||
[images, isSaving]
|
||||
);
|
||||
|
||||
const handleSave = async () => {
|
||||
// Validate input - only description is required
|
||||
if (!description.trim()) {
|
||||
@@ -296,8 +398,14 @@ export function TaskEditDialog({ task, open, onOpenChange, onSaved }: TaskEditDi
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
onPaste={handlePaste}
|
||||
onDragOver={handleTextareaDragOver}
|
||||
onDragLeave={handleTextareaDragLeave}
|
||||
onDrop={handleTextareaDrop}
|
||||
rows={5}
|
||||
disabled={isSaving}
|
||||
className={cn(
|
||||
isDragOverTextarea && !isSaving && "border-primary bg-primary/5 ring-2 ring-primary/20"
|
||||
)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Tip: Paste screenshots directly with {navigator.platform.includes('Mac') ? '⌘V' : 'Ctrl+V'} to add reference images.
|
||||
|
||||
@@ -48,7 +48,7 @@ export function Terminal({
|
||||
// Initialize xterm with command tracking
|
||||
const {
|
||||
terminalRef,
|
||||
xtermRef,
|
||||
xtermRef: _xtermRef,
|
||||
write,
|
||||
writeln,
|
||||
focus,
|
||||
|
||||
@@ -93,10 +93,10 @@ export function TerminalGrid({ projectPath, onNewTaskClick }: TerminalGridProps)
|
||||
const sessionsResult = await window.electronAPI.getTerminalSessionsForDate(date, projectPath);
|
||||
const sessionsToRestore = sessionsResult.success ? sessionsResult.data || [] : [];
|
||||
|
||||
console.log(`[TerminalGrid] Found ${sessionsToRestore.length} sessions to restore from ${date}`);
|
||||
console.warn(`[TerminalGrid] Found ${sessionsToRestore.length} sessions to restore from ${date}`);
|
||||
|
||||
if (sessionsToRestore.length === 0) {
|
||||
console.log('[TerminalGrid] No sessions found for this date');
|
||||
console.warn('[TerminalGrid] No sessions found for this date');
|
||||
setIsRestoring(false);
|
||||
return;
|
||||
}
|
||||
@@ -119,7 +119,7 @@ export function TerminalGrid({ projectPath, onNewTaskClick }: TerminalGridProps)
|
||||
);
|
||||
|
||||
if (result.success && result.data) {
|
||||
console.log(`[TerminalGrid] Main process restored ${result.data.restored} sessions from ${date}`);
|
||||
console.warn(`[TerminalGrid] Main process restored ${result.data.restored} sessions from ${date}`);
|
||||
|
||||
// Add each successfully restored session to the renderer's terminal store
|
||||
for (const sessionResult of result.data.sessions) {
|
||||
@@ -127,7 +127,7 @@ export function TerminalGrid({ projectPath, onNewTaskClick }: TerminalGridProps)
|
||||
// Find the full session data
|
||||
const fullSession = sessionsToRestore.find(s => s.id === sessionResult.id);
|
||||
if (fullSession) {
|
||||
console.log(`[TerminalGrid] Adding restored terminal to store: ${fullSession.id}`);
|
||||
console.warn(`[TerminalGrid] Adding restored terminal to store: ${fullSession.id}`);
|
||||
addRestoredTerminal(fullSession);
|
||||
}
|
||||
}
|
||||
@@ -162,6 +162,11 @@ export function TerminalGrid({ projectPath, onNewTaskClick }: TerminalGridProps)
|
||||
isDirectory: boolean;
|
||||
} | null>(null);
|
||||
|
||||
const handleCloseTerminal = useCallback((id: string) => {
|
||||
window.electronAPI.destroyTerminal(id);
|
||||
removeTerminal(id);
|
||||
}, [removeTerminal]);
|
||||
|
||||
// Handle keyboard shortcut for new terminal
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
@@ -181,12 +186,7 @@ export function TerminalGrid({ projectPath, onNewTaskClick }: TerminalGridProps)
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [addTerminal, canAddTerminal, projectPath, activeTerminalId]);
|
||||
|
||||
const handleCloseTerminal = useCallback((id: string) => {
|
||||
window.electronAPI.destroyTerminal(id);
|
||||
removeTerminal(id);
|
||||
}, [removeTerminal]);
|
||||
}, [addTerminal, canAddTerminal, projectPath, activeTerminalId, handleCloseTerminal]);
|
||||
|
||||
const handleAddTerminal = useCallback(() => {
|
||||
if (canAddTerminal()) {
|
||||
|
||||
@@ -83,7 +83,7 @@ export function WelcomeScreen({
|
||||
<Separator />
|
||||
<ScrollArea className="max-h-[320px]">
|
||||
<div className="p-2">
|
||||
{recentProjects.map((project, index) => (
|
||||
{recentProjects.map((project, _index) => (
|
||||
<button
|
||||
key={project.id}
|
||||
onClick={() => onSelectProject(project.id)}
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
Plus,
|
||||
Minus,
|
||||
ChevronRight,
|
||||
Terminal,
|
||||
Check,
|
||||
X
|
||||
} from 'lucide-react';
|
||||
@@ -27,13 +26,6 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from './ui/dialog';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from './ui/select';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -46,7 +38,7 @@ import {
|
||||
} from './ui/alert-dialog';
|
||||
import { useProjectStore } from '../stores/project-store';
|
||||
import { useTaskStore } from '../stores/task-store';
|
||||
import type { WorktreeListItem, WorktreeMergeResult, WorktreeDiscardResult } from '../../shared/types';
|
||||
import type { WorktreeListItem, WorktreeMergeResult } from '../../shared/types';
|
||||
|
||||
interface WorktreesProps {
|
||||
projectId: string;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user