Compare commits
224 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4a35420d16 | |||
| c6020ac10f | |||
| 669bdbd1d1 | |||
| 9fc5ef2fac | |||
| c65cf67230 | |||
| 5838f24ff7 | |||
| fc2075dd98 | |||
| ff033a8e2d | |||
| 8db71f3dfb | |||
| 772a5006d4 | |||
| d23fcd8669 | |||
| 326118bd59 | |||
| 6afcc92215 | |||
| 2c9389012e | |||
| 0d95f747f1 | |||
| fe7290a850 | |||
| 8fb5f148fe | |||
| 185d520013 | |||
| 89978edf6d | |||
| 8f1f7a769b | |||
| bdca9af3b8 | |||
| 06fc5dab10 | |||
| a960f00307 | |||
| a05216590b | |||
| 57fcc2403b | |||
| c93fe96ee2 | |||
| 6ee5a731f4 | |||
| f6601efc8a | |||
| a03fa8bc80 | |||
| 50f739dc16 | |||
| 14238788c9 | |||
| 39a08f6117 | |||
| 87e12cf627 | |||
| 4c8dfcafa7 | |||
| 17b092ba39 | |||
| 4b09b0c47e | |||
| b64faed197 | |||
| 252d4ccfd8 | |||
| 721b12753c | |||
| 757e5e04d2 | |||
| 1d1e15446d | |||
| 69d5c7323f | |||
| 9a03814e14 | |||
| c52caa6b17 | |||
| 12c8519246 | |||
| 8bcd00e4a6 | |||
| 7649a607e6 | |||
| f89e4e6c56 | |||
| b9797cbe21 | |||
| cc38a0619c | |||
| aee0ba4cc5 | |||
| 9981ee4469 | |||
| 297d380f4c | |||
| 05062562f0 | |||
| 438f6e2237 | |||
| 458d4bb97a | |||
| 10949905f7 | |||
| 9ab5a4f2cc | |||
| f0a6a0a0af | |||
| cdda3ff277 | |||
| 08aa2ff02b | |||
| 37ace0a39a | |||
| 7f0eeba366 | |||
| f82bd5b871 | |||
| f117bccbbc | |||
| 8b59375404 | |||
| 91a1e3df6c | |||
| 7f12ef0355 | |||
| 30921550df | |||
| 2b96160ab0 | |||
| 7171589002 | |||
| 2a96f855ae | |||
| 3ac3f067cc | |||
| 535d58c80f | |||
| 2ef90b980f | |||
| e6654b96c5 | |||
| 5db28fd8e8 | |||
| c1207ef7fc | |||
| 70072e4281 | |||
| ba776a3fb8 | |||
| e2b24e2e25 | |||
| 7589046bbe | |||
| e248256649 | |||
| 76c1bd7578 | |||
| bcbced24e5 | |||
| a75c0a9965 | |||
| c505d6e32c | |||
| 7d053313b5 | |||
| e9535c8dc4 | |||
| 1642719445 | |||
| 3efab867c5 | |||
| 2ca89ce7c9 | |||
| 52e12d8d2a | |||
| c5b72451af | |||
| ffd8b153a5 | |||
| ee168d317f | |||
| a335925eae | |||
| cf1ba6b57b | |||
| ce7c95cae7 | |||
| 4b6a59826e | |||
| e6058168f0 | |||
| c7dde1f979 | |||
| 15a7585f6e | |||
| c486e5ba84 | |||
| d94833a678 | |||
| 376e950bd4 | |||
| 0959e790df | |||
| e134c4cba9 | |||
| 81e1536801 | |||
| 1a7cf409eb | |||
| 5f26d3964d | |||
| 4a4ad6b1df | |||
| 5702692940 | |||
| 6a4c1b452b | |||
| b75a09c88c | |||
| 0601520e9b | |||
| 412ed0be3c | |||
| 586aa9f8c3 | |||
| bc6470f5c3 | |||
| a107ed03a3 | |||
| 679b8cd948 | |||
| cece172df6 | |||
| 1a38a06e6e | |||
| fe691066dd | |||
| 0f47961a8c | |||
| 9299ee107a | |||
| 6680ed49f6 | |||
| a3eee9285e | |||
| 01a4eb6bbf | |||
| b8a419af5a | |||
| 2b61ebbfad | |||
| 4750869526 | |||
| c9745b6669 | |||
| 08b65f315a | |||
| e1aee6a44f | |||
| b3636a5bce | |||
| 908eebfb16 | |||
| 0e6b652dd7 | |||
| 0acdba6f01 | |||
| de2eccd209 | |||
| 873cafa46f | |||
| 948db57763 | |||
| f98a13eaa0 | |||
| 24ff491d3c | |||
| a8f2d0b110 | |||
| 46d2536600 | |||
| 71535581c2 | |||
| 26725286d5 | |||
| 569e921759 | |||
| 03ccce5cc1 | |||
| 64d5170c94 | |||
| 0710c13964 | |||
| 56cedec2ae | |||
| c0c8067bc5 | |||
| db3a034d75 | |||
| 059315d6ab | |||
| 8df7ba4f16 | |||
| 2bffea842b | |||
| 99cf21e61b | |||
| da5e26b923 | |||
| c957eaa3a1 | |||
| 73d01c0103 | |||
| 41a507fe8b | |||
| e02aa597f2 | |||
| 909305c82b | |||
| 121b2b294f | |||
| c2fe3322a7 | |||
| aac6b106aa | |||
| 7f6beba3ad | |||
| 4b354e7b9f | |||
| eed5297e9d | |||
| 9a5ca8c78f | |||
| 63a1d3c138 | |||
| 3caf9cf18e | |||
| 7d351e3422 | |||
| 9dea155505 | |||
| d3cdd3a1c7 | |||
| a9d1ddb84f | |||
| 6985934825 | |||
| 4f1766b501 | |||
| 7ff326d898 | |||
| 48f7c3cc61 | |||
| 892e01d608 | |||
| 54501cbd73 | |||
| f1d578fd18 | |||
| 2e3a5d9de5 | |||
| a6dad428e9 | |||
| 3d24f8f59e | |||
| 9106038a17 | |||
| 895ed9f605 | |||
| cbe14fda9b | |||
| 4c1dd89840 | |||
| d93eefe806 | |||
| e11f5fcd50 | |||
| 8e891dfcfe | |||
| c721dc23b6 | |||
| 1a2b7a1bbb | |||
| b194c0e11f | |||
| a20b8cf12a | |||
| 0ed6afb805 | |||
| 914a09d0da | |||
| e44202a066 | |||
| 42496446bc | |||
| b0fc497583 | |||
| 462edcdd93 | |||
| affbc48cbe | |||
| d7fd1a24da | |||
| 96dd04d411 | |||
| 1d0566fce7 | |||
| 7f3cd5969d | |||
| 0ef0e1588b | |||
| efc112a313 | |||
| d33a0aaff6 | |||
| 6cff4420c9 | |||
| 12bf69def6 | |||
| 3818b4641f | |||
| 219b66dcc6 | |||
| 4e63e8559d | |||
| 2fa3c51659 | |||
| 59b091a79f | |||
| a0c775f690 | |||
| 9babdc23c1 | |||
| dc886dce44 | |||
| 32760348ae |
Generated
+2544
File diff suppressed because it is too large
Load Diff
+249
-249
File diff suppressed because it is too large
Load Diff
+249
-249
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Centralized Icon Exports for Design System
|
||||
*
|
||||
* This file serves as the single source of truth for all lucide-react icons used
|
||||
* throughout the design system demo app. By consolidating imports here, we enable:
|
||||
*
|
||||
* 1. Better tracking of which icons are actually used
|
||||
* 2. Potential code-splitting opportunities
|
||||
* 3. Easier future migration to alternative icon solutions
|
||||
* 4. Reduced bundle size through optimized tree-shaking
|
||||
*
|
||||
* Usage:
|
||||
* import { Check, ChevronLeft, X } from '../lib/icons';
|
||||
*
|
||||
* When adding new icons:
|
||||
* 1. Import the icon from 'lucide-react'
|
||||
* 2. Add it to the export statement in alphabetical order
|
||||
*/
|
||||
|
||||
export {
|
||||
Check,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Github,
|
||||
Heart,
|
||||
MessageSquare,
|
||||
Minus,
|
||||
Moon,
|
||||
MoreVertical,
|
||||
Plus,
|
||||
RotateCcw,
|
||||
Slack,
|
||||
Sparkles,
|
||||
Star,
|
||||
Sun,
|
||||
Video,
|
||||
X,
|
||||
Zap,
|
||||
} from 'lucide-react';
|
||||
@@ -0,0 +1,35 @@
|
||||
name-template: 'v$RESOLVED_VERSION'
|
||||
tag-template: 'v$RESOLVED_VERSION'
|
||||
|
||||
categories:
|
||||
- title: '## New Features'
|
||||
labels:
|
||||
- 'feature'
|
||||
- 'enhancement'
|
||||
- title: '## Bug Fixes'
|
||||
labels:
|
||||
- 'bug'
|
||||
- 'fix'
|
||||
- title: '## Improvements'
|
||||
labels:
|
||||
- 'improvement'
|
||||
- 'refactor'
|
||||
- title: '## Documentation'
|
||||
labels:
|
||||
- 'documentation'
|
||||
- title: '## Other Changes'
|
||||
labels:
|
||||
- '*'
|
||||
|
||||
change-template: '* $TITLE (#$NUMBER) @$AUTHOR'
|
||||
|
||||
sort-by: merged_at
|
||||
sort-direction: ascending
|
||||
|
||||
template: |
|
||||
$CHANGES
|
||||
|
||||
**Full Changelog**: https://github.com/$OWNER/$REPOSITORY/compare/$PREVIOUS_TAG...$RESOLVED_VERSION
|
||||
|
||||
## Contributors
|
||||
$CONTRIBUTORS
|
||||
@@ -0,0 +1,132 @@
|
||||
name: Build Native Module Prebuilds
|
||||
|
||||
on:
|
||||
# Build on releases
|
||||
release:
|
||||
types: [published]
|
||||
# Manual trigger for testing
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
electron_version:
|
||||
description: 'Electron version to build for'
|
||||
required: false
|
||||
default: '39.2.6'
|
||||
|
||||
env:
|
||||
# Default Electron version - update when upgrading Electron in package.json
|
||||
ELECTRON_VERSION: ${{ github.event.inputs.electron_version || '39.2.6' }}
|
||||
|
||||
jobs:
|
||||
build-windows:
|
||||
runs-on: windows-latest
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [x64]
|
||||
# Add arm64 when GitHub Actions supports Windows ARM runners
|
||||
# arch: [x64, arm64]
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Install Visual Studio Build Tools
|
||||
uses: microsoft/setup-msbuild@v2
|
||||
|
||||
- name: Install node-pty and rebuild for Electron
|
||||
working-directory: auto-claude-ui
|
||||
shell: pwsh
|
||||
run: |
|
||||
# Install only node-pty
|
||||
pnpm add node-pty@1.1.0-beta42
|
||||
|
||||
# Get Electron ABI version
|
||||
$electronAbi = (npx electron-abi $env:ELECTRON_VERSION)
|
||||
Write-Host "Building for Electron $env:ELECTRON_VERSION (ABI: $electronAbi)"
|
||||
|
||||
# Rebuild node-pty for Electron
|
||||
npx @electron/rebuild --version $env:ELECTRON_VERSION --module-dir node_modules/node-pty --arch ${{ matrix.arch }}
|
||||
|
||||
- name: Package prebuilt binaries
|
||||
working-directory: auto-claude-ui
|
||||
shell: pwsh
|
||||
run: |
|
||||
$electronAbi = (npx electron-abi $env:ELECTRON_VERSION)
|
||||
$prebuildDir = "prebuilds/win32-${{ matrix.arch }}-electron-$electronAbi"
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $prebuildDir
|
||||
|
||||
# Copy all built native files
|
||||
$buildDir = "node_modules/node-pty/build/Release"
|
||||
if (Test-Path $buildDir) {
|
||||
Copy-Item "$buildDir/*.node" $prebuildDir/ -Force
|
||||
Copy-Item "$buildDir/*.dll" $prebuildDir/ -Force -ErrorAction SilentlyContinue
|
||||
Copy-Item "$buildDir/*.exe" $prebuildDir/ -Force -ErrorAction SilentlyContinue
|
||||
|
||||
# Also copy conpty files if they exist in subdirectory
|
||||
if (Test-Path "$buildDir/conpty") {
|
||||
Copy-Item "$buildDir/conpty/*" $prebuildDir/ -Force
|
||||
}
|
||||
}
|
||||
|
||||
# List what we packaged
|
||||
Write-Host "Packaged prebuilds:"
|
||||
Get-ChildItem $prebuildDir
|
||||
|
||||
- name: Create archive
|
||||
working-directory: auto-claude-ui
|
||||
shell: pwsh
|
||||
run: |
|
||||
$electronAbi = (npx electron-abi $env:ELECTRON_VERSION)
|
||||
$archiveName = "node-pty-win32-${{ matrix.arch }}-electron-$electronAbi.zip"
|
||||
|
||||
Compress-Archive -Path "prebuilds/*" -DestinationPath $archiveName
|
||||
|
||||
Write-Host "Created archive: $archiveName"
|
||||
Get-ChildItem $archiveName
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: node-pty-win32-${{ matrix.arch }}
|
||||
path: auto-claude-ui/node-pty-*.zip
|
||||
retention-days: 90
|
||||
|
||||
- name: Upload to release
|
||||
if: github.event_name == 'release'
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
files: auto-claude-ui/node-pty-*.zip
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# Create a combined prebuilds package
|
||||
package-prebuilds:
|
||||
needs: build-windows
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: List artifacts
|
||||
run: |
|
||||
echo "Downloaded artifacts:"
|
||||
find artifacts -type f -name "*.zip"
|
||||
|
||||
- name: Upload combined artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: node-pty-prebuilds-all
|
||||
path: artifacts/**/*.zip
|
||||
retention-days: 90
|
||||
@@ -57,7 +57,7 @@ jobs:
|
||||
env:
|
||||
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
|
||||
|
||||
# Frontend tests
|
||||
# Frontend lint, typecheck, test, and build
|
||||
test-frontend:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -72,12 +72,34 @@ jobs:
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
version: 10
|
||||
|
||||
- name: Get pnpm store directory
|
||||
id: pnpm-cache
|
||||
run: echo "dir=$(pnpm store path)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ steps.pnpm-cache.outputs.dir }}
|
||||
key: ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||
restore-keys: ${{ runner.os }}-pnpm-
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: auto-claude-ui
|
||||
run: pnpm install --frozen-lockfile --ignore-scripts
|
||||
|
||||
- name: Lint
|
||||
working-directory: auto-claude-ui
|
||||
run: pnpm run lint
|
||||
|
||||
- name: Type check
|
||||
working-directory: auto-claude-ui
|
||||
run: pnpm run typecheck
|
||||
|
||||
- name: Run tests
|
||||
working-directory: auto-claude-ui
|
||||
run: pnpm test
|
||||
run: pnpm run test
|
||||
|
||||
- name: Build
|
||||
working-directory: auto-claude-ui
|
||||
run: pnpm run build
|
||||
|
||||
@@ -22,4 +22,3 @@ jobs:
|
||||
footer_timestamp: true
|
||||
reduce_headings: true
|
||||
remove_github_reference_links: true
|
||||
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: 'Test build without creating release'
|
||||
required: false
|
||||
default: true
|
||||
type: boolean
|
||||
|
||||
jobs:
|
||||
# Intel build on Intel runner for native compilation
|
||||
# Note: macos-15-intel is the last Intel runner, supported until Fall 2027
|
||||
build-macos-intel:
|
||||
runs-on: macos-15-intel
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- name: Get pnpm store directory
|
||||
id: pnpm-cache
|
||||
run: echo "dir=$(pnpm store path)" >> $GITHUB_OUTPUT
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ steps.pnpm-cache.outputs.dir }}
|
||||
key: ${{ runner.os }}-x64-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||
restore-keys: ${{ runner.os }}-x64-pnpm-
|
||||
|
||||
- name: Install dependencies
|
||||
run: cd auto-claude-ui && pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build application
|
||||
run: cd auto-claude-ui && pnpm run build
|
||||
|
||||
- name: Package macOS (Intel)
|
||||
run: cd auto-claude-ui && pnpm run package:mac -- --arch=x64 -p never
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
CSC_LINK: ${{ secrets.MAC_CERTIFICATE }}
|
||||
CSC_KEY_PASSWORD: ${{ secrets.MAC_CERTIFICATE_PASSWORD }}
|
||||
|
||||
- name: Notarize macOS Intel app
|
||||
env:
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
if [ -z "$APPLE_ID" ]; then
|
||||
echo "Skipping notarization: APPLE_ID not configured"
|
||||
exit 0
|
||||
fi
|
||||
cd auto-claude-ui
|
||||
for dmg in dist/*.dmg; do
|
||||
echo "Notarizing $dmg..."
|
||||
xcrun notarytool submit "$dmg" \
|
||||
--apple-id "$APPLE_ID" \
|
||||
--password "$APPLE_APP_SPECIFIC_PASSWORD" \
|
||||
--team-id "$APPLE_TEAM_ID" \
|
||||
--wait
|
||||
xcrun stapler staple "$dmg"
|
||||
echo "Successfully notarized and stapled $dmg"
|
||||
done
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: macos-intel-builds
|
||||
path: |
|
||||
auto-claude-ui/dist/*.dmg
|
||||
auto-claude-ui/dist/*.zip
|
||||
|
||||
# Apple Silicon build on ARM64 runner for native compilation
|
||||
build-macos-arm64:
|
||||
runs-on: macos-15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- name: Get pnpm store directory
|
||||
id: pnpm-cache
|
||||
run: echo "dir=$(pnpm store path)" >> $GITHUB_OUTPUT
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ steps.pnpm-cache.outputs.dir }}
|
||||
key: ${{ runner.os }}-arm64-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||
restore-keys: ${{ runner.os }}-arm64-pnpm-
|
||||
|
||||
- name: Install dependencies
|
||||
run: cd auto-claude-ui && pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build application
|
||||
run: cd auto-claude-ui && pnpm run build
|
||||
|
||||
- name: Package macOS (Apple Silicon)
|
||||
run: cd auto-claude-ui && pnpm run package:mac -- --arch=arm64 -p never
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
CSC_LINK: ${{ secrets.MAC_CERTIFICATE }}
|
||||
CSC_KEY_PASSWORD: ${{ secrets.MAC_CERTIFICATE_PASSWORD }}
|
||||
|
||||
- name: Notarize macOS ARM64 app
|
||||
env:
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
if [ -z "$APPLE_ID" ]; then
|
||||
echo "Skipping notarization: APPLE_ID not configured"
|
||||
exit 0
|
||||
fi
|
||||
cd auto-claude-ui
|
||||
for dmg in dist/*.dmg; do
|
||||
echo "Notarizing $dmg..."
|
||||
xcrun notarytool submit "$dmg" \
|
||||
--apple-id "$APPLE_ID" \
|
||||
--password "$APPLE_APP_SPECIFIC_PASSWORD" \
|
||||
--team-id "$APPLE_TEAM_ID" \
|
||||
--wait
|
||||
xcrun stapler staple "$dmg"
|
||||
echo "Successfully notarized and stapled $dmg"
|
||||
done
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: macos-arm64-builds
|
||||
path: |
|
||||
auto-claude-ui/dist/*.dmg
|
||||
auto-claude-ui/dist/*.zip
|
||||
|
||||
build-windows:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- name: Get pnpm store directory
|
||||
id: pnpm-cache
|
||||
shell: bash
|
||||
run: echo "dir=$(pnpm store path)" >> $GITHUB_OUTPUT
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ steps.pnpm-cache.outputs.dir }}
|
||||
key: ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||
restore-keys: ${{ runner.os }}-pnpm-
|
||||
|
||||
- name: Install dependencies
|
||||
run: cd auto-claude-ui && pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build application
|
||||
run: cd auto-claude-ui && pnpm run build
|
||||
|
||||
- name: Package Windows
|
||||
run: cd auto-claude-ui && pnpm run package:win -- -p never
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
CSC_LINK: ${{ secrets.WIN_CERTIFICATE }}
|
||||
CSC_KEY_PASSWORD: ${{ secrets.WIN_CERTIFICATE_PASSWORD }}
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-builds
|
||||
path: |
|
||||
auto-claude-ui/dist/*.exe
|
||||
|
||||
build-linux:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- name: Get pnpm store directory
|
||||
id: pnpm-cache
|
||||
run: echo "dir=$(pnpm store path)" >> $GITHUB_OUTPUT
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ steps.pnpm-cache.outputs.dir }}
|
||||
key: ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||
restore-keys: ${{ runner.os }}-pnpm-
|
||||
|
||||
- name: Install dependencies
|
||||
run: cd auto-claude-ui && pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build application
|
||||
run: cd auto-claude-ui && pnpm run build
|
||||
|
||||
- name: Package Linux
|
||||
run: cd auto-claude-ui && pnpm run package:linux -- -p never
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-builds
|
||||
path: |
|
||||
auto-claude-ui/dist/*.AppImage
|
||||
auto-claude-ui/dist/*.deb
|
||||
|
||||
create-release:
|
||||
needs: [build-macos-intel, build-macos-arm64, build-windows, build-linux]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: dist
|
||||
|
||||
- name: Flatten and validate artifacts
|
||||
run: |
|
||||
mkdir -p release-assets
|
||||
find dist -type f \( -name "*.dmg" -o -name "*.zip" -o -name "*.exe" -o -name "*.AppImage" -o -name "*.deb" \) -exec cp {} release-assets/ \;
|
||||
|
||||
# Validate that at least one artifact was copied
|
||||
artifact_count=$(find release-assets -type f \( -name "*.dmg" -o -name "*.zip" -o -name "*.exe" -o -name "*.AppImage" -o -name "*.deb" \) | wc -l)
|
||||
if [ "$artifact_count" -eq 0 ]; then
|
||||
echo "::error::No build artifacts found! Expected .dmg, .zip, .exe, .AppImage, or .deb files."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Found $artifact_count artifact(s):"
|
||||
ls -la release-assets/
|
||||
|
||||
- name: Generate checksums
|
||||
run: |
|
||||
cd release-assets
|
||||
sha256sum ./* > checksums.sha256
|
||||
cat checksums.sha256
|
||||
|
||||
- name: Scan with VirusTotal
|
||||
id: virustotal
|
||||
continue-on-error: true
|
||||
if: ${{ github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.dry_run != true) }}
|
||||
env:
|
||||
VT_API_KEY: ${{ secrets.VIRUSTOTAL_API_KEY }}
|
||||
run: |
|
||||
if [ -z "$VT_API_KEY" ]; then
|
||||
echo "::warning::VIRUSTOTAL_API_KEY not configured, skipping scan"
|
||||
echo "vt_results=" >> $GITHUB_OUTPUT
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "## VirusTotal Scan Results" > vt_results.md
|
||||
echo "" >> vt_results.md
|
||||
|
||||
for file in release-assets/*.{exe,dmg,AppImage,deb}; do
|
||||
[ -f "$file" ] || continue
|
||||
filename=$(basename "$file")
|
||||
filesize=$(stat -c%s "$file" 2>/dev/null || stat -f%z "$file")
|
||||
echo "Scanning $filename (${filesize} bytes)..."
|
||||
|
||||
# For files > 32MB, get a special upload URL first
|
||||
if [ "$filesize" -gt 33554432 ]; then
|
||||
echo " Large file detected, requesting upload URL..."
|
||||
upload_url_response=$(curl -s --request GET \
|
||||
--url "https://www.virustotal.com/api/v3/files/upload_url" \
|
||||
--header "x-apikey: $VT_API_KEY")
|
||||
|
||||
upload_url=$(echo "$upload_url_response" | jq -r '.data // empty')
|
||||
if [ -z "$upload_url" ]; then
|
||||
echo "::warning::Failed to get upload URL for large file $filename"
|
||||
echo "Response: $upload_url_response"
|
||||
echo "- $filename - ⚠️ Upload failed (large file)" >> vt_results.md
|
||||
continue
|
||||
fi
|
||||
api_url="$upload_url"
|
||||
else
|
||||
api_url="https://www.virustotal.com/api/v3/files"
|
||||
fi
|
||||
|
||||
# Upload file to VirusTotal
|
||||
response=$(curl -s --request POST \
|
||||
--url "$api_url" \
|
||||
--header "x-apikey: $VT_API_KEY" \
|
||||
--form "file=@$file")
|
||||
|
||||
# Check if response is valid JSON before parsing
|
||||
if ! echo "$response" | jq -e . >/dev/null 2>&1; then
|
||||
echo "::warning::VirusTotal returned invalid JSON for $filename"
|
||||
echo "Response (first 500 chars): ${response:0:500}"
|
||||
echo "- $filename - ⚠️ Scan failed (invalid response)" >> vt_results.md
|
||||
continue
|
||||
fi
|
||||
|
||||
# Check for API error response
|
||||
error_code=$(echo "$response" | jq -r '.error.code // empty')
|
||||
if [ -n "$error_code" ]; then
|
||||
error_msg=$(echo "$response" | jq -r '.error.message // "Unknown error"')
|
||||
echo "::warning::VirusTotal API error for $filename: $error_code - $error_msg"
|
||||
echo "- $filename - ⚠️ Scan failed ($error_code)" >> vt_results.md
|
||||
continue
|
||||
fi
|
||||
|
||||
# Extract analysis ID
|
||||
analysis_id=$(echo "$response" | jq -r '.data.id // empty')
|
||||
|
||||
if [ -z "$analysis_id" ]; then
|
||||
echo "::warning::Failed to upload $filename to VirusTotal"
|
||||
echo "Response: $response"
|
||||
echo "- $filename - ⚠️ Upload failed" >> vt_results.md
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "Uploaded $filename, analysis ID: $analysis_id"
|
||||
|
||||
# Wait for analysis to complete (max 5 minutes per file)
|
||||
analysis=""
|
||||
for i in {1..30}; do
|
||||
sleep 10
|
||||
analysis=$(curl -s --request GET \
|
||||
--url "https://www.virustotal.com/api/v3/analyses/$analysis_id" \
|
||||
--header "x-apikey: $VT_API_KEY")
|
||||
|
||||
# Validate JSON response
|
||||
if ! echo "$analysis" | jq -e . >/dev/null 2>&1; then
|
||||
echo " Warning: Invalid JSON response on attempt $i, retrying..."
|
||||
continue
|
||||
fi
|
||||
|
||||
status=$(echo "$analysis" | jq -r '.data.attributes.status // "unknown"')
|
||||
echo " Status: $status (attempt $i/30)"
|
||||
|
||||
if [ "$status" = "completed" ]; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
# Final validation that we have valid analysis data
|
||||
if ! echo "$analysis" | jq -e '.data.attributes.stats' >/dev/null 2>&1; then
|
||||
echo "::warning::Could not get complete analysis for $filename, using local hash"
|
||||
file_hash=$(sha256sum "$file" | cut -d' ' -f1)
|
||||
echo "- [$filename](https://www.virustotal.com/gui/file/$file_hash) - ⚠️ Analysis incomplete" >> vt_results.md
|
||||
continue
|
||||
fi
|
||||
|
||||
# Get file hash for permanent URL
|
||||
file_hash=$(echo "$analysis" | jq -r '.meta.file_info.sha256 // empty')
|
||||
|
||||
if [ -z "$file_hash" ]; then
|
||||
# Fallback: calculate hash locally
|
||||
file_hash=$(sha256sum "$file" | cut -d' ' -f1)
|
||||
fi
|
||||
|
||||
# Get detection stats
|
||||
malicious=$(echo "$analysis" | jq -r '.data.attributes.stats.malicious // 0')
|
||||
suspicious=$(echo "$analysis" | jq -r '.data.attributes.stats.suspicious // 0')
|
||||
undetected=$(echo "$analysis" | jq -r '.data.attributes.stats.undetected // 0')
|
||||
|
||||
vt_url="https://www.virustotal.com/gui/file/$file_hash"
|
||||
|
||||
if [ "$malicious" -gt 0 ] || [ "$suspicious" -gt 0 ]; then
|
||||
echo "::warning::$filename has $malicious malicious and $suspicious suspicious detections (likely false positives)"
|
||||
echo "- [$filename]($vt_url) - ⚠️ **$malicious malicious, $suspicious suspicious** detections (review recommended)" >> vt_results.md
|
||||
else
|
||||
echo "$filename is clean ($undetected engines, 0 detections)"
|
||||
echo "- [$filename]($vt_url) - ✅ Clean ($undetected engines, 0 detections)" >> vt_results.md
|
||||
fi
|
||||
done
|
||||
|
||||
echo "" >> vt_results.md
|
||||
|
||||
# Save results for release notes
|
||||
cat vt_results.md
|
||||
echo "vt_results<<EOF" >> $GITHUB_OUTPUT
|
||||
cat vt_results.md >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Dry run summary
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run == true }}
|
||||
run: |
|
||||
echo "## Dry Run Complete" >> $GITHUB_STEP_SUMMARY
|
||||
echo "Build artifacts created successfully:" >> $GITHUB_STEP_SUMMARY
|
||||
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
|
||||
ls -la release-assets/ >> $GITHUB_STEP_SUMMARY
|
||||
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
|
||||
echo "### Checksums" >> $GITHUB_STEP_SUMMARY
|
||||
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
|
||||
cat release-assets/checksums.sha256 >> $GITHUB_STEP_SUMMARY
|
||||
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
- name: Generate changelog
|
||||
if: ${{ github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.dry_run != true) }}
|
||||
id: changelog
|
||||
uses: release-drafter/release-drafter@v6
|
||||
with:
|
||||
config-name: release-drafter.yml
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Create Release
|
||||
if: ${{ github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.dry_run != true) }}
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
body: |
|
||||
${{ steps.changelog.outputs.body }}
|
||||
|
||||
${{ steps.virustotal.outputs.vt_results }}
|
||||
files: release-assets/*
|
||||
draft: false
|
||||
prerelease: ${{ contains(github.ref, 'beta') || contains(github.ref, 'alpha') }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,71 @@
|
||||
name: Validate Version
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
jobs:
|
||||
validate-version:
|
||||
name: Validate package.json version matches tag
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Extract version from tag
|
||||
id: tag_version
|
||||
run: |
|
||||
# Extract version from tag (e.g., v2.5.5 -> 2.5.5)
|
||||
TAG_VERSION=${GITHUB_REF#refs/tags/v}
|
||||
echo "version=$TAG_VERSION" >> $GITHUB_OUTPUT
|
||||
echo "Tag version: $TAG_VERSION"
|
||||
|
||||
- name: Extract version from package.json
|
||||
id: package_version
|
||||
run: |
|
||||
# Read version from package.json
|
||||
PACKAGE_VERSION=$(node -p "require('./auto-claude-ui/package.json').version")
|
||||
echo "version=$PACKAGE_VERSION" >> $GITHUB_OUTPUT
|
||||
echo "Package.json version: $PACKAGE_VERSION"
|
||||
|
||||
- name: Compare versions
|
||||
run: |
|
||||
TAG_VERSION="${{ steps.tag_version.outputs.version }}"
|
||||
PACKAGE_VERSION="${{ steps.package_version.outputs.version }}"
|
||||
|
||||
echo "=========================================="
|
||||
echo "Version Validation"
|
||||
echo "=========================================="
|
||||
echo "Git tag version: v$TAG_VERSION"
|
||||
echo "package.json version: $PACKAGE_VERSION"
|
||||
echo "=========================================="
|
||||
|
||||
if [ "$TAG_VERSION" != "$PACKAGE_VERSION" ]; then
|
||||
echo ""
|
||||
echo "❌ ERROR: Version mismatch detected!"
|
||||
echo ""
|
||||
echo "The version in package.json ($PACKAGE_VERSION) does not match"
|
||||
echo "the git tag version ($TAG_VERSION)."
|
||||
echo ""
|
||||
echo "To fix this:"
|
||||
echo " 1. Delete this tag: git tag -d v$TAG_VERSION"
|
||||
echo " 2. Update package.json version to $TAG_VERSION"
|
||||
echo " 3. Commit the change"
|
||||
echo " 4. Recreate the tag: git tag -a v$TAG_VERSION -m 'Release v$TAG_VERSION'"
|
||||
echo ""
|
||||
echo "Or use the automated script:"
|
||||
echo " node scripts/bump-version.js $TAG_VERSION"
|
||||
echo ""
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "✅ SUCCESS: Versions match!"
|
||||
echo ""
|
||||
|
||||
- name: Version validation result
|
||||
if: success()
|
||||
run: |
|
||||
echo "::notice::Version validation passed - package.json version matches tag v${{ steps.tag_version.outputs.version }}"
|
||||
+2
-1
@@ -74,6 +74,7 @@ dmypy.json
|
||||
.auto-claude-security.json
|
||||
.auto-claude-status
|
||||
.claude_settings.json
|
||||
.update-metadata.json
|
||||
|
||||
# Development of Auto Build with Auto Build
|
||||
dev/
|
||||
@@ -85,4 +86,4 @@ dev/
|
||||
_bmad
|
||||
_bmad-output
|
||||
|
||||
.claude
|
||||
.claude
|
||||
|
||||
@@ -33,4 +33,5 @@ repos:
|
||||
- id: trailing-whitespace
|
||||
- id: end-of-file-fixer
|
||||
- id: check-yaml
|
||||
exclude: pnpm-lock\.yaml$
|
||||
- id: check-added-large-files
|
||||
|
||||
+647
-1
@@ -1,3 +1,649 @@
|
||||
## 2.7.1 - Build Pipeline Enhancements
|
||||
|
||||
### 🛠️ Improvements
|
||||
|
||||
- Enhanced VirusTotal scan error handling in release workflow with graceful failure recovery and improved reporting visibility
|
||||
|
||||
- Refactored macOS build workflow to support both Intel and ARM64 architectures with notarization for Intel builds and improved artifact handling
|
||||
|
||||
- Streamlined CI/CD processes with updated caching strategies and enhanced error handling for external API interactions
|
||||
|
||||
### 📚 Documentation
|
||||
|
||||
- Clarified README documentation
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- chore: Enhance VirusTotal scan error handling in release workflow by @AndyMik90 in d23fcd8
|
||||
|
||||
- chore: Refactor macOS build workflow to support Intel and ARM64 architectures by @AndyMik90 in 326118b
|
||||
|
||||
- docs: readme clarification by @AndyMik90 in 6afcc92
|
||||
|
||||
- fix: version by @AndyMik90 in 2c93890
|
||||
|
||||
## Thanks to all contributors
|
||||
|
||||
@AndyMik90
|
||||
|
||||
## 2.7.0 - Tab Persistence & Memory System Modernization
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
- Project tab bar with persistent tab management and GitHub organization initialization on project creation
|
||||
|
||||
- Task creation enhanced with @ autocomplete for agent profiles and improved drag-and-drop support
|
||||
|
||||
- Keyboard shortcuts and tooltips added to project tabs for better navigation
|
||||
|
||||
- Agent task restart functionality with new profile support for flexible task recovery
|
||||
|
||||
- Ollama embedding model support with automatic dimension detection for self-hosted deployments
|
||||
|
||||
### 🛠️ Improvements
|
||||
|
||||
- Memory system completely redesigned with embedded LadybugDB, eliminating Docker/FalkorDB dependency and improving performance
|
||||
|
||||
- Tab persistence implemented via IPC-based mechanism for reliable session state management
|
||||
|
||||
- Terminal environment improved by using virtual environment Python for proper terminal name generation
|
||||
|
||||
- AI merge operations timeout increased from 2 to 10 minutes for reliability with larger changes
|
||||
|
||||
- Merge operations now use stored baseBranch metadata for consistent branch targeting
|
||||
|
||||
- Memory configuration UI simplified and rebranded with improved Ollama integration and detection
|
||||
|
||||
- CI/CD workflows enhanced with code signing support and automated release process
|
||||
|
||||
- Cross-platform compatibility improved by replacing Unix shell syntax with portable git commands
|
||||
|
||||
- Python venv created in userData for packaged applications to ensure proper environment isolation
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- Task title no longer blocks edit/close buttons in UI
|
||||
|
||||
- Tab persistence and terminal shortcuts properly scoped to prevent conflicts
|
||||
|
||||
- Agent profile fallback corrected from 'Balanced' to 'Auto (Optimized)'
|
||||
|
||||
- macOS notarization made optional and improved with private artifact storage
|
||||
|
||||
- Embedding provider changes now properly detected during migration
|
||||
|
||||
- Memory query CLI respects user's memory enabled flag
|
||||
|
||||
- CodeRabbit review issues and linting errors resolved across codebase
|
||||
|
||||
- F-string prefixes removed from strings without placeholders
|
||||
|
||||
- Import ordering fixed for ruff compliance
|
||||
|
||||
- Preview panel now receives projectPath prop correctly for image component functionality
|
||||
|
||||
- Default database path unified to ~/.auto-claude/memories for consistency
|
||||
|
||||
- @lydell/node-pty build scripts compatibility improved for pnpm v10
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- feat(ui): add project tab bar from PR #101 by @AndyMik90 in c400fe9
|
||||
|
||||
- feat: improve task creation UX with @ autocomplete and better drag-drop by @AndyMik90 in 20d1487
|
||||
|
||||
- feat(ui): add keyboard shortcuts and tooltips for project tabs by @AndyMik90 in ed73265
|
||||
|
||||
- feat(agent): enhance task restart functionality with new profile support by @AndyMik90 in c8452a5
|
||||
|
||||
- feat: add Ollama embedding model support with auto-detected dimensions by @AndyMik90 in 45901f3
|
||||
|
||||
- feat(memory): replace FalkorDB with LadybugDB embedded database by @AndyMik90 in 87d0b52
|
||||
|
||||
- feat: add automated release workflow with code signing by @AndyMik90 in 6819b00
|
||||
|
||||
- feat: add embedding provider change detection and fix import ordering by @AndyMik90 in 36f8006
|
||||
|
||||
- fix(tests): update tab management tests for IPC-based persistence by @AndyMik90 in ea25d6e
|
||||
|
||||
- fix(ui): address CodeRabbit PR review issues by @AndyMik90 in 39ce754
|
||||
|
||||
- fix: address CodeRabbit review issues by @AndyMik90 in 95ae0b0
|
||||
|
||||
- fix: prevent task title from blocking edit/close buttons by @AndyMik90 in 8a0fb26
|
||||
|
||||
- fix: use venv Python for terminal name generation by @AndyMik90 in 325cb54
|
||||
|
||||
- fix(merge): increase AI merge timeout from 2 to 10 minutes by @AndyMik90 in 4477538
|
||||
|
||||
- fix(merge): use stored baseBranch from task metadata for merge operations by @AndyMik90 in 8d56474
|
||||
|
||||
- fix: unify default database path to ~/.auto-claude/memories by @AndyMik90 in 684e3f9
|
||||
|
||||
- fix(ui): fix tab persistence and scope terminal shortcuts by @AndyMik90 in 2d1168b
|
||||
|
||||
- fix: create Python venv in userData for packaged apps by @AndyMik90 in b83377c
|
||||
|
||||
- fix(ui): change agent profile fallback from 'Balanced' to 'Auto (Optimized)' by @AndyMik90 in 385dcc1
|
||||
|
||||
- fix: check APPLE_ID in shell instead of workflow if condition by @AndyMik90 in 9eece01
|
||||
|
||||
- fix: allow @lydell/node-pty build scripts in pnpm v10 by @AndyMik90 in 1f6963f
|
||||
|
||||
- fix: use shell guard for notarization credentials check by @AndyMik90 in 4cbddd3
|
||||
|
||||
- fix: improve migrate_embeddings robustness and correctness by @AndyMik90 in 61f0238
|
||||
|
||||
- fix: respect user's memory enabled flag in query_memory CLI by @AndyMik90 in 45b2c83
|
||||
|
||||
- fix: save notarization logs to private artifact instead of public logs by @AndyMik90 in a82525d
|
||||
|
||||
- fix: make macOS notarization optional by @AndyMik90 in f2b7b56
|
||||
|
||||
- fix: add author email for Linux builds by @AndyMik90 in 5f66127
|
||||
|
||||
- fix: add GH_TOKEN and homepage for release workflow by @AndyMik90 in 568ea18
|
||||
|
||||
- fix(ci): quote GITHUB_OUTPUT for shell safety by @AndyMik90 in 1e891e1
|
||||
|
||||
- fix: address CodeRabbit review feedback by @AndyMik90 in 8e4b1da
|
||||
|
||||
- fix: update test and apply ruff formatting by @AndyMik90 in a087ba3
|
||||
|
||||
- fix: address additional CodeRabbit review comments by @AndyMik90 in 461fad6
|
||||
|
||||
- fix: sort imports in memory.py for ruff I001 by @AndyMik90 in b3c257d
|
||||
|
||||
- fix: address CodeRabbit review comments from PR #100 by @AndyMik90 in 1ed237a
|
||||
|
||||
- fix: remove f-string prefixes from strings without placeholders by @AndyMik90 in bcd453a
|
||||
|
||||
- fix: resolve remaining CI failures by @AndyMik90 in cfbccda
|
||||
|
||||
- fix: resolve all CI failures in PR #100 by @AndyMik90 in c493d6c
|
||||
|
||||
- fix(cli): update graphiti status display for LadybugDB by @AndyMik90 in 049c60c
|
||||
|
||||
- fix(ui): replace Unix shell syntax with cross-platform git commands by @AndyMik90 in 83aa3f0
|
||||
|
||||
- fix: correct model name and release workflow conditionals by @AndyMik90 in de41dfc
|
||||
|
||||
- style: fix ruff linting errors in graphiti queries by @AndyMik90 in 127559f
|
||||
|
||||
- style: apply ruff formatting to 4 files by @AndyMik90 in 9d5d075
|
||||
|
||||
- refactor: update memory test suite for LadybugDB by @AndyMik90 in f0b5efc
|
||||
|
||||
- refactor(ui): simplify reference files and images handling in task modal by @AndyMik90 in 1975e4d
|
||||
|
||||
- refactor: rebrand memory system UI and simplify configuration by @AndyMik90 in 2b3cd49
|
||||
|
||||
- refactor: replace Docker/FalkorDB with embedded LadybugDB for memory system by @AndyMik90 in 325458d
|
||||
|
||||
- docs: add CodeRabbit review response tracking by @AndyMik90 in 3452548
|
||||
|
||||
- chore: use GitHub noreply email for author field by @AndyMik90 in 18f2045
|
||||
|
||||
- chore: simplify notarization step after successful setup by @AndyMik90 in e4fe7cd
|
||||
|
||||
- chore: update CI and release workflows, remove changelog config by @AndyMik90 in 6f891b7
|
||||
|
||||
- chore: remove docker-compose.yml (FalkorDB no longer used) by @AndyMik90 in 68f3f06
|
||||
|
||||
- fix: Replace space with hyphen in productName to fix PTY daemon spawn (#65) by @Craig Van in 8f1f7a7
|
||||
|
||||
- fix: update npm scripts to use hyphenated product name by @AndyMik90 in 89978ed
|
||||
|
||||
- fix(ui): improve Ollama UX in memory settings by @AndyMik90 in dea1711
|
||||
|
||||
- auto-claude: subtask-1-1 - Add projectPath prop to PreviewPanel and implement custom img component by @AndyMik90 in e6529e0
|
||||
|
||||
- Project tab persistence and github org init on project creation by @AndyMik90 in ae1dac9
|
||||
|
||||
- Readme for installors by @AndyMik90 in 1855d7d
|
||||
|
||||
---
|
||||
|
||||
## Thanks to all contributors
|
||||
|
||||
@AndyMik90, @Craig Van
|
||||
|
||||
## 2.6.0 - Improved User Experience and Agent Configuration
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
- Add customizable phase configuration in app settings, allowing users to tailor the AI build pipeline to their workflow
|
||||
|
||||
- Implement parallel AI merge functionality for faster integration of completed builds
|
||||
|
||||
- Add Google AI as LLM and embedding provider for Graphiti memory system
|
||||
|
||||
- Implement device code authentication flow with timeout handling, browser launch fallback, and comprehensive testing
|
||||
|
||||
### 🛠️ Improvements
|
||||
|
||||
- Move Agent Profiles from dashboard to Settings for better organization and discoverability
|
||||
|
||||
- Default agent profile to 'Auto (Optimized)' for streamlined out-of-the-box experience
|
||||
|
||||
- Enhance WorkspaceStatus component UI with improved visual design
|
||||
|
||||
- Refactor task management from sidebar to modal interface for cleaner navigation
|
||||
|
||||
- Add comprehensive theme system with multiple color schemes (Forest, Neo, Retro, Dusk, Ocean, Lime) and light/dark mode support
|
||||
|
||||
- Extract human-readable feature titles from spec.md for better task identification
|
||||
|
||||
- Improve task description display for specs with compact markdown formatting
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- Fix asyncio coroutine creation in worker threads to properly support async operations
|
||||
|
||||
- Improve UX for phase configuration in task creation workflow
|
||||
|
||||
- Address CodeRabbit PR #69 feedback and additional review comments
|
||||
|
||||
- Fix auto-close behavior for task modal when marking tasks as done
|
||||
|
||||
- Resolve Python lint errors and import sorting issues (ruff I001 compliance)
|
||||
|
||||
- Ensure planner agent properly writes implementation_plan.json
|
||||
|
||||
- Add platform detection for terminal profile commands on Windows
|
||||
|
||||
- Set default selected agent profile to 'auto' across all users
|
||||
|
||||
- Fix display of correct merge target branch in worktree UI
|
||||
|
||||
- Add validation for invalid colorTheme fallback to prevent UI errors
|
||||
|
||||
- Remove outdated Sun/Moon toggle button from sidebar
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- feat: add customizable phase configuration in app settings by @AndyMik90 in aee0ba4
|
||||
|
||||
- feat: implement parallel AI merge functionality by @AndyMik90 in 458d4bb
|
||||
|
||||
- feat(graphiti): add Google AI as LLM and embedding provider by @adryserage in fe69106
|
||||
|
||||
- fix: create coroutine inside worker thread for asyncio.run by @AndyMik90 in f89e4e6
|
||||
|
||||
- fix: improve UX for phase configuration in task creation by @AndyMik90 in b9797cb
|
||||
|
||||
- fix: address CodeRabbit PR #69 feedback by @AndyMik90 in cc38a06
|
||||
|
||||
- fix: sort imports in workspace.py to pass ruff I001 check by @AndyMik90 in 9981ee4
|
||||
|
||||
- fix(ui): auto-close task modal when marking task as done by @AndyMik90 in 297d380
|
||||
|
||||
- fix: resolve Python lint errors in workspace.py by @AndyMik90 in 0506256
|
||||
|
||||
- refactor: move Agent Profiles from dashboard to Settings by @AndyMik90 in 1094990
|
||||
|
||||
- fix(planning): ensure planner agent writes implementation_plan.json by @AndyMik90 in 9ab5a4f
|
||||
|
||||
- fix(windows): add platform detection for terminal profile commands by @AndyMik90 in f0a6a0a
|
||||
|
||||
- fix: default agent profile to 'Auto (Optimized)' for all users by @AndyMik90 in 08aa2ff
|
||||
|
||||
- fix: update default selected agent profile to 'auto' by @AndyMik90 in 37ace0a
|
||||
|
||||
- style: enhance WorkspaceStatus component UI by @AndyMik90 in 3092155
|
||||
|
||||
- fix: display correct merge target branch in worktree UI by @AndyMik90 in 2b96160
|
||||
|
||||
- Improvement/refactor task sidebar to task modal by @AndyMik90 in 2a96f85
|
||||
|
||||
- fix: extract human-readable title from spec.md when feature field is spec ID by @AndyMik90 in 8b59375
|
||||
|
||||
- fix: task descriptions not showing for specs with compact markdown by @AndyMik90 in 7f12ef0
|
||||
|
||||
- Add comprehensive theme system with Forest, Neo, Retro, Dusk, Ocean, and Lime color schemes by @AndyMik90 in ba776a3, e2b24e2, 7589046, e248256, 76c1bd7, bcbced2
|
||||
|
||||
- Add ColorTheme type and configuration to app settings by @AndyMik90 in 2ca89ce, c505d6e, a75c0a9
|
||||
|
||||
- Implement device code authentication flow with timeout handling and fallback URL display by @AndyMik90 in 5f26d39, 81e1536, 1a7cf40, 4a4ad6b, 6a4c1b4, b75a09c, e134c4c
|
||||
|
||||
- fix(graphiti): address CodeRabbit review comments by @adryserage in 679b8cd
|
||||
|
||||
- fix(lint): sort imports in Google provider files by @adryserage in 1a38a06
|
||||
|
||||
## 2.6.0 - Multi-Provider Graphiti Support & Platform Fixes
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
- **Google AI Provider for Graphiti**: Full Google AI (Gemini) support for both LLM and embeddings in the Memory Layer
|
||||
- Add GoogleLLMClient with gemini-2.0-flash default model
|
||||
- Add GoogleEmbedder with text-embedding-004 default model
|
||||
- UI integration for Google API key configuration with link to Google AI Studio
|
||||
- **Ollama LLM Provider in UI**: Add Ollama as an LLM provider option in Graphiti onboarding wizard
|
||||
- Ollama runs locally and doesn't require an API key
|
||||
- Configure Base URL instead of API key for local inference
|
||||
- **LLM Provider Selection UI**: Add provider selection dropdown to Graphiti setup wizard for flexible backend configuration
|
||||
- **Per-Project GitHub Configuration**: UI clarity improvements for per-project GitHub org/repo settings
|
||||
|
||||
### 🛠️ Improvements
|
||||
|
||||
- Enhanced Graphiti provider factory to support Google AI alongside existing providers
|
||||
- Updated env-handlers to properly populate graphitiProviderConfig from .env files
|
||||
- Improved type definitions with proper Graphiti provider config properties in AppSettings
|
||||
- Better API key loading when switching between providers in settings
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- **node-pty Migration**: Replaced node-pty with @lydell/node-pty for prebuilt Windows binaries
|
||||
- Updated all imports to use @lydell/node-pty directly
|
||||
- Fixed "Cannot find module 'node-pty'" startup error
|
||||
- **GitHub Organization Support**: Fixed repository support for GitHub organization accounts
|
||||
- Add defensive array validation for GitHub issues API response
|
||||
- **Asyncio Deprecation**: Fixed asyncio deprecation warning by using get_running_loop() instead of get_event_loop()
|
||||
- Applied ruff formatting and fixed import sorting (I001) in Google provider files
|
||||
|
||||
### 🔧 Other Changes
|
||||
|
||||
- Added google-generativeai dependency to requirements.txt
|
||||
- Updated provider validation to include Google/Groq/HuggingFace type assertions
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- fix(graphiti): address CodeRabbit review comments by @adryserage in 679b8cd
|
||||
- fix(lint): sort imports in Google provider files by @adryserage in 1a38a06
|
||||
- feat(graphiti): add Google AI as LLM and embedding provider by @adryserage in fe69106
|
||||
- fix: GitHub organization repository support by @mojaray2k in 873cafa
|
||||
- feat(ui): add LLM provider selection to Graphiti onboarding by @adryserage in 4750869
|
||||
- fix(types): add missing AppSettings properties for Graphiti providers by @adryserage in 6680ed4
|
||||
- feat(ui): add Ollama as LLM provider option for Graphiti by @adryserage in a3eee92
|
||||
- fix(ui): address PR review feedback for Graphiti provider selection by @adryserage in b8a419a
|
||||
- fix(deps): update imports to use @lydell/node-pty directly by @adryserage in 2b61ebb
|
||||
- fix(deps): replace node-pty with @lydell/node-pty for prebuilt binaries by @adryserage in e1aee6a
|
||||
- fix: add UI clarity for per-project GitHub configuration by @mojaray2k in c9745b6
|
||||
- fix: add defensive array validation for GitHub issues API response by @mojaray2k in b3636a5
|
||||
|
||||
---
|
||||
|
||||
## 2.5.5 - Enhanced Agent Reliability & Build Workflow
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
- Required GitHub setup flow after Auto Claude initialization to ensure proper configuration
|
||||
- Atomic log saving mechanism to prevent log file corruption during concurrent operations
|
||||
- Per-session model and thinking level selection in insights management
|
||||
- Multi-auth token support and ANTHROPIC_BASE_URL passthrough for flexible authentication
|
||||
- Comprehensive DEBUG logging at Claude SDK invocation points for improved troubleshooting
|
||||
- Auto-download of prebuilt node-pty binaries for Windows environments
|
||||
- Enhanced merge workflow with current branch detection for accurate change previews
|
||||
- Phase configuration module and enhanced agent profiles for improved flexibility
|
||||
- Stage-only merge handling with comprehensive verification checks
|
||||
- Authentication failure detection system with patterns and validation checks across agent pipeline
|
||||
|
||||
### 🛠️ Improvements
|
||||
|
||||
- Changed default agent profile from 'balanced' to 'auto' for more adaptive behavior
|
||||
- Better GitHub issue tracking and improved user experience in issue management
|
||||
- Improved merge preview accuracy using git diff counts for file statistics
|
||||
- Preserved roadmap generation state when switching between projects
|
||||
- Enhanced agent profiles with phase configuration support
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- Resolved CI test failures and improved merge preview reliability
|
||||
- Fixed CI failures related to linting, formatting, and tests
|
||||
- Prevented dialog skip during project initialization flow
|
||||
- Updated model IDs for Sonnet and Haiku to match current Claude versions
|
||||
- Fixed branch namespace conflict detection to prevent worktree creation failures
|
||||
- Removed duplicate LINEAR_API_KEY checks and consolidated imports
|
||||
- Python 3.10+ version requirement enforced with proper version checking
|
||||
- Prevented command injection vulnerabilities in GitHub API calls
|
||||
|
||||
### 🔧 Other Changes
|
||||
|
||||
- Code cleanup and test fixture updates
|
||||
- Removed redundant auto-claude/specs directory structure
|
||||
- Untracked .auto-claude directory to respect gitignore rules
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- fix: resolve CI test failures and improve merge preview by @AndyMik90 in de2eccd
|
||||
- chore: code cleanup and test fixture updates by @AndyMik90 in 948db57
|
||||
- refactor: change default agent profile from 'balanced' to 'auto' by @AndyMik90 in f98a13e
|
||||
- security: prevent command injection in GitHub API calls by @AndyMik90 in 24ff491
|
||||
- fix: resolve CI failures (lint, format, test) by @AndyMik90 in a8f2d0b
|
||||
- fix: use git diff count for totalFiles in merge preview by @AndyMik90 in 46d2536
|
||||
- feat: enhance stage-only merge handling with verification checks by @AndyMik90 in 7153558
|
||||
- feat: introduce phase configuration module and enhance agent profiles by @AndyMik90 in 2672528
|
||||
- fix: preserve roadmap generation state when switching projects by @AndyMik90 in 569e921
|
||||
- feat: add required GitHub setup flow after Auto Claude initialization by @AndyMik90 in 03ccce5
|
||||
- chore: remove redundant auto-claude/specs directory by @AndyMik90 in 64d5170
|
||||
- chore: untrack .auto-claude directory (should be gitignored) by @AndyMik90 in 0710c13
|
||||
- fix: prevent dialog skip during project initialization by @AndyMik90 in 56cedec
|
||||
- feat: enhance merge workflow by detecting current branch by @AndyMik90 in c0c8067
|
||||
- fix: update model IDs for Sonnet and Haiku by @AndyMik90 in 059315d
|
||||
- feat: add comprehensive DEBUG logging and fix lint errors by @AndyMik90 in 99cf21e
|
||||
- feat: implement atomic log saving to prevent corruption by @AndyMik90 in da5e26b
|
||||
- feat: add better github issue tracking and UX by @AndyMik90 in c957eaa
|
||||
- feat: add comprehensive DEBUG logging to Claude SDK invocation points by @AndyMik90 in 73d01c0
|
||||
- feat: auto-download prebuilt node-pty binaries for Windows by @AndyMik90 in 41a507f
|
||||
- feat(insights): add per-session model and thinking level selection by @AndyMik90 in e02aa59
|
||||
- fix: require Python 3.10+ and add version check by @AndyMik90 in 9a5ca8c
|
||||
- fix: detect branch namespace conflict blocking worktree creation by @AndyMik90 in 63a1d3c
|
||||
- fix: remove duplicate LINEAR_API_KEY check and consolidate imports by @Jacob in 7d351e3
|
||||
- feat: add multi-auth token support and ANTHROPIC_BASE_URL passthrough by @Jacob in 9dea155
|
||||
|
||||
## 2.5.0 - Roadmap Intelligence & Workflow Refinements
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
- Interactive competitor analysis viewer for roadmap planning with real-time data visualization
|
||||
|
||||
- GitHub issue label mapping to task categories for improved organization and tracking
|
||||
|
||||
- GitHub issue comment selection in task creation workflow for better context integration
|
||||
|
||||
- TaskCreationWizard enhanced with drag-and-drop support for file references and inline @mentions
|
||||
|
||||
- Roadmap generation now includes stop functionality and comprehensive debug logging
|
||||
|
||||
### 🛠️ Improvements
|
||||
|
||||
- Refined visual drop zone feedback in file reference system for more subtle user guidance
|
||||
|
||||
- Remove auto-expand behavior for referenced files on draft restore to improve UX
|
||||
|
||||
- Always-visible referenced files section in TaskCreationWizard for better discoverability
|
||||
|
||||
- Drop zone wrapper added around main modal content area for improved drag-and-drop ergonomics
|
||||
|
||||
- Stuck task detection now enabled for ai_review status to better track blocked work
|
||||
|
||||
- Enhanced React component stability with proper key usage in RoadmapHeader and PhaseProgressIndicator
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- Corrected CompetitorAnalysisViewer type definitions for proper TypeScript compliance
|
||||
|
||||
- Fixed multiple CodeRabbit review feedback items for improved code quality
|
||||
|
||||
- Resolved React key warnings in PhaseProgressIndicator component
|
||||
|
||||
- Fixed git status parsing in merge preview for accurate worktree state detection
|
||||
|
||||
- Corrected path resolution in runners for proper module imports and .env loading
|
||||
|
||||
- Resolved CI lint and TypeScript errors across codebase
|
||||
|
||||
- Fixed HTTP error handling and path resolution issues in core modules
|
||||
|
||||
- Corrected worktree test to match intended branch detection behavior
|
||||
|
||||
- Refined TaskReview component conditional rendering for proper staged task display
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- feat: add interactive competitor analysis viewer for roadmap by @AndyMik90 in 7ff326d
|
||||
|
||||
- fix: correct CompetitorAnalysisViewer to match type definitions by @AndyMik90 in 4f1766b
|
||||
|
||||
- fix: address multiple CodeRabbit review feedback items by @AndyMik90 in 48f7c3c
|
||||
|
||||
- fix: use stable React keys instead of array indices in RoadmapHeader by @AndyMik90 in 892e01d
|
||||
|
||||
- fix: additional fixes for http error handling and path resolution by @AndyMik90 in 54501cb
|
||||
|
||||
- fix: update worktree test to match intended branch detection behavior by @AndyMik90 in f1d578f
|
||||
|
||||
- fix: resolve CI lint and TypeScript errors by @AndyMik90 in 2e3a5d9
|
||||
|
||||
- feat: enhance roadmap generation with stop functionality and debug logging by @AndyMik90 in a6dad42
|
||||
|
||||
- fix: correct path resolution in runners for module imports and .env loading by @AndyMik90 in 3d24f8f
|
||||
|
||||
- fix: resolve React key warning in PhaseProgressIndicator by @AndyMik90 in 9106038
|
||||
|
||||
- fix: enable stuck task detection for ai_review status by @AndyMik90 in 895ed9f
|
||||
|
||||
- feat: map GitHub issue labels to task categories by @AndyMik90 in cbe14fd
|
||||
|
||||
- feat: add GitHub issue comment selection and fix auto-start bug by @AndyMik90 in 4c1dd89
|
||||
|
||||
- feat: enhance TaskCreationWizard with drag-and-drop support for file references and inline @mentions by @AndyMik90 in d93eefe
|
||||
|
||||
- cleanup docs by @AndyMik90 in 8e891df
|
||||
|
||||
- fix: correct git status parsing in merge preview by @AndyMik90 in c721dc2
|
||||
|
||||
- Update TaskReview component to refine conditional rendering for staged tasks, ensuring proper display when staging is unsuccessful by @AndyMik90 in 1a2b7a1
|
||||
|
||||
- auto-claude: subtask-2-3 - Refine visual drop zone feedback to be more subtle by @AndyMik90 in 6cff442
|
||||
|
||||
- auto-claude: subtask-2-1 - Remove showFiles auto-expand on draft restore by @AndyMik90 in 12bf69d
|
||||
|
||||
- auto-claude: subtask-1-3 - Create an always-visible referenced files section by @AndyMik90 in 3818b46
|
||||
|
||||
- auto-claude: subtask-1-2 - Add drop zone wrapper around main modal content area by @AndyMik90 in 219b66d
|
||||
|
||||
- auto-claude: subtask-1-1 - Remove Reference Files toggle button by @AndyMik90 in 4e63e85
|
||||
|
||||
## 2.4.0 - Enhanced Cross-Platform Experience with OAuth & Auto-Updates
|
||||
|
||||
### ✨ New Features
|
||||
|
||||
- Claude account OAuth implementation on onboarding for seamless token setup
|
||||
|
||||
- Integrated release workflow with AI-powered version suggestion capabilities
|
||||
|
||||
- Auto-upgrading functionality supporting Windows, Linux, and macOS with automatic app updates
|
||||
|
||||
- Git repository initialization on app startup with project addition checks
|
||||
|
||||
- Debug logging for app updater to track update processes
|
||||
|
||||
- Auto-open settings to updates section when app update is ready
|
||||
|
||||
### 🛠️ Improvements
|
||||
|
||||
- Major Windows and Linux compatibility enhancements for cross-platform reliability
|
||||
|
||||
- Enhanced task status handling to support 'done' status in limbo state with worktree existence checks
|
||||
|
||||
- Better handling of lock files from worktrees upon merging
|
||||
|
||||
- Improved README documentation and build process
|
||||
|
||||
- Refined visual drop zone feedback for more subtle user experience
|
||||
|
||||
- Removed showFiles auto-expand on draft restore for better UX consistency
|
||||
|
||||
- Created always-visible referenced files section in task creation wizard
|
||||
|
||||
- Removed Reference Files toggle button for streamlined interface
|
||||
|
||||
- Worktree manual deletion enforcement for early access safety (prevents accidental work loss)
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- Corrected git status parsing in merge preview functionality
|
||||
|
||||
- Fixed ESLint warnings and failing tests
|
||||
|
||||
- Fixed Windows/Linux Python handling for cross-platform compatibility
|
||||
|
||||
- Fixed Windows/Linux source path detection
|
||||
|
||||
- Refined TaskReview component conditional rendering for proper staged task display
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- docs: cleanup docs by @AndyMik90 in 8e891df
|
||||
- fix: correct git status parsing in merge preview by @AndyMik90 in c721dc2
|
||||
- refactor: Update TaskReview component to refine conditional rendering for staged tasks by @AndyMik90 in 1a2b7a1
|
||||
- feat: Enhance task status handling to allow 'done' status in limbo state by @AndyMik90 in a20b8cf
|
||||
- improvement: Worktree needs to be manually deleted for early access safety by @AndyMik90 in 0ed6afb
|
||||
- feat: Claude account OAuth implementation on onboarding by @AndyMik90 in 914a09d
|
||||
- fix: Better handling of lock files from worktrees upon merging by @AndyMik90 in e44202a
|
||||
- feat: GitHub OAuth integration upon onboarding by @AndyMik90 in 4249644
|
||||
- chore: lock update by @AndyMik90 in b0fc497
|
||||
- improvement: Improved README and build process by @AndyMik90 in 462edcd
|
||||
- fix: ESLint warnings and failing tests by @AndyMik90 in affbc48
|
||||
- feat: Major Windows and Linux compatibility enhancements with auto-upgrade by @AndyMik90 in d7fd1a2
|
||||
- feat: Add debug logging to app updater by @AndyMik90 in 96dd04d
|
||||
- feat: Auto-open settings to updates section when app update is ready by @AndyMik90 in 1d0566f
|
||||
- feat: Add integrated release workflow with AI version suggestion by @AndyMik90 in 7f3cd59
|
||||
- fix: Windows/Linux Python handling by @AndyMik90 in 0ef0e15
|
||||
- feat: Implement Electron app auto-updater by @AndyMik90 in efc112a
|
||||
- fix: Windows/Linux source path detection by @AndyMik90 in d33a0aa
|
||||
- refactor: Refine visual drop zone feedback to be more subtle by @AndyMik90 in 6cff442
|
||||
- refactor: Remove showFiles auto-expand on draft restore by @AndyMik90 in 12bf69d
|
||||
- feat: Create always-visible referenced files section by @AndyMik90 in 3818b46
|
||||
- feat: Add drop zone wrapper around main modal content by @AndyMik90 in 219b66d
|
||||
- feat: Remove Reference Files toggle button by @AndyMik90 in 4e63e85
|
||||
- docs: Update README with git initialization and folder structure by @AndyMik90 in 2fa3c51
|
||||
- chore: Version bump to 2.3.2 by @AndyMik90 in 59b091a
|
||||
|
||||
## 2.3.2 - UI Polish & Build Improvements
|
||||
|
||||
### 🛠️ Improvements
|
||||
|
||||
- Restructured SortableFeatureCard badge layout for improved visual presentation
|
||||
|
||||
Bug Fixes:
|
||||
- Fixed spec runner path configuration for more reliable task execution
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- fix: fix to spec runner paths by @AndyMik90 in 9babdc2
|
||||
|
||||
- feat: auto-claude: subtask-1-1 - Restructure SortableFeatureCard badge layout by @AndyMik90 in dc886dc
|
||||
|
||||
## 2.3.1 - Linux Compatibility Fix
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- Resolved path handling issues on Linux systems for improved cross-platform compatibility
|
||||
|
||||
---
|
||||
|
||||
## What's Changed
|
||||
|
||||
- fix: Fix to linux path issue by @AndyMik90 in 3276034
|
||||
|
||||
## 2.2.0 - 2025-12-17
|
||||
|
||||
### ✨ New Features
|
||||
@@ -278,4 +924,4 @@
|
||||
- **Draft Auto-Save**: Task creation state is now automatically saved when you navigate away, preventing accidental loss of work-in-progress.
|
||||
|
||||
### Bug Fixes
|
||||
- Fixed task editing to support the same comprehensive options available in new task creation
|
||||
- Fixed task editing to support the same comprehensive options available in new task creation
|
||||
|
||||
@@ -81,6 +81,21 @@ auto-claude/.venv/bin/pytest tests/ -m "not slow"
|
||||
python auto-claude/validate_spec.py --spec-dir auto-claude/specs/001-feature --checkpoint all
|
||||
```
|
||||
|
||||
### Releases
|
||||
```bash
|
||||
# Automated version bump and release (recommended)
|
||||
node scripts/bump-version.js patch # 2.5.5 -> 2.5.6
|
||||
node scripts/bump-version.js minor # 2.5.5 -> 2.6.0
|
||||
node scripts/bump-version.js major # 2.5.5 -> 3.0.0
|
||||
node scripts/bump-version.js 2.6.0 # Set specific version
|
||||
|
||||
# Then push to trigger GitHub release workflows
|
||||
git push origin main
|
||||
git push origin v2.6.0
|
||||
```
|
||||
|
||||
See [RELEASE.md](RELEASE.md) for detailed release process documentation.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Core Pipeline
|
||||
@@ -103,7 +118,7 @@ python auto-claude/validate_spec.py --spec-dir auto-claude/specs/001-feature --c
|
||||
- **worktree.py** - Git worktree isolation for safe feature development
|
||||
- **memory.py** - File-based session memory (primary, always-available storage)
|
||||
- **graphiti_memory.py** - Optional graph-based cross-session memory with semantic search
|
||||
- **graphiti_providers.py** - Multi-provider factory for Graphiti (OpenAI, Anthropic, Azure, Ollama)
|
||||
- **graphiti_providers.py** - Multi-provider factory for Graphiti (OpenAI, Anthropic, Azure, Ollama, Google AI)
|
||||
- **graphiti_config.py** - Configuration and validation for Graphiti integration
|
||||
- **linear_updater.py** - Optional Linear integration for progress tracking
|
||||
|
||||
@@ -174,11 +189,17 @@ Dual-layer memory architecture:
|
||||
- Session insights, patterns, gotchas, codebase map
|
||||
|
||||
**Graphiti Memory (Optional Enhancement)** - `graphiti_memory.py`
|
||||
- Graph database with semantic search (FalkorDB)
|
||||
- Graph database with semantic search (LadybugDB - embedded, no Docker)
|
||||
- Cross-session context retrieval
|
||||
- Multi-provider support (V2):
|
||||
- LLM: OpenAI, Anthropic, Azure OpenAI, Ollama
|
||||
- Embedders: OpenAI, Voyage AI, Azure OpenAI, Ollama
|
||||
- Requires Python 3.12+
|
||||
- Multi-provider support:
|
||||
- LLM: OpenAI, Anthropic, Azure OpenAI, Ollama, Google AI (Gemini)
|
||||
- Embedders: OpenAI, Voyage AI, Azure OpenAI, Ollama, Google AI
|
||||
|
||||
```bash
|
||||
# Setup (requires Python 3.12+)
|
||||
pip install real_ladybug graphiti-core
|
||||
```
|
||||
|
||||
Enable with: `GRAPHITI_ENABLED=true` + provider credentials. See `.env.example`.
|
||||
|
||||
|
||||
+53
-1
@@ -8,6 +8,7 @@ Thank you for your interest in contributing to Auto Claude! This document provid
|
||||
- [Development Setup](#development-setup)
|
||||
- [Python Backend](#python-backend)
|
||||
- [Electron Frontend](#electron-frontend)
|
||||
- [Running from Source](#running-from-source)
|
||||
- [Pre-commit Hooks](#pre-commit-hooks)
|
||||
- [Code Style](#code-style)
|
||||
- [Testing](#testing)
|
||||
@@ -28,7 +29,6 @@ Before contributing, ensure you have the following installed:
|
||||
- **pnpm** - Package manager for the frontend (`npm install -g pnpm`)
|
||||
- **uv** (recommended) or **pip** - Python package manager
|
||||
- **Git** - Version control
|
||||
- **Docker** (optional) - For running FalkorDB if using Graphiti memory
|
||||
|
||||
## Development Setup
|
||||
|
||||
@@ -80,6 +80,58 @@ pnpm build
|
||||
pnpm package
|
||||
```
|
||||
|
||||
## Running from Source
|
||||
|
||||
If you want to run Auto Claude from source (for development or testing unreleased features), follow these steps:
|
||||
|
||||
### Step 1: Clone and Set Up Python Backend
|
||||
|
||||
```bash
|
||||
git clone https://github.com/AndyMik90/Auto-Claude.git
|
||||
cd Auto-Claude/auto-claude
|
||||
|
||||
# Using uv (recommended)
|
||||
uv venv && uv pip install -r requirements.txt
|
||||
|
||||
# Or using standard Python
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate # On Windows: .venv\Scripts\activate
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Set up environment
|
||||
cp .env.example .env
|
||||
# Edit .env and add your CLAUDE_CODE_OAUTH_TOKEN (get it via: claude setup-token)
|
||||
```
|
||||
|
||||
### Step 2: Run the Desktop UI
|
||||
|
||||
```bash
|
||||
cd ../auto-claude-ui
|
||||
|
||||
# Install dependencies
|
||||
pnpm install
|
||||
|
||||
# Development mode (hot reload)
|
||||
pnpm dev
|
||||
|
||||
# Or production build
|
||||
pnpm run build && pnpm run start
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><b>Windows users:</b> If installation fails with node-gyp errors, click here</summary>
|
||||
|
||||
Auto Claude automatically downloads prebuilt binaries for Windows. If prebuilts aren't available for your Electron version yet, you'll need Visual Studio Build Tools:
|
||||
|
||||
1. Download [Visual Studio Build Tools 2022](https://visualstudio.microsoft.com/visual-cpp-build-tools/)
|
||||
2. Select "Desktop development with C++" workload
|
||||
3. In "Individual Components", add "MSVC v143 - VS 2022 C++ x64/x86 Spectre-mitigated libs"
|
||||
4. Restart terminal and run `pnpm install` again
|
||||
|
||||
</details>
|
||||
|
||||
> **Note:** For regular usage, we recommend downloading the pre-built releases from [GitHub Releases](https://github.com/AndyMik90/Auto-Claude/releases). Running from source is primarily for contributors and those testing unreleased features.
|
||||
|
||||
## Pre-commit Hooks
|
||||
|
||||
We use [pre-commit](https://pre-commit.com/) to run linting and formatting checks before each commit. This ensures code quality and consistency across the project.
|
||||
|
||||
@@ -0,0 +1,641 @@
|
||||
# Investigation: v2.7.1 Release Artifacts Issue
|
||||
|
||||
## Investigation Date
|
||||
|
||||
2025-12-25
|
||||
|
||||
## Summary
|
||||
|
||||
The v2.7.1 release has **incorrect files attached**. All artifacts have v2.7.0 in their filenames, indicating the wrong build artifacts were uploaded.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Reproduce and Verify Issue
|
||||
|
||||
### Subtask 1-1: Current v2.7.1 Assets
|
||||
|
||||
**Command:** `gh release view v2.7.1 --json assets -q '.assets[].name'`
|
||||
|
||||
**Release Metadata:**
|
||||
- Tag Name: v2.7.1
|
||||
- Release Name: v2.7.1
|
||||
- Published At: 2025-12-22T13:35:38Z
|
||||
- Is Draft: false
|
||||
- Is Prerelease: false
|
||||
|
||||
**Files Currently Attached to v2.7.1:**
|
||||
|
||||
| File Name | Size (bytes) | Expected Name |
|
||||
|-----------|-------------|---------------|
|
||||
| Auto-Claude-2.7.0-darwin-arm64.dmg | 124,187,073 | Auto-Claude-2.7.1-darwin-arm64.dmg |
|
||||
| Auto-Claude-2.7.0-darwin-arm64.zip | 117,694,085 | Auto-Claude-2.7.1-darwin-arm64.zip |
|
||||
| Auto-Claude-2.7.0-darwin-x64.dmg | 130,635,398 | Auto-Claude-2.7.1-darwin-x64.dmg |
|
||||
| Auto-Claude-2.7.0-darwin-x64.zip | 124,176,354 | Auto-Claude-2.7.1-darwin-x64.zip |
|
||||
| Auto-Claude-2.7.0-linux-amd64.deb | 104,558,694 | Auto-Claude-2.7.1-linux-amd64.deb |
|
||||
| Auto-Claude-2.7.0-linux-x86_64.AppImage | 145,482,885 | Auto-Claude-2.7.1-linux-x86_64.AppImage |
|
||||
| Auto-Claude-2.7.0-win32-x64.exe | 101,941,972 | Auto-Claude-2.7.1-win32-x64.exe |
|
||||
| checksums.sha256 | 718 | checksums.sha256 (with v2.7.1 filenames) |
|
||||
|
||||
### Issue Confirmed
|
||||
|
||||
**Problem:** All 7 platform artifacts attached to v2.7.1 have "2.7.0" in their filename instead of "2.7.1".
|
||||
|
||||
**Impact:**
|
||||
- Users downloading v2.7.1 are receiving v2.7.0 binaries
|
||||
- File naming does not match the release version
|
||||
- Checksums file likely references v2.7.0 filenames
|
||||
- Auto-update mechanisms may be confused by version mismatch
|
||||
|
||||
**Evidence:**
|
||||
```
|
||||
Files attached to v2.7.1:
|
||||
- Auto-Claude-2.7.0-darwin-arm64.dmg (WRONG - should be 2.7.1)
|
||||
- Auto-Claude-2.7.0-darwin-arm64.zip (WRONG - should be 2.7.1)
|
||||
- Auto-Claude-2.7.0-darwin-x64.dmg (WRONG - should be 2.7.1)
|
||||
- Auto-Claude-2.7.0-darwin-x64.zip (WRONG - should be 2.7.1)
|
||||
- Auto-Claude-2.7.0-linux-amd64.deb (WRONG - should be 2.7.1)
|
||||
- Auto-Claude-2.7.0-linux-x86_64.AppImage (WRONG - should be 2.7.1)
|
||||
- Auto-Claude-2.7.0-win32-x64.exe (WRONG - should be 2.7.1)
|
||||
- checksums.sha256 (likely references wrong filenames)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Subtask 1-2: Comparison with v2.7.0 and Expected Naming
|
||||
|
||||
**Command:** `gh release view v2.7.0 --json assets -q '.assets[].name'`
|
||||
|
||||
#### v2.7.0 Release Analysis
|
||||
|
||||
**Release Metadata:**
|
||||
- Tag Name: v2.7.0
|
||||
- Release Name: v2.7.0
|
||||
- Published At: 2025-12-22T13:19:13Z
|
||||
- Target Commitish: main
|
||||
- Is Draft: false
|
||||
- Is Prerelease: false
|
||||
|
||||
**Critical Finding:** v2.7.0 has **NO assets attached** (empty assets array).
|
||||
|
||||
#### Release Timeline
|
||||
|
||||
| Release | Published At | Assets Count | Status |
|
||||
|---------|-------------|--------------|--------|
|
||||
| v2.7.0 | 2025-12-22T13:19:13Z | 0 | No files attached |
|
||||
| v2.7.1 | 2025-12-22T13:35:38Z | 8 | Wrong version in filenames |
|
||||
| v2.7.2 | 2025-12-22T13:52:51Z | ? | Draft release |
|
||||
|
||||
**Observation:** v2.7.0 was published 16 minutes before v2.7.1, but has no artifacts attached.
|
||||
|
||||
#### Checksums File Analysis
|
||||
|
||||
The `checksums.sha256` file attached to v2.7.1 contains:
|
||||
```
|
||||
0a0094ff3e52609665f6f0d6d54180dbfc592956f91ef2cdd94e43a61b6b24d2 ./Auto-Claude-2.7.0-darwin-arm64.dmg
|
||||
43b168f3073d60644bb111c8fa548369431dc448e67700ed526cb4cad61034e0 ./Auto-Claude-2.7.0-darwin-arm64.zip
|
||||
5150cbba934fbeb3d97309a493cc8ef3c035e9ec38b31f01382d628025f5c451 ./Auto-Claude-2.7.0-darwin-x64.dmg
|
||||
ea9139277290a8189f799d00bc3cd1aaf81a16e890ff90327eca01a4cce73e61 ./Auto-Claude-2.7.0-darwin-x64.zip
|
||||
078b2ba6a2594bf048932776dc31a45e59cd9cb23b34b2cf2f810f4101f04736 ./Auto-Claude-2.7.0-linux-amd64.deb
|
||||
1feb6b9be348a5e23238e009dbc1ce8b2788103a262cd856613332b3ab1711e9 ./Auto-Claude-2.7.0-linux-x86_64.AppImage
|
||||
25383314b3bc032ceaf8a8416d5383879ed351c906f03175b8533047647a612d ./Auto-Claude-2.7.0-win32-x64.exe
|
||||
```
|
||||
|
||||
**Issue:** Checksums file also references v2.7.0 filenames, confirming the build was run with v2.7.0 version.
|
||||
|
||||
#### Expected Naming Pattern (from release.yml)
|
||||
|
||||
Based on the release workflow analysis, artifacts follow this naming convention:
|
||||
```
|
||||
Auto-Claude-{version}-{platform}-{arch}.{ext}
|
||||
```
|
||||
|
||||
Where version comes from `package.json` in `auto-claude-ui/`.
|
||||
|
||||
**Expected v2.7.1 Artifacts:**
|
||||
| Expected Filename | Actual Filename (Wrong) |
|
||||
|-------------------|-------------------------|
|
||||
| Auto-Claude-2.7.1-darwin-arm64.dmg | Auto-Claude-2.7.0-darwin-arm64.dmg |
|
||||
| Auto-Claude-2.7.1-darwin-arm64.zip | Auto-Claude-2.7.0-darwin-arm64.zip |
|
||||
| Auto-Claude-2.7.1-darwin-x64.dmg | Auto-Claude-2.7.0-darwin-x64.dmg |
|
||||
| Auto-Claude-2.7.1-darwin-x64.zip | Auto-Claude-2.7.0-darwin-x64.zip |
|
||||
| Auto-Claude-2.7.1-linux-amd64.deb | Auto-Claude-2.7.0-linux-amd64.deb |
|
||||
| Auto-Claude-2.7.1-linux-x86_64.AppImage | Auto-Claude-2.7.0-linux-x86_64.AppImage |
|
||||
| Auto-Claude-2.7.1-win32-x64.exe | Auto-Claude-2.7.0-win32-x64.exe |
|
||||
| checksums.sha256 (v2.7.1 refs) | checksums.sha256 (v2.7.0 refs) |
|
||||
|
||||
#### Hypothesis
|
||||
|
||||
The evidence suggests one of the following scenarios:
|
||||
|
||||
1. **Tag/Version Mismatch:** The v2.7.1 tag may point to a commit where `package.json` still had version `2.7.0`
|
||||
2. **Workflow Re-run:** The v2.7.1 release may have been created by re-running the v2.7.0 workflow artifacts
|
||||
3. **Manual Upload Error:** Artifacts from v2.7.0 were manually attached to the v2.7.1 release
|
||||
4. **Artifact Caching:** Old workflow artifacts were incorrectly reused for v2.7.1
|
||||
|
||||
**Next step:** Check git tags and package.json versions to determine root cause.
|
||||
|
||||
---
|
||||
|
||||
### Subtask 1-3: Package.json Version and Git State Analysis
|
||||
|
||||
**Commands Used:**
|
||||
- `git show v2.7.1:auto-claude-ui/package.json | jq -r '.version'`
|
||||
- `git show v2.7.0:auto-claude-ui/package.json | jq -r '.version'`
|
||||
- `git log --oneline v2.7.0..v2.7.1`
|
||||
- `git rev-parse v2.7.1^{commit}`
|
||||
|
||||
#### Current Package.json State
|
||||
|
||||
| Location | Current Version |
|
||||
|----------|-----------------|
|
||||
| `auto-claude-ui/package.json` (HEAD) | 2.7.1 |
|
||||
|
||||
**Note:** The subtask referenced `apps/frontend/package.json`, but the actual path is `auto-claude-ui/package.json`.
|
||||
|
||||
#### Version at Git Tags
|
||||
|
||||
| Tag | Commit | package.json Version | Expected |
|
||||
|-----|--------|---------------------|----------|
|
||||
| v2.7.0 | `fe7290a8` | 2.6.5 | 2.7.0 |
|
||||
| v2.7.1 | `772a5006` | **2.7.0** ❌ | 2.7.1 |
|
||||
|
||||
#### Commit Timeline
|
||||
|
||||
```
|
||||
fc2075dd auto-claude: subtask-1-2 - Compare v2.7.1 artifacts...
|
||||
ff033a8e auto-claude: subtask-1-1 - List all files...
|
||||
8db71f3d Update version to 2.7.1 in package.json <-- Version bump (AFTER tag)
|
||||
772a5006 2.7.1 <-- v2.7.1 TAG placed here
|
||||
d23fcd86 Enhance VirusTotal scan error handling...
|
||||
...more commits...
|
||||
fe7290a8 Release v2.7.0... <-- v2.7.0 TAG placed here
|
||||
```
|
||||
|
||||
#### Root Cause Identified ✅
|
||||
|
||||
**Problem:** The `v2.7.1` tag was placed on commit `772a5006` BEFORE the `package.json` version was updated to `2.7.1`.
|
||||
|
||||
**Timeline of error:**
|
||||
1. Commit `772a5006` created with message "2.7.1" - tag `v2.7.1` placed here
|
||||
2. At this commit, `package.json` still contained version `2.7.0`
|
||||
3. The release workflow triggered on tag push, building with version `2.7.0` from `package.json`
|
||||
4. All artifacts named with `2.7.0` because that's what was in `package.json`
|
||||
5. Commit `8db71f3d` later updated `package.json` to `2.7.1` (but tag was already pushed)
|
||||
|
||||
**This is a "tag before version bump" error.**
|
||||
|
||||
The release workflow correctly read the version from `package.json`, but the tag was created before the version was bumped. The naming convention `${productName}-${version}-${platform}-${arch}.${ext}` correctly used version `2.7.0` because that's what was in `package.json` at the tagged commit.
|
||||
|
||||
#### Verification of Build Configuration
|
||||
|
||||
From `auto-claude-ui/package.json`:
|
||||
```json
|
||||
"build": {
|
||||
"artifactName": "${productName}-${version}-${platform}-${arch}.${ext}",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
This confirms the version is sourced from `package.json` during the build process.
|
||||
|
||||
#### Git State Summary
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| Current Branch | `auto-claude/009-latest-release-v2-7-1-has-wrong-files-attached` |
|
||||
| Working Tree | Clean |
|
||||
| Current HEAD package.json | 2.7.1 |
|
||||
| v2.7.1 tag package.json | 2.7.0 ❌ |
|
||||
| v2.7.0 tag package.json | 2.6.5 ❌ |
|
||||
|
||||
**Note:** Both v2.7.0 and v2.7.1 tags have version mismatches in `package.json`, indicating a pattern of tagging before version bumping.
|
||||
|
||||
---
|
||||
|
||||
## Root Cause Summary
|
||||
|
||||
| Factor | Finding |
|
||||
|--------|---------|
|
||||
| What happened? | v2.7.1 tag placed before package.json version bump |
|
||||
| Why? | Incorrect release process: tag first, version bump second |
|
||||
| Impact | All 7 artifacts have v2.7.0 in filename |
|
||||
| Evidence | `git show v2.7.1:auto-claude-ui/package.json` shows version 2.7.0 |
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Root Cause Analysis
|
||||
|
||||
### Subtask 2-1: Inspect v2.7.1 Git Tag and Commit
|
||||
|
||||
**Commands Used:**
|
||||
```bash
|
||||
git log -1 v2.7.1 --format='%H %s %ci'
|
||||
git show v2.7.1 --format='Commit: %H%nAuthor: %an <%ae>%nDate: %ci%nMessage: %s' --no-patch
|
||||
git tag -l v2.7.1 -n1
|
||||
git cat-file -t v2.7.1
|
||||
git show v2.7.1:auto-claude-ui/package.json | head -10 | grep version
|
||||
```
|
||||
|
||||
#### Tag Details
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Tag Name | v2.7.1 |
|
||||
| Tag Type | Lightweight (commit reference, not annotated) |
|
||||
| Points To | `772a5006d45487b600ce4079bae1c98f9ccf6b2e` |
|
||||
|
||||
#### Tagged Commit Details
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Commit Hash | `772a5006d45487b600ce4079bae1c98f9ccf6b2e` |
|
||||
| Author | AndyMik90 <andre@mikalsenutvikling.no> |
|
||||
| Commit Date | 2025-12-22 14:35:30 +0100 |
|
||||
| Commit Message | `2.7.1` |
|
||||
| package.json Version | **2.7.0** (MISMATCH) |
|
||||
|
||||
#### Verification Output
|
||||
|
||||
```
|
||||
$ git log -1 v2.7.1 --format='%H %s %ci'
|
||||
772a5006d45487b600ce4079bae1c98f9ccf6b2e 2.7.1 2025-12-22 14:35:30 +0100
|
||||
|
||||
$ git show v2.7.1:auto-claude-ui/package.json | grep version
|
||||
"version": "2.7.0",
|
||||
```
|
||||
|
||||
#### Commit Context
|
||||
|
||||
```
|
||||
$ git log -3 --oneline v2.7.1
|
||||
772a5006 2.7.1 <-- v2.7.1 TAG HERE
|
||||
d23fcd86 Enhance VirusTotal scan error handling...
|
||||
326118bd Refactor macOS build workflow...
|
||||
```
|
||||
|
||||
#### Analysis
|
||||
|
||||
1. **Tag Type:** The tag is a lightweight tag (just a commit reference), not an annotated tag. This means there's no separate tag object with metadata, author, or message.
|
||||
|
||||
2. **Commit Message vs Version:** The commit message says "2.7.1" but the `package.json` at this commit still contains version `2.7.0`. This is the source of the mismatch.
|
||||
|
||||
3. **Release Workflow Behavior:** When the GitHub release workflow triggered on tag push `v2.7.1`:
|
||||
- It checked out commit `772a5006`
|
||||
- It read version from `auto-claude-ui/package.json` which was `2.7.0`
|
||||
- It built artifacts with `2.7.0` in the filename
|
||||
- It uploaded these incorrectly-versioned artifacts to the v2.7.1 release
|
||||
|
||||
4. **Timeline Confirmation:**
|
||||
- Tag created: 2025-12-22 14:35:30 +0100
|
||||
- Release published: 2025-12-22T13:35:38Z (same time, UTC)
|
||||
- Version bump commit `8db71f3d` happened AFTER this
|
||||
|
||||
#### Root Cause Confirmed
|
||||
|
||||
The v2.7.1 tag points to a commit where `package.json` still had version `2.7.0`. This is a **"tag before version bump"** error in the release process.
|
||||
|
||||
The correct sequence should have been:
|
||||
1. First: Bump package.json version to 2.7.1
|
||||
2. Second: Commit the version bump
|
||||
3. Third: Create and push the v2.7.1 tag
|
||||
|
||||
What actually happened:
|
||||
1. Created tag v2.7.1 on commit with package.json version 2.7.0
|
||||
2. Workflow triggered and built with wrong version
|
||||
3. Version bump to 2.7.1 committed afterwards (too late)
|
||||
|
||||
---
|
||||
|
||||
### Subtask 2-2: GitHub Actions Workflow Run Analysis
|
||||
|
||||
**Commands Used:**
|
||||
```bash
|
||||
gh run list --workflow=release.yml --limit=20
|
||||
gh run view 20433472030 --json conclusion,status,headSha,event,jobs
|
||||
gh run view 20433472034 --json conclusion,status,headSha,jobs # Validate Version workflow
|
||||
```
|
||||
|
||||
#### Release Workflow Run Details
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Run ID | 20433472030 |
|
||||
| Status | Completed |
|
||||
| Conclusion | **success** |
|
||||
| Event | push (tag v2.7.1) |
|
||||
| Head SHA | `772a5006d45487b600ce4079bae1c98f9ccf6b2e` |
|
||||
| Created At | 2025-12-22T13:35:39Z |
|
||||
| Updated At | 2025-12-22T13:53:02Z |
|
||||
| Total Duration | ~17 minutes |
|
||||
|
||||
#### Build Jobs Summary
|
||||
|
||||
| Job | Status | Duration | Started | Completed |
|
||||
|-----|--------|----------|---------|-----------|
|
||||
| build-linux | ✅ success | ~2.5 min | 13:35:42Z | 13:38:15Z |
|
||||
| build-windows | ✅ success | ~4.5 min | 13:35:41Z | 13:40:11Z |
|
||||
| build-macos-intel | ✅ success | ~7 min | 13:35:42Z | 13:42:52Z |
|
||||
| build-macos-arm64 | ✅ success | ~5.5 min | 13:35:42Z | 13:41:12Z |
|
||||
| create-release | ✅ success | ~10 min | 13:42:55Z | 13:53:01Z |
|
||||
|
||||
#### Create-Release Job Steps
|
||||
|
||||
| Step | Conclusion |
|
||||
|------|------------|
|
||||
| Set up job | ✅ success |
|
||||
| Run actions/checkout@v4 | ✅ success |
|
||||
| Download all artifacts | ✅ success |
|
||||
| Flatten and validate artifacts | ✅ success |
|
||||
| Generate checksums | ✅ success |
|
||||
| Scan with VirusTotal | ✅ success |
|
||||
| Dry run summary | ⏭️ skipped |
|
||||
| Generate changelog | ✅ success |
|
||||
| Create Release | ✅ success |
|
||||
|
||||
**Workflow Analysis:** The release workflow executed **successfully** - all build jobs and the release creation completed without errors. The workflow correctly:
|
||||
1. Checked out commit `772a5006d45487b600ce4079bae1c98f9ccf6b2e`
|
||||
2. Built artifacts for all platforms (Linux, Windows, macOS Intel, macOS ARM64)
|
||||
3. Generated checksums
|
||||
4. Ran VirusTotal scans
|
||||
5. Created the GitHub release with artifacts
|
||||
|
||||
**Key Finding:** The workflow operated as designed. The problem was the **input** (source code at tagged commit), not the **workflow logic**.
|
||||
|
||||
---
|
||||
|
||||
#### 🚨 CRITICAL: Validate Version Workflow FAILED
|
||||
|
||||
**Run ID:** 20433472034
|
||||
**Conclusion:** ❌ **FAILURE**
|
||||
|
||||
| Step | Conclusion |
|
||||
|------|------------|
|
||||
| Set up job | ✅ success |
|
||||
| Checkout | ✅ success |
|
||||
| Extract version from tag | ✅ success |
|
||||
| Extract version from package.json | ✅ success |
|
||||
| **Compare versions** | ❌ **FAILURE** |
|
||||
| Version validation result | ⏭️ skipped |
|
||||
|
||||
**What Happened:**
|
||||
1. The `validate-version.yml` workflow triggered on the v2.7.1 tag push
|
||||
2. It correctly detected that:
|
||||
- Tag version: `2.7.1`
|
||||
- package.json version: `2.7.0`
|
||||
3. It **FAILED** with an error because versions didn't match
|
||||
|
||||
**Why Didn't This Stop the Release?**
|
||||
|
||||
The `validate-version.yml` and `release.yml` workflows are **independent**:
|
||||
- Both trigger on `push: tags: - 'v*'`
|
||||
- They run in **parallel**, not sequentially
|
||||
- The release workflow has **no dependency** on the validation workflow
|
||||
- Even though validation failed, the release proceeded and succeeded
|
||||
|
||||
**Validation Workflow (from `.github/workflows/validate-version.yml`):**
|
||||
```yaml
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
```
|
||||
|
||||
**Expected Output from Failed Validation:**
|
||||
```
|
||||
❌ ERROR: Version mismatch detected!
|
||||
|
||||
The version in package.json (2.7.0) does not match
|
||||
the git tag version (2.7.1).
|
||||
|
||||
To fix this:
|
||||
1. Delete this tag: git tag -d v2.7.1
|
||||
2. Update package.json version to 2.7.1
|
||||
3. Commit the change
|
||||
4. Recreate the tag: git tag -a v2.7.1 -m 'Release v2.7.1'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### Workflow Architecture Issue
|
||||
|
||||
```
|
||||
Tag Push (v2.7.1)
|
||||
│
|
||||
├──────────────────────────────────┐
|
||||
│ │
|
||||
▼ ▼
|
||||
┌──────────────────┐ ┌──────────────────┐
|
||||
│ validate-version │ │ release │
|
||||
│ ❌ FAILED │ │ ✅ SUCCESS │
|
||||
│ (detected error) │ ← No │ (built wrong │
|
||||
│ │ link → │ version) │
|
||||
└──────────────────┘ └──────────────────┘
|
||||
```
|
||||
|
||||
**Problem:** The validation workflow runs but cannot **block** the release workflow.
|
||||
|
||||
---
|
||||
|
||||
#### Other v2.7.1 Workflows
|
||||
|
||||
| Workflow | Run ID | Conclusion | Notes |
|
||||
|----------|--------|------------|-------|
|
||||
| Release | 20433472030 | ✅ success | Built and released v2.7.0 files |
|
||||
| Validate Version | 20433472034 | ❌ failure | Detected mismatch but couldn't stop release |
|
||||
| Discord Release Notification | 20433472029 | ✅ success | Notified Discord about "v2.7.1" |
|
||||
| Test on Tag | 20433472046 | ✅ success | Tests passed |
|
||||
| Build Native Module Prebuilds | 20433472017 | ❌ failure | Separate prebuilt module issue |
|
||||
|
||||
---
|
||||
|
||||
#### Root Cause Confirmation
|
||||
|
||||
The GitHub Actions analysis confirms:
|
||||
|
||||
1. **The release workflow worked correctly** - it built exactly what was in the source code at the tagged commit
|
||||
2. **The validation workflow detected the problem** - it correctly identified the version mismatch
|
||||
3. **The workflows are not connected** - validation failure could not prevent the release
|
||||
4. **The artifacts are from the right commit but wrong version** - v2.7.1 release contains v2.7.0 artifacts because that's what package.json said at commit `772a5006`
|
||||
|
||||
---
|
||||
|
||||
### Subtask 2-3: Root Cause Statement and Fix Options
|
||||
|
||||
#### Root Cause Statement
|
||||
|
||||
**Summary:** The v2.7.1 release contains v2.7.0 artifacts because the git tag was created BEFORE the `package.json` version was updated.
|
||||
|
||||
**Root Cause:** "Tag Before Version Bump" Error
|
||||
|
||||
| Factor | Details |
|
||||
|--------|---------|
|
||||
| **What happened** | The `v2.7.1` git tag was placed on commit `772a5006` which still had `package.json` version `2.7.0` |
|
||||
| **Why it happened** | Incorrect release procedure: tag was created before version bump was committed |
|
||||
| **How it propagated** | The release workflow correctly built from the tagged commit, reading version `2.7.0` from `package.json` |
|
||||
| **Why it wasn't caught** | The `validate-version.yml` workflow detected the mismatch but runs in parallel with `release.yml` and cannot block it |
|
||||
|
||||
**Evidence Chain:**
|
||||
1. `git show v2.7.1:auto-claude-ui/package.json` → version `2.7.0`
|
||||
2. Release workflow run #20433472030 → built from commit `772a5006` → success
|
||||
3. Validate-version workflow run #20433472034 → detected mismatch → **FAILED** (but couldn't stop release)
|
||||
4. All 7 artifacts named `Auto-Claude-2.7.0-*` instead of `Auto-Claude-2.7.1-*`
|
||||
|
||||
**Contributing Factors:**
|
||||
- Lightweight tag (no metadata) - easier to create on wrong commit
|
||||
- No pre-tag validation hook or script
|
||||
- Independent parallel workflows with no blocking dependency
|
||||
- Version in `package.json` is the single source of truth for artifact naming
|
||||
|
||||
---
|
||||
|
||||
#### Fix Options
|
||||
|
||||
##### Option A: Recreate v2.7.1 Tag and Release (RECOMMENDED)
|
||||
|
||||
**Description:** Delete the current v2.7.1 tag and release, then create a new tag on a commit where `package.json` has version `2.7.1`.
|
||||
|
||||
**Steps:**
|
||||
1. Delete the v2.7.1 GitHub release: `gh release delete v2.7.1 --cleanup-tag --yes`
|
||||
2. Identify correct commit: `git log --oneline | grep -A1 "Update version to 2.7.1"`
|
||||
3. Create new tag at correct commit: `git tag v2.7.1 8db71f3d && git push origin v2.7.1`
|
||||
4. Release workflow will trigger automatically with correct version
|
||||
5. Verify new artifacts have `2.7.1` in filenames
|
||||
|
||||
**Pros:**
|
||||
- ✅ Users get the correct version they expect (v2.7.1)
|
||||
- ✅ Maintains clean version history
|
||||
- ✅ Checksums will match the correct filenames
|
||||
- ✅ Auto-update mechanisms will work correctly
|
||||
- ✅ No need to update documentation or links
|
||||
|
||||
**Cons:**
|
||||
- ⚠️ Users who already downloaded v2.7.1 (v2.7.0 files) may be confused
|
||||
- ⚠️ Requires deleting and recreating the release
|
||||
- ⚠️ Brief window where v2.7.1 doesn't exist
|
||||
|
||||
**Risk Level:** Medium - temporary unavailability, but correct outcome
|
||||
|
||||
---
|
||||
|
||||
##### Option B: Publish v2.7.2 with Correct Files
|
||||
|
||||
**Description:** Leave v2.7.1 as-is (deprecated) and publish v2.7.2 with the correct build.
|
||||
|
||||
**Steps:**
|
||||
1. Mark v2.7.1 as deprecated in release notes
|
||||
2. Bump package.json to 2.7.2
|
||||
3. Create and push v2.7.2 tag
|
||||
4. Publish v2.7.2 release with correct artifacts
|
||||
5. Update download links/documentation to point to v2.7.2
|
||||
|
||||
**Pros:**
|
||||
- ✅ No disruption to existing v2.7.1 downloads
|
||||
- ✅ Preserves release history for audit trail
|
||||
- ✅ Clear indication that v2.7.2 supersedes v2.7.1
|
||||
|
||||
**Cons:**
|
||||
- ❌ Version number gap in release history (no "real" 2.7.1)
|
||||
- ❌ Confusing version progression for users
|
||||
- ❌ Requires updating all download links and documentation
|
||||
- ❌ Users may still download deprecated v2.7.1
|
||||
|
||||
**Risk Level:** Low - no deletion, but messy version history
|
||||
|
||||
---
|
||||
|
||||
##### Option C: Manual File Upload with --clobber
|
||||
|
||||
**Description:** Build correct v2.7.1 artifacts locally and upload to replace existing files.
|
||||
|
||||
**Steps:**
|
||||
1. Checkout commit with package.json version 2.7.1
|
||||
2. Build all platform artifacts locally (or trigger workflow to download)
|
||||
3. Delete existing assets: `gh release delete-asset v2.7.1 Auto-Claude-2.7.0-* --yes`
|
||||
4. Upload correct files: `gh release upload v2.7.1 ./dist/* --clobber`
|
||||
5. Update checksums file
|
||||
|
||||
**Pros:**
|
||||
- ✅ Keeps same release and tag
|
||||
- ✅ No temporary unavailability window
|
||||
|
||||
**Cons:**
|
||||
- ❌ Complex manual process prone to errors
|
||||
- ❌ Requires local build environment for all platforms (macOS, Windows, Linux)
|
||||
- ❌ May not match workflow-built artifacts exactly
|
||||
- ❌ Code signing could be different than CI
|
||||
- ❌ Does not address underlying tag/commit mismatch
|
||||
|
||||
**Risk Level:** High - manual process, potential signing issues
|
||||
|
||||
---
|
||||
|
||||
#### Recommendation
|
||||
|
||||
**Recommended Option: A - Recreate v2.7.1 Tag and Release**
|
||||
|
||||
**Rationale:**
|
||||
1. **Correctness**: The tag should point to a commit where the codebase reflects v2.7.1
|
||||
2. **Automation**: Letting the release workflow rebuild ensures identical CI artifacts
|
||||
3. **User Experience**: Users expect v2.7.1 to contain 2.7.1 code and files
|
||||
4. **Maintainability**: Clean version history is easier to manage long-term
|
||||
5. **Auto-updates**: Electron auto-updater relies on version matching
|
||||
|
||||
**Implementation Priority:**
|
||||
1. First: Fix v2.7.1 release (Option A)
|
||||
2. Then: Update workflow to prevent recurrence (make validation blocking)
|
||||
|
||||
---
|
||||
|
||||
#### Process Improvements Required
|
||||
|
||||
Regardless of fix option chosen, these changes should be implemented to prevent recurrence:
|
||||
|
||||
| Improvement | Priority | Description |
|
||||
|-------------|----------|-------------|
|
||||
| Make validation blocking | HIGH | Modify `release.yml` to depend on `validate-version.yml` passing |
|
||||
| Add pre-tag script | MEDIUM | Create script that validates version before allowing tag creation |
|
||||
| Use annotated tags | LOW | Annotated tags include metadata and require explicit message |
|
||||
| Document release procedure | MEDIUM | Create runbook for correct release process |
|
||||
|
||||
**Workflow Architecture Change:**
|
||||
```yaml
|
||||
# Before (parallel, independent):
|
||||
Tag Push → release.yml (runs)
|
||||
→ validate-version.yml (runs, but can't block)
|
||||
|
||||
# After (sequential, dependent):
|
||||
Tag Push → validate-version.yml (runs first)
|
||||
↓ success required
|
||||
→ release.yml (only runs if validation passes)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. ~~**Subtask 1-1:** Verify v2.7.1 assets~~ ✅ Complete
|
||||
2. ~~**Subtask 1-2:** Compare with v2.7.0 release and verify expected naming pattern~~ ✅ Complete
|
||||
3. ~~**Subtask 1-3:** Check package.json version and git state~~ ✅ Complete - ROOT CAUSE IDENTIFIED
|
||||
4. ~~**Subtask 2-1:** Inspect v2.7.1 git tag and commit~~ ✅ Complete - TAG/COMMIT MISMATCH CONFIRMED
|
||||
5. ~~**Subtask 2-2:** Check release workflow runs~~ ✅ Complete - VALIDATION DETECTED BUT COULDN'T STOP RELEASE
|
||||
6. ~~**Subtask 2-3:** Document fix options~~ ✅ Complete - 3 OPTIONS DOCUMENTED, OPTION A RECOMMENDED
|
||||
7. **Phase 3:** Implement fix (re-upload correct files or publish v2.7.2)
|
||||
8. **Phase 4:** Add validation to prevent future occurrences
|
||||
|
||||
---
|
||||
|
||||
## Status: Phase 2 Complete ✅
|
||||
|
||||
**Root Cause:** The v2.7.1 tag was created on commit `772a5006` which still had `package.json` version `2.7.0`. The validation workflow detected this but couldn't stop the release workflow.
|
||||
|
||||
**Key Findings from Workflow Analysis:**
|
||||
- Release workflow (ID: 20433472030): ✅ Success - correctly built from tagged commit
|
||||
- Validate Version workflow (ID: 20433472034): ❌ Failed - correctly detected version mismatch
|
||||
- The workflows run in parallel with no dependency relationship
|
||||
|
||||
**Recommended Fix:** Option A - Delete v2.7.1 tag and release, recreate tag at commit `8db71f3d` where `package.json` has version `2.7.1`, let workflow rebuild.
|
||||
|
||||
**Process Improvement Needed:**
|
||||
- Version bump should ALWAYS happen BEFORE tagging
|
||||
- **Make release.yml depend on validate-version.yml** using `needs:` or combine them
|
||||
- Consider using a reusable workflow or job dependency to enforce validation
|
||||
@@ -4,7 +4,7 @@ Your AI coding companion. Build features, fix bugs, and ship faster — with aut
|
||||
|
||||

|
||||
|
||||
[](https://discord.gg/maj9EWmY)
|
||||
[](https://discord.gg/KCXaPBr4Dj)
|
||||
|
||||
## What It Does ✨
|
||||
|
||||
@@ -24,88 +24,57 @@ Your AI coding companion. Build features, fix bugs, and ship faster — with aut
|
||||
- **Self-Validating**: Built-in QA loop catches issues before you review
|
||||
- **Isolated Workspaces**: All work happens in git worktrees — your code stays safe
|
||||
- **AI Merge Resolution**: Intelligent conflict resolution when merging back to main — no manual conflict fixing
|
||||
- **Memory Layer**: Agents remember insights across sessions for smarter decisions
|
||||
- **Cross-Platform**: Desktop app runs on Mac, Windows, and Linux
|
||||
- **Any Project Type**: Build web apps, APIs, CLIs — works with any software project
|
||||
|
||||
## 🚀 Quick Start (Desktop UI)
|
||||
## Quick Start
|
||||
|
||||
The Desktop UI is the recommended way to use Auto Claude. It provides visual task management, real-time progress tracking, and a Kanban board interface.
|
||||
### Download Auto Claude
|
||||
|
||||
Download the latest release for your platform from [GitHub Releases](https://github.com/AndyMik90/Auto-Claude/releases/latest):
|
||||
|
||||
| Platform | Download |
|
||||
|----------|----------|
|
||||
| **macOS (Apple Silicon M1-M4)** | `*-arm64.dmg` |
|
||||
| **macOS (Intel)** | `*-x64.dmg` |
|
||||
| **Windows** | `*.exe` |
|
||||
| **Linux** | `*.AppImage` or `*.deb` |
|
||||
|
||||
> **Not sure which Mac?** Click the Apple menu () > "About This Mac". Look for "Chip" - M1/M2/M3/M4 = Apple Silicon, otherwise Intel.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
1. **Node.js 18+** - [Download Node.js](https://nodejs.org/)
|
||||
2. **Python 3.9+** - [Download Python](https://www.python.org/downloads/)
|
||||
3. **Docker Desktop** - Required for the Memory Layer
|
||||
4. **Claude Code CLI** - `npm install -g @anthropic-ai/claude-code`
|
||||
5. **Claude Subscription** - Requires [Claude Pro or Max](https://claude.ai/upgrade) for Claude Code access
|
||||
Before using Auto Claude, you need:
|
||||
|
||||
---
|
||||
1. **Claude Subscription** - Requires [Claude Pro or Max](https://claude.ai/upgrade) for Claude Code access
|
||||
2. **Claude Code CLI** - Install with: `npm install -g @anthropic-ai/claude-code`
|
||||
|
||||
### Installing Docker Desktop
|
||||
### Install and Run
|
||||
|
||||
Docker runs the FalkorDB database that powers Auto Claude's cross-session memory.
|
||||
1. **Download** the installer for your platform from the table above
|
||||
2. **Install**:
|
||||
- **macOS**: Open the `.dmg`, drag Auto Claude to Applications
|
||||
- **Windows**: Run the `.exe` installer (see note below about security warning)
|
||||
- **Linux**: Make the AppImage executable (`chmod +x`) and run it, or install the `.deb`
|
||||
3. **Launch** Auto Claude
|
||||
4. **Add your project** and start building!
|
||||
|
||||
| Operating System | Download Link |
|
||||
|------------------|---------------|
|
||||
| **Mac (Apple Silicon M1/M2/M3/M4)** | [Download for Apple Chip](https://desktop.docker.com/mac/main/arm64/Docker.dmg) |
|
||||
| **Mac (Intel)** | [Download for Intel Chip](https://desktop.docker.com/mac/main/amd64/Docker.dmg) |
|
||||
| **Windows** | [Download for Windows](https://desktop.docker.com/win/main/amd64/Docker%20Desktop%20Installer.exe) |
|
||||
| **Linux** | [Installation Guide](https://docs.docker.com/desktop/install/linux-install/) |
|
||||
<details>
|
||||
<summary><b>Windows users:</b> Security warning when installing</summary>
|
||||
|
||||
> **Not sure which Mac?** Click the Apple menu (🍎) → "About This Mac". Look for "Chip" - M1/M2/M3/M4 = Apple Silicon, otherwise Intel.
|
||||
The Windows installer is not yet code-signed, so you may see a "Windows protected your PC" warning from Microsoft Defender SmartScreen.
|
||||
|
||||
**After installing:** Open Docker Desktop and wait for the whale icon (🐳) to appear in your menu bar/system tray.
|
||||
**To proceed:**
|
||||
1. Click "More info"
|
||||
2. Click "Run anyway"
|
||||
|
||||
> **Using the Desktop UI?** It automatically detects Docker status and offers one-click FalkorDB setup. No terminal commands needed!
|
||||
This is safe — all releases are automatically scanned with VirusTotal before publishing. You can verify any installer by checking the **VirusTotal Scan Results** section in each [release's notes](https://github.com/AndyMik90/Auto-Claude/releases).
|
||||
|
||||
📚 **For detailed installation steps, troubleshooting, and advanced configuration, see [guides/DOCKER-SETUP.md](guides/DOCKER-SETUP.md)**
|
||||
We're working on obtaining a code signing certificate for future releases.
|
||||
|
||||
---
|
||||
</details>
|
||||
|
||||
### Step 1: Set Up the Python Backend
|
||||
|
||||
The Desktop UI runs Python scripts behind the scenes. Set up the Python environment:
|
||||
|
||||
```bash
|
||||
cd auto-claude
|
||||
|
||||
# Using uv (recommended)
|
||||
uv venv && uv pip install -r requirements.txt
|
||||
|
||||
# Or using standard Python
|
||||
python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt
|
||||
```
|
||||
|
||||
### Step 2: Start the Memory Layer
|
||||
|
||||
The Auto Claude Memory Layer provides cross-session context retention using a graph database:
|
||||
|
||||
```bash
|
||||
# Make sure Docker Desktop is running, then:
|
||||
docker-compose up -d falkordb
|
||||
```
|
||||
|
||||
### Step 3: Install and Launch the Desktop UI
|
||||
|
||||
```bash
|
||||
cd auto-claude-ui
|
||||
|
||||
# Install dependencies (pnpm recommended, npm works too)
|
||||
pnpm install
|
||||
# or: npm install
|
||||
|
||||
# Build and start the application
|
||||
pnpm run build && pnpm run start
|
||||
# or: npm run build && npm run start
|
||||
```
|
||||
|
||||
### Step 4: Start Building
|
||||
|
||||
1. Add your project in the UI
|
||||
2. Create a new task describing what you want to build
|
||||
3. Watch as Auto Claude creates a spec, plans, and implements your feature
|
||||
4. Review changes and merge when satisfied
|
||||
> **Want to build from source?** See [CONTRIBUTING.md](CONTRIBUTING.md#running-from-source) for development setup.
|
||||
|
||||
---
|
||||
|
||||
@@ -215,22 +184,6 @@ Three-layer defense keeps your code safe:
|
||||
- **Filesystem Restrictions** — Operations limited to project directory
|
||||
- **Command Allowlist** — Only approved commands based on your project's stack
|
||||
|
||||
### 🧠 Memory Layer
|
||||
|
||||
The Memory Layer is a **hybrid RAG system** combining graph nodes with semantic search to deliver the best possible context during AI coding. Agents remember insights from previous sessions, discovered codebase patterns persist and are reusable, and historical context helps agents make smarter decisions.
|
||||
|
||||
**Architecture:**
|
||||
- **Backend**: FalkorDB (graph database) via Docker
|
||||
- **Library**: Graphiti for knowledge graph operations
|
||||
- **Providers**: OpenAI, Anthropic, Azure OpenAI, or Ollama (local/offline)
|
||||
|
||||
| Setup | LLM | Embeddings | Notes |
|
||||
|-------|-----|------------|-------|
|
||||
| **OpenAI** | OpenAI | OpenAI | Simplest - single API key |
|
||||
| **Anthropic + Voyage** | Anthropic | Voyage AI | High quality |
|
||||
| **Ollama** | Ollama | Ollama | Fully offline |
|
||||
| **Azure** | Azure OpenAI | Azure OpenAI | Enterprise |
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
@@ -246,11 +199,33 @@ your-project/
|
||||
│ ├── spec_runner.py # Spec creation orchestrator
|
||||
│ ├── prompts/ # Agent prompt templates
|
||||
│ └── ...
|
||||
├── auto-claude-ui/ # Electron desktop application
|
||||
│ └── ...
|
||||
└── docker-compose.yml # FalkorDB for Memory Layer
|
||||
└── auto-claude-ui/ # Electron desktop application
|
||||
└── ...
|
||||
```
|
||||
|
||||
### 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.
|
||||
@@ -259,12 +234,6 @@ your-project/
|
||||
|----------|----------|-------------|
|
||||
| `CLAUDE_CODE_OAUTH_TOKEN` | Yes | OAuth token from `claude setup-token` |
|
||||
| `AUTO_BUILD_MODEL` | No | Model override (default: claude-opus-4-5-20251101) |
|
||||
| `GRAPHITI_ENABLED` | Recommended | Set to `true` to enable Memory Layer |
|
||||
| `GRAPHITI_LLM_PROVIDER` | For Memory | LLM provider: openai, anthropic, azure_openai, ollama |
|
||||
| `GRAPHITI_EMBEDDER_PROVIDER` | For Memory | Embedder: openai, voyage, azure_openai, ollama |
|
||||
| `OPENAI_API_KEY` | For OpenAI | Required for OpenAI provider |
|
||||
| `ANTHROPIC_API_KEY` | For Anthropic | Required for Anthropic LLM |
|
||||
| `VOYAGE_API_KEY` | For Voyage | Required for Voyage embeddings |
|
||||
|
||||
See `auto-claude/.env.example` for complete configuration options.
|
||||
|
||||
@@ -272,7 +241,7 @@ See `auto-claude/.env.example` for complete configuration options.
|
||||
|
||||
Join our Discord to get help, share what you're building, and connect with other Auto Claude users:
|
||||
|
||||
[](https://discord.gg/maj9EWmY)
|
||||
[](https://discord.gg/KCXaPBr4Dj)
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
# Release Process
|
||||
|
||||
This document describes how to create a new release of Auto Claude.
|
||||
|
||||
## Automated Release Process (Recommended)
|
||||
|
||||
We provide an automated script that handles version bumping, git commits, and tagging to ensure version consistency.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Clean git working directory (no uncommitted changes)
|
||||
- You're on the branch you want to release from (usually `main`)
|
||||
|
||||
### Steps
|
||||
|
||||
1. **Run the version bump script:**
|
||||
|
||||
```bash
|
||||
# Bump patch version (2.5.5 -> 2.5.6)
|
||||
node scripts/bump-version.js patch
|
||||
|
||||
# Bump minor version (2.5.5 -> 2.6.0)
|
||||
node scripts/bump-version.js minor
|
||||
|
||||
# Bump major version (2.5.5 -> 3.0.0)
|
||||
node scripts/bump-version.js major
|
||||
|
||||
# Set specific version
|
||||
node scripts/bump-version.js 2.6.0
|
||||
```
|
||||
|
||||
This script will:
|
||||
- ✅ Update `auto-claude-ui/package.json` with the new version
|
||||
- ✅ Create a git commit with the version change
|
||||
- ✅ Create a git tag (e.g., `v2.5.6`)
|
||||
- ⚠️ **NOT** push to remote (you control when to push)
|
||||
|
||||
2. **Review the changes:**
|
||||
|
||||
```bash
|
||||
git log -1 # View the commit
|
||||
git show v2.5.6 # View the tag
|
||||
```
|
||||
|
||||
3. **Push to GitHub:**
|
||||
|
||||
```bash
|
||||
# Push the commit
|
||||
git push origin main
|
||||
|
||||
# Push the tag
|
||||
git push origin v2.5.6
|
||||
```
|
||||
|
||||
4. **Create GitHub Release:**
|
||||
|
||||
- Go to [GitHub Releases](https://github.com/AndyMik90/Auto-Claude/releases)
|
||||
- Click "Draft a new release"
|
||||
- Select the tag you just pushed (e.g., `v2.5.6`)
|
||||
- Add release notes (describe what changed)
|
||||
- Click "Publish release"
|
||||
|
||||
5. **Automated builds will trigger:**
|
||||
|
||||
- ✅ Version validation workflow will verify version consistency
|
||||
- ✅ Tests will run (`test-on-tag.yml`)
|
||||
- ✅ Native module prebuilds will be created (`build-prebuilds.yml`)
|
||||
- ✅ Discord notification will be sent (`discord-release.yml`)
|
||||
|
||||
## Manual Release Process (Not Recommended)
|
||||
|
||||
If you need to create a release manually, follow these steps **carefully** to avoid version mismatches:
|
||||
|
||||
1. **Update `auto-claude-ui/package.json`:**
|
||||
|
||||
```json
|
||||
{
|
||||
"version": "2.5.6"
|
||||
}
|
||||
```
|
||||
|
||||
2. **Commit the change:**
|
||||
|
||||
```bash
|
||||
git add auto-claude-ui/package.json
|
||||
git commit -m "chore: bump version to 2.5.6"
|
||||
```
|
||||
|
||||
3. **Create and push tag:**
|
||||
|
||||
```bash
|
||||
git tag -a v2.5.6 -m "Release v2.5.6"
|
||||
git push origin main
|
||||
git push origin v2.5.6
|
||||
```
|
||||
|
||||
4. **Create GitHub Release** (same as step 4 above)
|
||||
|
||||
## Version Validation
|
||||
|
||||
A GitHub Action automatically validates that the version in `package.json` matches the git tag.
|
||||
|
||||
If there's a mismatch, the workflow will **fail** with a clear error message:
|
||||
|
||||
```
|
||||
❌ ERROR: Version mismatch detected!
|
||||
|
||||
The version in package.json (2.5.0) does not match
|
||||
the git tag version (2.5.5).
|
||||
|
||||
To fix this:
|
||||
1. Delete this tag: git tag -d v2.5.5
|
||||
2. Update package.json version to 2.5.5
|
||||
3. Commit the change
|
||||
4. Recreate the tag: git tag -a v2.5.5 -m 'Release v2.5.5'
|
||||
```
|
||||
|
||||
This validation ensures we never ship a release where the updater shows the wrong version.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Version Mismatch Error
|
||||
|
||||
If you see a version mismatch error in GitHub Actions:
|
||||
|
||||
1. **Delete the incorrect tag:**
|
||||
```bash
|
||||
git tag -d v2.5.6 # Delete locally
|
||||
git push origin :refs/tags/v2.5.6 # Delete remotely
|
||||
```
|
||||
|
||||
2. **Use the automated script:**
|
||||
```bash
|
||||
node scripts/bump-version.js 2.5.6
|
||||
git push origin main
|
||||
git push origin v2.5.6
|
||||
```
|
||||
|
||||
### Git Working Directory Not Clean
|
||||
|
||||
If the version bump script fails with "Git working directory is not clean":
|
||||
|
||||
```bash
|
||||
# Commit or stash your changes first
|
||||
git status
|
||||
git add .
|
||||
git commit -m "your changes"
|
||||
|
||||
# Then run the version bump script
|
||||
node scripts/bump-version.js patch
|
||||
```
|
||||
|
||||
## Release Checklist
|
||||
|
||||
Use this checklist when creating a new release:
|
||||
|
||||
- [ ] All tests passing on main branch
|
||||
- [ ] CHANGELOG updated (if applicable)
|
||||
- [ ] Run `node scripts/bump-version.js <type>`
|
||||
- [ ] Review commit and tag
|
||||
- [ ] Push commit and tag to GitHub
|
||||
- [ ] Create GitHub Release with release notes
|
||||
- [ ] Verify version validation passed
|
||||
- [ ] Verify builds completed successfully
|
||||
- [ ] Test the updater shows correct version
|
||||
|
||||
## What Gets Released
|
||||
|
||||
When you create a release, the following are built and published:
|
||||
|
||||
1. **Native module prebuilds** - Windows node-pty binaries
|
||||
2. **Electron app packages** - Desktop installers (triggered manually or via electron-builder)
|
||||
3. **Discord notification** - Sent to the Auto Claude community
|
||||
|
||||
## Version Numbering
|
||||
|
||||
We follow [Semantic Versioning (SemVer)](https://semver.org/):
|
||||
|
||||
- **MAJOR** version (X.0.0) - Breaking changes
|
||||
- **MINOR** version (0.X.0) - New features (backward compatible)
|
||||
- **PATCH** version (0.0.X) - Bug fixes (backward compatible)
|
||||
|
||||
Examples:
|
||||
- `2.5.5 -> 2.5.6` - Bug fix
|
||||
- `2.5.6 -> 2.6.0` - New feature
|
||||
- `2.6.0 -> 3.0.0` - Breaking change
|
||||
+1
-1
@@ -658,4 +658,4 @@ specific requirements.
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# Auto Claude UI Environment Variables
|
||||
# Copy this file to .env and set your values
|
||||
|
||||
# ============================================
|
||||
# DEBUG SETTINGS
|
||||
# ============================================
|
||||
|
||||
# Enable debug logging across the entire application
|
||||
# When enabled, you'll see detailed console logs for:
|
||||
# - Ideation and roadmap generation
|
||||
# - IPC communication between processes
|
||||
# - Store state updates
|
||||
# - Changelog generation and project initialization
|
||||
# - GitHub OAuth flow
|
||||
# Usage: Set to 'true' before starting the app
|
||||
# DEBUG=true
|
||||
|
||||
# Enable debug logging for the auto-updater only
|
||||
# Shows detailed information about app update checks and downloads
|
||||
# DEBUG_UPDATER=true
|
||||
|
||||
# ============================================
|
||||
# HOW TO USE
|
||||
# ============================================
|
||||
|
||||
# Option 1: Set in your shell before starting the app
|
||||
# DEBUG=true npm start
|
||||
#
|
||||
# Option 2: Export in your shell profile (~/.bashrc, ~/.zshrc, etc.)
|
||||
# export DEBUG=true
|
||||
#
|
||||
# Option 3: Create a .env file in this directory (auto-claude-ui/)
|
||||
# Copy this file: cp .env.example .env
|
||||
# Then uncomment and set the variables you need
|
||||
#
|
||||
# Note: The Electron app will read these from process.env
|
||||
# The Python backend (auto-claude) has its own .env file
|
||||
|
||||
# ============================================
|
||||
# DEVELOPMENT
|
||||
# ============================================
|
||||
|
||||
# Node environment (automatically set by npm scripts)
|
||||
# NODE_ENV=development
|
||||
+108
-139
@@ -2,161 +2,130 @@
|
||||
|
||||
A desktop application for managing AI-driven development tasks using the Auto Claude autonomous coding framework.
|
||||
|
||||
## Overview
|
||||
## Quick Start
|
||||
|
||||
Auto Claude UI provides a visual Kanban board interface for creating, monitoring, and managing auto-claude tasks. It replaces the terminal-based workflow with an intuitive GUI while preserving all CLI functionality.
|
||||
```bash
|
||||
# 1. Clone the repo (if you haven't already)
|
||||
git clone https://github.com/AndyMik90/Auto-Claude.git
|
||||
cd Auto-Claude/auto-claude-ui
|
||||
|
||||
# 2. Install dependencies
|
||||
npm install
|
||||
|
||||
# 3. Build the desktop app
|
||||
npm run package:win # Windows
|
||||
npm run package:mac # macOS
|
||||
npm run package:linux # Linux
|
||||
|
||||
# 4. Run the app
|
||||
# Windows: .\dist\win-unpacked\Auto Claude.exe
|
||||
# macOS: open dist/mac-arm64/Auto\ Claude.app
|
||||
# Linux: ./dist/linux-unpacked/auto-claude
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 18+
|
||||
- npm or pnpm
|
||||
- Python 3.10+ (for auto-claude backend)
|
||||
- **Windows only**: Visual Studio Build Tools 2022 with "Desktop development with C++" workload
|
||||
- **Windows only**: Developer Mode enabled (Settings → System → For developers)
|
||||
|
||||
## How to Run
|
||||
|
||||
### Building for Production (Recommended)
|
||||
|
||||
Build the Electron desktop app for your platform:
|
||||
|
||||
```bash
|
||||
# Build for Windows
|
||||
npm run package:win
|
||||
|
||||
# Build for macOS
|
||||
npm run package:mac
|
||||
|
||||
# Build for Linux
|
||||
npm run package:linux
|
||||
```
|
||||
|
||||
### Running the Production Build
|
||||
|
||||
After building, run the application from the `dist` folder:
|
||||
|
||||
```bash
|
||||
# Windows - run the executable
|
||||
.\dist\win-unpacked\Auto Claude.exe
|
||||
|
||||
# Windows - or use the installer
|
||||
.\dist\Auto Claude Setup X.X.X.exe
|
||||
|
||||
# macOS
|
||||
open dist/mac-arm64/Auto\ Claude.app
|
||||
|
||||
# Linux
|
||||
./dist/linux-unpacked/auto-claude
|
||||
```
|
||||
|
||||
### Development Mode
|
||||
|
||||
For development with hot reload (optional):
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
> **Note**: Some features like auto-updates only work in packaged builds.
|
||||
|
||||
## Distribution Files
|
||||
|
||||
After packaging, the `dist` folder contains:
|
||||
|
||||
| Platform | Files |
|
||||
|----------|-------|
|
||||
| macOS | `Auto Claude.app`, `.dmg`, `.zip` |
|
||||
| Windows | `Auto Claude Setup X.X.X.exe` (installer), `.zip`, `win-unpacked/` |
|
||||
| Linux | `.AppImage`, `.deb`, `linux-unpacked/` |
|
||||
|
||||
## Testing
|
||||
|
||||
```bash
|
||||
# Run tests
|
||||
npm run test
|
||||
```
|
||||
|
||||
## Linting
|
||||
|
||||
```bash
|
||||
# Run ESLint
|
||||
npm run lint
|
||||
|
||||
# Run type checking
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- **Project Management**: Add, configure, and switch between multiple projects
|
||||
- **Kanban Board**: Visual task board with columns for Backlog, In Progress, AI Review, Human Review, and Done
|
||||
- **Task Creation Wizard**: Form-based interface for creating new tasks
|
||||
- **Real-Time Progress**: Live updates from implementation_plan.json during agent execution
|
||||
- **Real-Time Progress**: Live updates during agent execution
|
||||
- **Human Review Workflow**: Review QA results and provide feedback
|
||||
- **Theme Support**: Light and dark mode with system preference detection
|
||||
- **Settings**: Per-project and app-wide configuration options
|
||||
- **Theme Support**: Light and dark mode
|
||||
- **Auto Updates**: Automatic update notifications
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Framework**: Electron with React 18 (TypeScript)
|
||||
- **Build Tool**: electron-vite with electron-builder
|
||||
- **UI Components**: Radix UI primitives (shadcn/ui pattern)
|
||||
- **Styling**: TailwindCSS with dark mode support
|
||||
- **Framework**: Electron + React 18 (TypeScript)
|
||||
- **Build Tool**: electron-vite + electron-builder
|
||||
- **UI Components**: Radix UI (shadcn/ui pattern)
|
||||
- **Styling**: TailwindCSS
|
||||
- **State Management**: Zustand
|
||||
- **File Watching**: chokidar
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
auto-claude-ui/
|
||||
├── src/
|
||||
│ ├── main/ # Electron main process
|
||||
│ │ ├── index.ts # App entry point
|
||||
│ │ ├── agent-manager.ts # Python subprocess management
|
||||
│ │ ├── file-watcher.ts # Implementation plan watching
|
||||
│ │ ├── ipc-handlers.ts # IPC message handlers
|
||||
│ │ └── project-store.ts # JSON project persistence
|
||||
│ ├── preload/ # Preload scripts
|
||||
│ │ └── index.ts # Secure contextBridge API
|
||||
│ ├── renderer/ # React application
|
||||
│ │ ├── components/ # React components
|
||||
│ │ │ ├── ui/ # Wrapped Radix UI components
|
||||
│ │ │ ├── Sidebar.tsx
|
||||
│ │ │ ├── KanbanBoard.tsx
|
||||
│ │ │ ├── TaskCard.tsx
|
||||
│ │ │ ├── TaskDetailPanel.tsx
|
||||
│ │ │ ├── TaskCreationWizard.tsx
|
||||
│ │ │ ├── ProjectSettings.tsx
|
||||
│ │ │ └── AppSettings.tsx
|
||||
│ │ ├── stores/ # Zustand state stores
|
||||
│ │ ├── hooks/ # Custom React hooks
|
||||
│ │ ├── styles/ # Global CSS
|
||||
│ │ └── App.tsx # Root component
|
||||
│ └── shared/ # Shared code
|
||||
│ ├── types.ts # TypeScript interfaces
|
||||
│ └── constants.ts # Constants and IPC channels
|
||||
├── electron.vite.config.ts # Build configuration
|
||||
├── package.json
|
||||
├── tsconfig.json
|
||||
├── tailwind.config.js
|
||||
└── postcss.config.js
|
||||
```
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 18+
|
||||
- npm or pnpm
|
||||
- Python 3.10+ (for auto-claude backend)
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Navigate to auto-claude-ui directory
|
||||
cd auto-claude-ui
|
||||
|
||||
# Install dependencies
|
||||
npm install
|
||||
```
|
||||
|
||||
### Development
|
||||
|
||||
```bash
|
||||
# Start development server with hot reload
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```bash
|
||||
# Build for production
|
||||
npm run build
|
||||
|
||||
# Package for macOS
|
||||
npm run package:mac
|
||||
|
||||
# Package for Windows
|
||||
npm run package:win
|
||||
|
||||
# Package for Linux
|
||||
npm run package:linux
|
||||
```
|
||||
|
||||
### Type Checking
|
||||
|
||||
```bash
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
### Linting
|
||||
|
||||
```bash
|
||||
npm run lint
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
```bash
|
||||
npm run test
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Main Process
|
||||
|
||||
The main process handles:
|
||||
- Window management
|
||||
- Python subprocess spawning (agent-manager.ts)
|
||||
- File system watching (file-watcher.ts)
|
||||
- Project data persistence (project-store.ts)
|
||||
- IPC communication with renderer
|
||||
|
||||
### Preload Script
|
||||
|
||||
Provides a secure bridge between main and renderer processes using Electron's contextBridge. All IPC channels are explicitly defined and typed.
|
||||
|
||||
### Renderer Process
|
||||
|
||||
A React application with:
|
||||
- Zustand stores for state management
|
||||
- Custom hooks for IPC event handling
|
||||
- Radix UI components wrapped in the shadcn/ui pattern
|
||||
- TailwindCSS for styling
|
||||
|
||||
## Security
|
||||
|
||||
The application follows Electron security best practices:
|
||||
- `contextIsolation: true`
|
||||
- `nodeIntegration: false`
|
||||
- Minimal API surface via contextBridge
|
||||
- No direct ipcRenderer exposure
|
||||
|
||||
## Environment Variables
|
||||
|
||||
- `CLAUDE_CODE_OAUTH_TOKEN`: OAuth token for Claude Code SDK (from auto-claude/.env)
|
||||
- `FALKORDB_URL`: FalkorDB connection URL (optional, defaults to localhost:6379)
|
||||
- `FALKORDB_URL`: FalkorDB connection URL (optional)
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
AGPL-3.0
|
||||
|
||||
+60
-60
@@ -63,10 +63,10 @@
|
||||
"id": "default",
|
||||
"name": "Default",
|
||||
"description": "Oscura Midnight - deepest dark with saturated yellow accent, inspired by Fey/Oscura",
|
||||
"previewColors": {
|
||||
"lightBg": "#F2F2ED",
|
||||
"previewColors": {
|
||||
"lightBg": "#F2F2ED",
|
||||
"lightAccent": "#A5A66A",
|
||||
"darkBg": "#0B0B0F",
|
||||
"darkBg": "#0B0B0F",
|
||||
"darkAccent": "#D6D876"
|
||||
},
|
||||
"semanticColors": {
|
||||
@@ -81,10 +81,10 @@
|
||||
"id": "dusk",
|
||||
"name": "Dusk",
|
||||
"description": "Warmer Oscura variant with slightly lighter dark mode",
|
||||
"previewColors": {
|
||||
"lightBg": "#F5F5F0",
|
||||
"previewColors": {
|
||||
"lightBg": "#F5F5F0",
|
||||
"lightAccent": "#B8B978",
|
||||
"darkBg": "#131419",
|
||||
"darkBg": "#131419",
|
||||
"darkAccent": "#E6E7A3"
|
||||
},
|
||||
"semanticColors": {
|
||||
@@ -99,50 +99,50 @@
|
||||
"id": "lime",
|
||||
"name": "Lime",
|
||||
"description": "Fresh, energetic lime/chartreuse with purple accents",
|
||||
"previewColors": {
|
||||
"lightBg": "#E8F5A3",
|
||||
"darkBg": "#0F0F1A",
|
||||
"accent": "#7C3AED"
|
||||
"previewColors": {
|
||||
"lightBg": "#E8F5A3",
|
||||
"darkBg": "#0F0F1A",
|
||||
"accent": "#7C3AED"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ocean",
|
||||
"name": "Ocean",
|
||||
"name": "Ocean",
|
||||
"description": "Calm, professional blue tones",
|
||||
"previewColors": {
|
||||
"lightBg": "#E0F2FE",
|
||||
"darkBg": "#082F49",
|
||||
"accent": "#0284C7"
|
||||
"previewColors": {
|
||||
"lightBg": "#E0F2FE",
|
||||
"darkBg": "#082F49",
|
||||
"accent": "#0284C7"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "retro",
|
||||
"name": "Retro",
|
||||
"description": "Warm, nostalgic amber/orange vibes",
|
||||
"previewColors": {
|
||||
"lightBg": "#FEF3C7",
|
||||
"darkBg": "#1C1917",
|
||||
"accent": "#D97706"
|
||||
"previewColors": {
|
||||
"lightBg": "#FEF3C7",
|
||||
"darkBg": "#1C1917",
|
||||
"accent": "#D97706"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "neo",
|
||||
"name": "Neo",
|
||||
"description": "Modern cyberpunk pink/magenta",
|
||||
"previewColors": {
|
||||
"lightBg": "#FDF4FF",
|
||||
"darkBg": "#0F0720",
|
||||
"accent": "#D946EF"
|
||||
"previewColors": {
|
||||
"lightBg": "#FDF4FF",
|
||||
"darkBg": "#0F0720",
|
||||
"accent": "#D946EF"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "forest",
|
||||
"name": "Forest",
|
||||
"description": "Natural, earthy green tones",
|
||||
"previewColors": {
|
||||
"lightBg": "#DCFCE7",
|
||||
"darkBg": "#052E16",
|
||||
"accent": "#16A34A"
|
||||
"previewColors": {
|
||||
"lightBg": "#DCFCE7",
|
||||
"darkBg": "#052E16",
|
||||
"accent": "#16A34A"
|
||||
}
|
||||
}
|
||||
],
|
||||
@@ -152,7 +152,7 @@
|
||||
"colors": {
|
||||
"note": "These are the Default theme colors (Oscura Midnight). See themeSystem for all available themes.",
|
||||
"cssVariablePrefix": "--color-",
|
||||
|
||||
|
||||
"lightMode": {
|
||||
"background": {
|
||||
"primary": "#F2F2ED",
|
||||
@@ -186,7 +186,7 @@
|
||||
"focus": "#A5A66A"
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
"darkMode": {
|
||||
"background": {
|
||||
"primary": "#0B0B0F",
|
||||
@@ -223,7 +223,7 @@
|
||||
"focus": "#D6D876"
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
"semantic": {
|
||||
"success": "#4EBE96",
|
||||
"successLight": { "light": "#E0F5ED", "dark": "#1A2924" },
|
||||
@@ -238,7 +238,7 @@
|
||||
"infoLight": { "light": "#E8F4FF", "dark": "#1A2230" },
|
||||
"infoDescription": "Blue - for links and informational elements"
|
||||
},
|
||||
|
||||
|
||||
"shadows": {
|
||||
"lightMode": {
|
||||
"sm": "0 1px 2px 0 rgba(0, 0, 0, 0.05)",
|
||||
@@ -511,30 +511,30 @@
|
||||
"fontWeight": "500"
|
||||
},
|
||||
"variants": {
|
||||
"default": {
|
||||
"background": "var(--color-background-secondary)",
|
||||
"text": "var(--color-text-secondary)"
|
||||
"default": {
|
||||
"background": "var(--color-background-secondary)",
|
||||
"text": "var(--color-text-secondary)"
|
||||
},
|
||||
"primary": {
|
||||
"background": "var(--color-accent-primary-light)",
|
||||
"text": "var(--color-accent-primary)"
|
||||
"primary": {
|
||||
"background": "var(--color-accent-primary-light)",
|
||||
"text": "var(--color-accent-primary)"
|
||||
},
|
||||
"success": {
|
||||
"background": "var(--color-semantic-success-light)",
|
||||
"text": "var(--color-semantic-success)"
|
||||
"success": {
|
||||
"background": "var(--color-semantic-success-light)",
|
||||
"text": "var(--color-semantic-success)"
|
||||
},
|
||||
"warning": {
|
||||
"background": "var(--color-semantic-warning-light)",
|
||||
"text": "var(--color-semantic-warning)"
|
||||
"warning": {
|
||||
"background": "var(--color-semantic-warning-light)",
|
||||
"text": "var(--color-semantic-warning)"
|
||||
},
|
||||
"error": {
|
||||
"background": "var(--color-semantic-error-light)",
|
||||
"text": "var(--color-semantic-error)"
|
||||
"error": {
|
||||
"background": "var(--color-semantic-error-light)",
|
||||
"text": "var(--color-semantic-error)"
|
||||
},
|
||||
"outline": {
|
||||
"background": "transparent",
|
||||
"border": "1px solid var(--color-border-default)",
|
||||
"text": "var(--color-text-secondary)"
|
||||
"outline": {
|
||||
"background": "transparent",
|
||||
"border": "1px solid var(--color-border-default)",
|
||||
"text": "var(--color-text-secondary)"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -616,10 +616,10 @@
|
||||
"description": "Date picker grid with clear day cells and selection states.",
|
||||
"styling": {
|
||||
"dayCell": { "size": "36px", "borderRadius": "md (8px)" },
|
||||
"selectedDay": {
|
||||
"background": "var(--color-accent-primary)",
|
||||
"text": "var(--color-text-inverse)",
|
||||
"borderRadius": "full"
|
||||
"selectedDay": {
|
||||
"background": "var(--color-accent-primary)",
|
||||
"text": "var(--color-text-inverse)",
|
||||
"borderRadius": "full"
|
||||
},
|
||||
"todayIndicator": "var(--color-accent-primary) text color or dot",
|
||||
"rangeSelection": "var(--color-accent-primary-light) background for range days"
|
||||
@@ -634,14 +634,14 @@
|
||||
"thumbSize": "20px"
|
||||
},
|
||||
"styling": {
|
||||
"off": {
|
||||
"track": "var(--color-border-default)",
|
||||
"off": {
|
||||
"track": "var(--color-border-default)",
|
||||
"lightTrack": "#DEDED9",
|
||||
"darkTrack": "#232323",
|
||||
"thumb": "white"
|
||||
"thumb": "white"
|
||||
},
|
||||
"on": {
|
||||
"track": "var(--color-accent-primary)",
|
||||
"on": {
|
||||
"track": "var(--color-accent-primary)",
|
||||
"lightTrack": "#A5A66A",
|
||||
"darkTrack": "#D6D876",
|
||||
"thumb": "var(--color-text-inverse)",
|
||||
@@ -895,7 +895,7 @@
|
||||
"cssVariableMap": {
|
||||
"backgrounds": [
|
||||
"--color-background-primary",
|
||||
"--color-background-secondary",
|
||||
"--color-background-secondary",
|
||||
"--color-background-neutral"
|
||||
],
|
||||
"surfaces": [
|
||||
|
||||
@@ -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,14 +5,22 @@ import { resolve } from 'path';
|
||||
export default defineConfig({
|
||||
main: {
|
||||
plugins: [externalizeDepsPlugin({
|
||||
exclude: []
|
||||
// Bundle these packages into the main process (they won't be in node_modules in packaged app)
|
||||
exclude: [
|
||||
'uuid',
|
||||
'chokidar',
|
||||
'kuzu',
|
||||
'electron-updater',
|
||||
'@electron-toolkit/utils'
|
||||
]
|
||||
})],
|
||||
build: {
|
||||
rollupOptions: {
|
||||
input: {
|
||||
index: resolve(__dirname, 'src/main/index.ts')
|
||||
},
|
||||
external: ['node-pty']
|
||||
// Only node-pty needs to be external (native module rebuilt by electron-builder)
|
||||
external: ['@lydell/node-pty']
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -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
+1880
-183
File diff suppressed because it is too large
Load Diff
+68
-15
@@ -1,22 +1,32 @@
|
||||
{
|
||||
"name": "auto-claude-ui",
|
||||
"version": "2.3.0",
|
||||
"version": "2.7.1",
|
||||
"description": "Desktop UI for Auto Claude autonomous coding framework",
|
||||
"homepage": "https://github.com/AndyMik90/Auto-Claude",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/AndyMik90/Auto-Claude.git"
|
||||
},
|
||||
"main": "./out/main/index.js",
|
||||
"author": "Auto Claude Team",
|
||||
"author": {
|
||||
"name": "Auto Claude Team",
|
||||
"email": "119136210+AndyMik90@users.noreply.github.com"
|
||||
},
|
||||
"license": "AGPL-3.0",
|
||||
"scripts": {
|
||||
"postinstall": "electron-rebuild",
|
||||
"postinstall": "node scripts/postinstall.js",
|
||||
"dev": "electron-vite dev",
|
||||
"dev:mcp": "electron-vite dev -- --remote-debugging-port=9222",
|
||||
"build": "electron-vite build",
|
||||
"start": "electron .",
|
||||
"start:mcp": "electron . --remote-debugging-port=9222",
|
||||
"preview": "electron-vite preview",
|
||||
"package": "electron-vite build && electron-builder",
|
||||
"package:mac": "electron-vite build && electron-builder --mac",
|
||||
"package:win": "electron-vite build && electron-builder --win",
|
||||
"package:linux": "electron-vite build && electron-builder --linux",
|
||||
"start:packaged:mac": "open dist/mac-arm64/Auto\\ Claude.app || open dist/mac/Auto\\ Claude.app",
|
||||
"start:packaged:win": "start \"\" \"dist\\win-unpacked\\Auto Claude.exe\"",
|
||||
"start:packaged:mac": "open dist/mac-arm64/Auto-Claude.app || open dist/mac/Auto-Claude.app",
|
||||
"start:packaged:win": "start \"\" \"dist\\win-unpacked\\Auto-Claude.exe\"",
|
||||
"start:packaged:linux": "./dist/linux-unpacked/auto-claude",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
@@ -30,6 +40,7 @@
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@lydell/node-pty": "^1.1.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.15",
|
||||
"@radix-ui/react-checkbox": "^1.1.4",
|
||||
"@radix-ui/react-collapsible": "^1.1.3",
|
||||
@@ -55,10 +66,9 @@
|
||||
"chokidar": "^5.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"ioredis": "^5.8.2",
|
||||
"electron-updater": "^6.6.2",
|
||||
"lucide-react": "^0.560.0",
|
||||
"motion": "^12.23.26",
|
||||
"node-pty": "^1.0.0",
|
||||
"react": "^19.2.3",
|
||||
"react-dom": "^19.2.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
@@ -76,7 +86,6 @@
|
||||
"@playwright/test": "^1.52.0",
|
||||
"@tailwindcss/postcss": "^4.1.17",
|
||||
"@testing-library/react": "^16.1.0",
|
||||
"@types/ioredis": "^4.28.10",
|
||||
"@types/node": "^25.0.0",
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
@@ -103,34 +112,77 @@
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"electron-builder-squirrel-windows": "^26.0.12",
|
||||
"dmg-builder": "^26.0.12"
|
||||
"dmg-builder": "^26.0.12",
|
||||
"node-pty": "npm:@lydell/node-pty@^1.1.0"
|
||||
},
|
||||
"onlyBuiltDependencies": [
|
||||
"@lydell/node-pty",
|
||||
"electron",
|
||||
"esbuild",
|
||||
"node-pty"
|
||||
"electron-winstaller",
|
||||
"esbuild"
|
||||
]
|
||||
},
|
||||
"build": {
|
||||
"appId": "com.autoclaude.ui",
|
||||
"productName": "Auto Claude",
|
||||
"productName": "Auto-Claude",
|
||||
"artifactName": "${productName}-${version}-${platform}-${arch}.${ext}",
|
||||
"publish": [
|
||||
{
|
||||
"provider": "github",
|
||||
"owner": "AndyMik90",
|
||||
"repo": "Auto-Claude"
|
||||
}
|
||||
],
|
||||
"directories": {
|
||||
"output": "dist",
|
||||
"buildResources": "resources"
|
||||
},
|
||||
"files": [
|
||||
"out/**/*"
|
||||
"out/**/*",
|
||||
"package.json"
|
||||
],
|
||||
"extraResources": [
|
||||
{
|
||||
"from": "node_modules/@lydell/node-pty",
|
||||
"to": "node_modules/@lydell/node-pty"
|
||||
},
|
||||
{
|
||||
"from": "resources/icon.ico",
|
||||
"to": "icon.ico"
|
||||
},
|
||||
{
|
||||
"from": "../auto-claude",
|
||||
"to": "auto-claude",
|
||||
"filter": [
|
||||
"!**/.git",
|
||||
"!**/__pycache__",
|
||||
"!**/*.pyc",
|
||||
"!**/specs",
|
||||
"!**/.venv",
|
||||
"!**/.venv-*",
|
||||
"!**/venv",
|
||||
"!**/.env",
|
||||
"!**/tests",
|
||||
"!**/*.egg-info",
|
||||
"!**/.pytest_cache",
|
||||
"!**/.mypy_cache"
|
||||
]
|
||||
}
|
||||
],
|
||||
"mac": {
|
||||
"category": "public.app-category.developer-tools",
|
||||
"icon": "resources/icon.icns",
|
||||
"hardenedRuntime": true,
|
||||
"gatekeeperAssess": false,
|
||||
"entitlements": "resources/entitlements.mac.plist",
|
||||
"entitlementsInherit": "resources/entitlements.mac.plist",
|
||||
"target": [
|
||||
"dmg",
|
||||
"zip"
|
||||
]
|
||||
},
|
||||
"win": {
|
||||
"icon": "resources/icon-256.png",
|
||||
"icon": "resources/icon.ico",
|
||||
"target": [
|
||||
"nsis",
|
||||
"zip"
|
||||
@@ -149,5 +201,6 @@
|
||||
"*.{ts,tsx}": [
|
||||
"eslint --fix"
|
||||
]
|
||||
}
|
||||
},
|
||||
"packageManager": "pnpm@10.26.1+sha512.664074abc367d2c9324fdc18037097ce0a8f126034160f709928e9e9f95d98714347044e5c3164d65bd5da6c59c6be362b107546292a8eecb7999196e5ce58fa"
|
||||
}
|
||||
|
||||
Generated
+675
-407
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- Allow the app to be debugged -->
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<!-- Allow loading unsigned libraries (needed for native modules) -->
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
<!-- Allow dyld environment variables (needed for Electron) -->
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
<!-- Allow spawning child processes (needed for Python backend and terminals) -->
|
||||
<key>com.apple.security.cs.allow-dyld-environment-variables</key>
|
||||
<true/>
|
||||
<!-- Network access for API calls -->
|
||||
<key>com.apple.security.network.client</key>
|
||||
<true/>
|
||||
<!-- File access for user documents -->
|
||||
<key>com.apple.security.files.user-selected.read-write</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 74 KiB |
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Download prebuilt native modules for Windows
|
||||
*
|
||||
* This script downloads pre-compiled node-pty binaries from GitHub releases,
|
||||
* eliminating the need for Visual Studio Build Tools on Windows.
|
||||
*/
|
||||
|
||||
const https = require('https');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { execSync } = require('child_process');
|
||||
|
||||
const GITHUB_REPO = 'AndyMik90/Auto-Claude';
|
||||
const GITHUB_API = 'https://api.github.com';
|
||||
|
||||
/**
|
||||
* Get the Electron ABI version for the installed Electron
|
||||
*/
|
||||
function getElectronAbi() {
|
||||
try {
|
||||
// Try to get from electron-abi package
|
||||
const result = execSync('npx electron-abi', {
|
||||
encoding: 'utf8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
}).trim();
|
||||
return result;
|
||||
} catch {
|
||||
// Fallback: read from electron package
|
||||
try {
|
||||
const electronPkg = require('electron/package.json');
|
||||
const version = electronPkg.version;
|
||||
// Electron 39.x = ABI 140
|
||||
const majorVersion = parseInt(version.split('.')[0], 10);
|
||||
// This is a rough mapping, electron-abi is more accurate
|
||||
const abiMap = {
|
||||
39: 140,
|
||||
38: 139,
|
||||
37: 136,
|
||||
36: 135,
|
||||
35: 134,
|
||||
34: 132,
|
||||
33: 131,
|
||||
32: 130,
|
||||
31: 129,
|
||||
30: 128,
|
||||
};
|
||||
return abiMap[majorVersion] || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the latest release from GitHub
|
||||
*/
|
||||
function getLatestRelease() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const options = {
|
||||
hostname: 'api.github.com',
|
||||
path: `/repos/${GITHUB_REPO}/releases/latest`,
|
||||
headers: {
|
||||
'User-Agent': 'Auto-Claude-Installer',
|
||||
Accept: 'application/vnd.github.v3+json',
|
||||
},
|
||||
};
|
||||
|
||||
https
|
||||
.get(options, (res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => (data += chunk));
|
||||
res.on('end', () => {
|
||||
if (res.statusCode === 200) {
|
||||
resolve(JSON.parse(data));
|
||||
} else if (res.statusCode === 404) {
|
||||
resolve(null); // No releases yet
|
||||
} else {
|
||||
reject(new Error(`GitHub API returned ${res.statusCode}`));
|
||||
}
|
||||
});
|
||||
})
|
||||
.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Find prebuild asset in release
|
||||
*/
|
||||
function findPrebuildAsset(release, arch, electronAbi) {
|
||||
if (!release || !release.assets) return null;
|
||||
|
||||
const assetName = `node-pty-win32-${arch}-electron-${electronAbi}.zip`;
|
||||
return release.assets.find((asset) => asset.name === assetName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a file from URL
|
||||
*/
|
||||
function downloadFile(url, destPath) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const file = fs.createWriteStream(destPath);
|
||||
|
||||
const request = (url) => {
|
||||
https
|
||||
.get(url, { headers: { 'User-Agent': 'Auto-Claude-Installer' } }, (res) => {
|
||||
if (res.statusCode === 302 || res.statusCode === 301) {
|
||||
// Follow redirect
|
||||
request(res.headers.location);
|
||||
return;
|
||||
}
|
||||
|
||||
if (res.statusCode !== 200) {
|
||||
reject(new Error(`Download failed with status ${res.statusCode}`));
|
||||
return;
|
||||
}
|
||||
|
||||
res.pipe(file);
|
||||
file.on('finish', () => {
|
||||
file.close();
|
||||
resolve();
|
||||
});
|
||||
})
|
||||
.on('error', (err) => {
|
||||
fs.unlink(destPath, () => {}); // Delete partial file
|
||||
reject(err);
|
||||
});
|
||||
};
|
||||
|
||||
request(url);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract zip file (using built-in tools)
|
||||
*/
|
||||
function extractZip(zipPath, destDir) {
|
||||
const { execSync } = require('child_process');
|
||||
|
||||
// Use PowerShell on Windows
|
||||
execSync(`powershell -Command "Expand-Archive -Path '${zipPath}' -DestinationPath '${destDir}' -Force"`, {
|
||||
stdio: 'inherit',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function to download and install prebuilds
|
||||
*/
|
||||
async function downloadPrebuilds() {
|
||||
const arch = process.arch; // x64 or arm64
|
||||
const electronAbi = getElectronAbi();
|
||||
|
||||
if (!electronAbi) {
|
||||
console.log('[prebuilds] Could not determine Electron ABI version');
|
||||
return { success: false, reason: 'unknown-abi' };
|
||||
}
|
||||
|
||||
console.log(`[prebuilds] Looking for prebuilds: win32-${arch}, Electron ABI ${electronAbi}`);
|
||||
|
||||
// Check for prebuilds in GitHub releases
|
||||
let release;
|
||||
try {
|
||||
release = await getLatestRelease();
|
||||
} catch (err) {
|
||||
console.log(`[prebuilds] Could not fetch releases: ${err.message}`);
|
||||
return { success: false, reason: 'fetch-failed' };
|
||||
}
|
||||
|
||||
if (!release) {
|
||||
console.log('[prebuilds] No releases found');
|
||||
return { success: false, reason: 'no-releases' };
|
||||
}
|
||||
|
||||
const asset = findPrebuildAsset(release, arch, electronAbi);
|
||||
if (!asset) {
|
||||
console.log(`[prebuilds] No prebuild found for win32-${arch}-electron-${electronAbi}`);
|
||||
console.log('[prebuilds] Available assets:', release.assets?.map((a) => a.name).join(', ') || 'none');
|
||||
return { success: false, reason: 'no-matching-prebuild' };
|
||||
}
|
||||
|
||||
console.log(`[prebuilds] Found prebuild: ${asset.name}`);
|
||||
|
||||
// Download the prebuild
|
||||
const tempDir = path.join(__dirname, '..', '.prebuild-temp');
|
||||
const zipPath = path.join(tempDir, asset.name);
|
||||
const nodePtyDir = path.join(__dirname, '..', 'node_modules', 'node-pty');
|
||||
const buildDir = path.join(nodePtyDir, 'build', 'Release');
|
||||
|
||||
try {
|
||||
// Create temp directory
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
console.log(`[prebuilds] Downloading ${asset.name}...`);
|
||||
await downloadFile(asset.browser_download_url, zipPath);
|
||||
|
||||
console.log('[prebuilds] Extracting...');
|
||||
extractZip(zipPath, tempDir);
|
||||
|
||||
// Find the extracted prebuild directory
|
||||
const extractedDir = path.join(tempDir, 'prebuilds', `win32-${arch}-electron-${electronAbi}`);
|
||||
|
||||
if (!fs.existsSync(extractedDir)) {
|
||||
throw new Error(`Extracted directory not found: ${extractedDir}`);
|
||||
}
|
||||
|
||||
// Ensure build/Release directory exists
|
||||
fs.mkdirSync(buildDir, { recursive: true });
|
||||
|
||||
// Copy files to node_modules/node-pty/build/Release
|
||||
const files = fs.readdirSync(extractedDir);
|
||||
for (const file of files) {
|
||||
const src = path.join(extractedDir, file);
|
||||
const dest = path.join(buildDir, file);
|
||||
fs.copyFileSync(src, dest);
|
||||
console.log(`[prebuilds] Installed: ${file}`);
|
||||
}
|
||||
|
||||
// Cleanup temp directory
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
|
||||
console.log('[prebuilds] Successfully installed prebuilt binaries!');
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
// Cleanup on error
|
||||
if (fs.existsSync(tempDir)) {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
console.log(`[prebuilds] Download/extract failed: ${err.message}`);
|
||||
return { success: false, reason: 'install-failed', error: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
// Export for use by postinstall
|
||||
module.exports = { downloadPrebuilds, getElectronAbi };
|
||||
|
||||
// Run if called directly
|
||||
if (require.main === module) {
|
||||
downloadPrebuilds()
|
||||
.then((result) => {
|
||||
if (!result.success) {
|
||||
process.exit(1);
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('[prebuilds] Error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Post-install script for Auto Claude UI
|
||||
*
|
||||
* On Windows:
|
||||
* 1. Try to download prebuilt node-pty binaries from GitHub releases
|
||||
* 2. Fall back to electron-rebuild if prebuilds aren't available
|
||||
* 3. Show helpful error message if compilation fails
|
||||
*
|
||||
* On macOS/Linux:
|
||||
* 1. Run electron-rebuild (compilers are typically available)
|
||||
*/
|
||||
|
||||
const { spawn } = require('child_process');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const isWindows = os.platform() === 'win32';
|
||||
|
||||
const WINDOWS_BUILD_TOOLS_HELP = `
|
||||
================================================================================
|
||||
VISUAL STUDIO BUILD TOOLS REQUIRED
|
||||
================================================================================
|
||||
|
||||
Prebuilt binaries weren't available for your Electron version, and compilation
|
||||
requires Visual Studio Build Tools.
|
||||
|
||||
To install:
|
||||
|
||||
1. Download Visual Studio Build Tools 2022:
|
||||
https://visualstudio.microsoft.com/visual-cpp-build-tools/
|
||||
|
||||
2. Run installer and select:
|
||||
- "Desktop development with C++" workload
|
||||
|
||||
3. In "Individual Components", also select:
|
||||
- "MSVC v143 - VS 2022 C++ x64/x86 Spectre-mitigated libs"
|
||||
|
||||
4. Restart your terminal and run: npm install
|
||||
|
||||
================================================================================
|
||||
`;
|
||||
|
||||
/**
|
||||
* Run electron-rebuild
|
||||
*/
|
||||
function runElectronRebuild() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const npx = isWindows ? 'npx.cmd' : 'npx';
|
||||
const child = spawn(npx, ['electron-rebuild'], {
|
||||
stdio: 'inherit',
|
||||
shell: isWindows,
|
||||
cwd: path.join(__dirname, '..'),
|
||||
});
|
||||
|
||||
child.on('close', (code) => {
|
||||
if (code === 0) {
|
||||
resolve({ success: true });
|
||||
} else {
|
||||
reject(new Error(`electron-rebuild exited with code ${code}`));
|
||||
}
|
||||
});
|
||||
|
||||
child.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if node-pty is already built
|
||||
*/
|
||||
function isNodePtyBuilt() {
|
||||
const buildDir = path.join(__dirname, '..', 'node_modules', 'node-pty', 'build', 'Release');
|
||||
if (!fs.existsSync(buildDir)) return false;
|
||||
|
||||
// Check for the main .node file
|
||||
const files = fs.readdirSync(buildDir);
|
||||
return files.some((f) => f.endsWith('.node'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Main postinstall logic
|
||||
*/
|
||||
async function main() {
|
||||
console.log('[postinstall] Setting up native modules for Electron...\n');
|
||||
|
||||
// If node-pty is already built (e.g., from a previous successful install), skip
|
||||
if (isNodePtyBuilt()) {
|
||||
console.log('[postinstall] Native modules already built, skipping rebuild.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (isWindows) {
|
||||
// On Windows, try prebuilds first
|
||||
console.log('[postinstall] Windows detected - checking for prebuilt binaries...\n');
|
||||
|
||||
try {
|
||||
// Dynamic import to handle case where the script doesn't exist yet
|
||||
const { downloadPrebuilds } = require('./download-prebuilds.js');
|
||||
const result = await downloadPrebuilds();
|
||||
|
||||
if (result.success) {
|
||||
console.log('\n[postinstall] Successfully installed prebuilt binaries!');
|
||||
console.log('[postinstall] No Visual Studio Build Tools required.\n');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`\n[postinstall] Prebuilds not available (${result.reason})`);
|
||||
console.log('[postinstall] Falling back to electron-rebuild...\n');
|
||||
} catch (err) {
|
||||
console.log('[postinstall] Could not check for prebuilds:', err.message);
|
||||
console.log('[postinstall] Falling back to electron-rebuild...\n');
|
||||
}
|
||||
}
|
||||
|
||||
// Run electron-rebuild
|
||||
try {
|
||||
console.log('[postinstall] Running electron-rebuild...\n');
|
||||
await runElectronRebuild();
|
||||
console.log('\n[postinstall] Native modules built successfully!');
|
||||
} catch (error) {
|
||||
console.error('\n[postinstall] Failed to build native modules.\n');
|
||||
|
||||
if (isWindows) {
|
||||
console.error(WINDOWS_BUILD_TOOLS_HELP);
|
||||
} else {
|
||||
console.error('Error:', error.message);
|
||||
console.error('\nYou may need to install build tools for your platform:');
|
||||
console.error(' macOS: xcode-select --install');
|
||||
console.error(' Linux: sudo apt-get install build-essential\n');
|
||||
}
|
||||
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('[postinstall] Unexpected error:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -3,7 +3,6 @@
|
||||
* Tests IPC messages flow between main and renderer
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
// Mock ipcRenderer for renderer-side tests
|
||||
const mockIpcRenderer = {
|
||||
@@ -285,7 +284,8 @@ describe('IPC Bridge Integration', () => {
|
||||
const getAppVersion = electronAPI['getAppVersion'] as () => Promise<unknown>;
|
||||
await getAppVersion();
|
||||
|
||||
expect(mockIpcRenderer.invoke).toHaveBeenCalledWith('app:version');
|
||||
// getAppVersion now uses the app-update channel (from AppUpdateAPI which is spread last)
|
||||
expect(mockIpcRenderer.invoke).toHaveBeenCalledWith('app-update:get-version');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,11 +6,16 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { mkdirSync, rmSync, existsSync, writeFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { findPythonCommand, parsePythonCommand } from '../../main/python-detector';
|
||||
|
||||
// Test directories
|
||||
const TEST_DIR = '/tmp/subprocess-spawn-test';
|
||||
const TEST_PROJECT_PATH = path.join(TEST_DIR, 'test-project');
|
||||
|
||||
// Detect the Python command that will actually be used
|
||||
const DETECTED_PYTHON_CMD = findPythonCommand() || 'python';
|
||||
const [EXPECTED_PYTHON_COMMAND, EXPECTED_PYTHON_BASE_ARGS] = parsePythonCommand(DETECTED_PYTHON_CMD);
|
||||
|
||||
// Mock child_process spawn
|
||||
const mockStdout = new EventEmitter();
|
||||
const mockStderr = new EventEmitter();
|
||||
@@ -29,6 +34,14 @@ vi.mock('child_process', () => ({
|
||||
spawn: vi.fn(() => mockProcess)
|
||||
}));
|
||||
|
||||
// Mock claude-profile-manager to bypass auth checks in tests
|
||||
vi.mock('../../main/claude-profile-manager', () => ({
|
||||
getClaudeProfileManager: () => ({
|
||||
hasValidAuth: () => true,
|
||||
getActiveProfile: () => ({ profileId: 'default', profileName: 'Default' })
|
||||
})
|
||||
}));
|
||||
|
||||
// Auto-claude source path (for getAutoBuildSourcePath to find)
|
||||
const AUTO_CLAUDE_SOURCE = path.join(TEST_DIR, 'auto-claude-source');
|
||||
|
||||
@@ -39,8 +52,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 });
|
||||
@@ -91,8 +104,9 @@ describe('Subprocess Spawn Integration', () => {
|
||||
manager.startSpecCreation('task-1', TEST_PROJECT_PATH, 'Test task description');
|
||||
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'python3',
|
||||
EXPECTED_PYTHON_COMMAND,
|
||||
expect.arrayContaining([
|
||||
...EXPECTED_PYTHON_BASE_ARGS,
|
||||
expect.stringContaining('spec_runner.py'),
|
||||
'--task',
|
||||
'Test task description'
|
||||
@@ -115,8 +129,13 @@ describe('Subprocess Spawn Integration', () => {
|
||||
manager.startTaskExecution('task-1', TEST_PROJECT_PATH, 'spec-001');
|
||||
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'python3',
|
||||
expect.arrayContaining([expect.stringContaining('run.py'), '--spec', 'spec-001']),
|
||||
EXPECTED_PYTHON_COMMAND,
|
||||
expect.arrayContaining([
|
||||
...EXPECTED_PYTHON_BASE_ARGS,
|
||||
expect.stringContaining('run.py'),
|
||||
'--spec',
|
||||
'spec-001'
|
||||
]),
|
||||
expect.objectContaining({
|
||||
cwd: AUTO_CLAUDE_SOURCE // Process runs from auto-claude source directory
|
||||
})
|
||||
@@ -132,8 +151,9 @@ describe('Subprocess Spawn Integration', () => {
|
||||
manager.startQAProcess('task-1', TEST_PROJECT_PATH, 'spec-001');
|
||||
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'python3',
|
||||
EXPECTED_PYTHON_COMMAND,
|
||||
expect.arrayContaining([
|
||||
...EXPECTED_PYTHON_BASE_ARGS,
|
||||
expect.stringContaining('run.py'),
|
||||
'--spec',
|
||||
'spec-001',
|
||||
@@ -159,8 +179,13 @@ describe('Subprocess Spawn Integration', () => {
|
||||
|
||||
// Should spawn normally - parallel options don't affect CLI args anymore
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'python3',
|
||||
expect.arrayContaining([expect.stringContaining('run.py'), '--spec', 'spec-001']),
|
||||
EXPECTED_PYTHON_COMMAND,
|
||||
expect.arrayContaining([
|
||||
...EXPECTED_PYTHON_BASE_ARGS,
|
||||
expect.stringContaining('run.py'),
|
||||
'--spec',
|
||||
'spec-001'
|
||||
]),
|
||||
expect.any(Object)
|
||||
);
|
||||
});
|
||||
|
||||
@@ -5,14 +5,40 @@ import { vi, beforeEach, afterEach } from 'vitest';
|
||||
import { mkdirSync, rmSync, existsSync } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
// Mock localStorage for tests that need it
|
||||
const localStorageMock = (() => {
|
||||
let store: Record<string, string> = {};
|
||||
|
||||
return {
|
||||
getItem: vi.fn((key: string) => store[key] || null),
|
||||
setItem: vi.fn((key: string, value: string) => {
|
||||
store[key] = value;
|
||||
}),
|
||||
removeItem: vi.fn((key: string) => {
|
||||
delete store[key];
|
||||
}),
|
||||
clear: vi.fn(() => {
|
||||
store = {};
|
||||
})
|
||||
};
|
||||
})();
|
||||
|
||||
// Make localStorage available globally
|
||||
Object.defineProperty(global, 'localStorage', {
|
||||
value: localStorageMock
|
||||
});
|
||||
|
||||
// Test data directory for isolated file operations
|
||||
export const TEST_DATA_DIR = '/tmp/auto-claude-ui-tests';
|
||||
|
||||
// Create fresh test directory before each test
|
||||
beforeEach(() => {
|
||||
// Clear localStorage
|
||||
localStorageMock.clear();
|
||||
|
||||
// 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)) {
|
||||
@@ -56,7 +82,13 @@ if (typeof window !== 'undefined') {
|
||||
getSettings: vi.fn(),
|
||||
saveSettings: vi.fn(),
|
||||
selectDirectory: vi.fn(),
|
||||
getAppVersion: vi.fn()
|
||||
getAppVersion: vi.fn(),
|
||||
// Tab state persistence (IPC-based)
|
||||
getTabState: vi.fn().mockResolvedValue({
|
||||
success: true,
|
||||
data: { openProjectIds: [], activeProjectId: null, tabOrder: [] }
|
||||
}),
|
||||
saveTabState: vi.fn().mockResolvedValue({ success: true })
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,42 @@ 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 version-manager to return a predictable version
|
||||
vi.mock('../updater/version-manager', () => ({
|
||||
getEffectiveVersion: vi.fn(() => '0.1.0'),
|
||||
getBundledVersion: vi.fn(() => '0.1.0'),
|
||||
parseVersionFromTag: vi.fn((tag: string) => tag.replace('v', '')),
|
||||
compareVersions: vi.fn(() => 0)
|
||||
}));
|
||||
|
||||
// Mock modules before importing
|
||||
vi.mock('electron', () => {
|
||||
const mockIpcMain = new (class extends EventEmitter {
|
||||
|
||||
@@ -1,463 +0,0 @@
|
||||
/**
|
||||
* Unit tests for IPC handlers
|
||||
* Tests all IPC communication patterns between main and renderer processes
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { mkdirSync, writeFileSync, rmSync, existsSync } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
// Test data directory
|
||||
const TEST_DIR = '/tmp/ipc-handlers-test';
|
||||
const TEST_PROJECT_PATH = path.join(TEST_DIR, 'test-project');
|
||||
|
||||
// Mock modules before importing
|
||||
vi.mock('electron', () => {
|
||||
const mockIpcMain = new (class extends EventEmitter {
|
||||
private handlers: Map<string, Function> = new Map();
|
||||
|
||||
handle(channel: string, handler: Function): void {
|
||||
this.handlers.set(channel, handler);
|
||||
}
|
||||
|
||||
removeHandler(channel: string): void {
|
||||
this.handlers.delete(channel);
|
||||
}
|
||||
|
||||
async invokeHandler(channel: string, event: unknown, ...args: unknown[]): Promise<unknown> {
|
||||
const handler = this.handlers.get(channel);
|
||||
if (handler) {
|
||||
return handler(event, ...args);
|
||||
}
|
||||
throw new Error(`No handler for channel: ${channel}`);
|
||||
}
|
||||
|
||||
getHandler(channel: string): Function | undefined {
|
||||
return this.handlers.get(channel);
|
||||
}
|
||||
})();
|
||||
|
||||
return {
|
||||
app: {
|
||||
getPath: vi.fn((name: string) => {
|
||||
if (name === 'userData') return path.join(TEST_DIR, 'userData');
|
||||
return TEST_DIR;
|
||||
}),
|
||||
getVersion: vi.fn(() => '0.1.0'),
|
||||
isPackaged: false
|
||||
},
|
||||
ipcMain: mockIpcMain,
|
||||
dialog: {
|
||||
showOpenDialog: vi.fn(() => Promise.resolve({ canceled: false, filePaths: [TEST_PROJECT_PATH] }))
|
||||
},
|
||||
BrowserWindow: class {
|
||||
webContents = { send: vi.fn() };
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
// Setup test project structure
|
||||
function setupTestProject(): void {
|
||||
mkdirSync(TEST_PROJECT_PATH, { recursive: true });
|
||||
mkdirSync(path.join(TEST_PROJECT_PATH, 'auto-claude', 'specs'), { recursive: true });
|
||||
}
|
||||
|
||||
// Cleanup test directories
|
||||
function cleanupTestDirs(): void {
|
||||
if (existsSync(TEST_DIR)) {
|
||||
rmSync(TEST_DIR, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
describe('IPC Handlers', () => {
|
||||
let ipcMain: EventEmitter & {
|
||||
handlers: Map<string, Function>;
|
||||
invokeHandler: (channel: string, event: unknown, ...args: unknown[]) => Promise<unknown>;
|
||||
getHandler: (channel: string) => Function | undefined;
|
||||
};
|
||||
let mockMainWindow: { webContents: { send: ReturnType<typeof vi.fn> } };
|
||||
let mockAgentManager: EventEmitter & {
|
||||
startSpecCreation: ReturnType<typeof vi.fn>;
|
||||
startTaskExecution: ReturnType<typeof vi.fn>;
|
||||
startQAProcess: ReturnType<typeof vi.fn>;
|
||||
killTask: ReturnType<typeof vi.fn>;
|
||||
configure: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let mockTerminalManager: {
|
||||
create: ReturnType<typeof vi.fn>;
|
||||
destroy: ReturnType<typeof vi.fn>;
|
||||
write: ReturnType<typeof vi.fn>;
|
||||
resize: ReturnType<typeof vi.fn>;
|
||||
invokeClaude: ReturnType<typeof vi.fn>;
|
||||
killAll: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
cleanupTestDirs();
|
||||
setupTestProject();
|
||||
mkdirSync(path.join(TEST_DIR, 'userData', 'store'), { recursive: true });
|
||||
|
||||
// Get mocked ipcMain
|
||||
const electron = await import('electron');
|
||||
ipcMain = electron.ipcMain as unknown as typeof ipcMain;
|
||||
|
||||
// Create mock window
|
||||
mockMainWindow = {
|
||||
webContents: { send: vi.fn() }
|
||||
};
|
||||
|
||||
// Create mock agent manager
|
||||
mockAgentManager = Object.assign(new EventEmitter(), {
|
||||
startSpecCreation: vi.fn(),
|
||||
startTaskExecution: vi.fn(),
|
||||
startQAProcess: vi.fn(),
|
||||
killTask: vi.fn(),
|
||||
configure: vi.fn()
|
||||
});
|
||||
|
||||
// Create mock terminal manager
|
||||
mockTerminalManager = {
|
||||
create: vi.fn(() => Promise.resolve({ success: true })),
|
||||
destroy: vi.fn(() => Promise.resolve({ success: true })),
|
||||
write: vi.fn(),
|
||||
resize: vi.fn(),
|
||||
invokeClaude: vi.fn(),
|
||||
killAll: vi.fn(() => Promise.resolve())
|
||||
};
|
||||
|
||||
// Need to reset modules to re-register handlers
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDirs();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('project:add handler', () => {
|
||||
it('should return error for non-existent path', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler('project:add', {}, '/nonexistent/path');
|
||||
|
||||
expect(result).toEqual({
|
||||
success: false,
|
||||
error: 'Directory does not exist'
|
||||
});
|
||||
});
|
||||
|
||||
it('should successfully add an existing project', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
expect(result).toHaveProperty('data');
|
||||
const data = (result as { data: { path: string; name: string } }).data;
|
||||
expect(data.path).toBe(TEST_PROJECT_PATH);
|
||||
expect(data.name).toBe('test-project');
|
||||
});
|
||||
|
||||
it('should return existing project if already added', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add project twice
|
||||
const result1 = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
const result2 = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
|
||||
const data1 = (result1 as { data: { id: string } }).data;
|
||||
const data2 = (result2 as { data: { id: string } }).data;
|
||||
expect(data1.id).toBe(data2.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('project:list handler', () => {
|
||||
it('should return empty array when no projects', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler('project:list', {});
|
||||
|
||||
expect(result).toEqual({
|
||||
success: true,
|
||||
data: []
|
||||
});
|
||||
});
|
||||
|
||||
it('should return all added projects', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add a project
|
||||
await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
|
||||
const result = await ipcMain.invokeHandler('project:list', {});
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: unknown[] }).data;
|
||||
expect(data).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('project:remove handler', () => {
|
||||
it('should return false for non-existent project', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler('project:remove', {}, 'nonexistent-id');
|
||||
|
||||
expect(result).toEqual({ success: false });
|
||||
});
|
||||
|
||||
it('should successfully remove an existing project', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add a project first
|
||||
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
const projectId = (addResult as { data: { id: string } }).data.id;
|
||||
|
||||
// Remove it
|
||||
const removeResult = await ipcMain.invokeHandler('project:remove', {}, projectId);
|
||||
|
||||
expect(removeResult).toEqual({ success: true });
|
||||
|
||||
// Verify it's gone
|
||||
const listResult = await ipcMain.invokeHandler('project:list', {});
|
||||
const data = (listResult as { data: unknown[] }).data;
|
||||
expect(data).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('project:updateSettings handler', () => {
|
||||
it('should return error for non-existent project', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler(
|
||||
'project:updateSettings',
|
||||
{},
|
||||
'nonexistent-id',
|
||||
{ parallelEnabled: true }
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
success: false,
|
||||
error: 'Project not found'
|
||||
});
|
||||
});
|
||||
|
||||
it('should successfully update project settings', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add a project first
|
||||
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
const projectId = (addResult as { data: { id: string } }).data.id;
|
||||
|
||||
// Update settings
|
||||
const result = await ipcMain.invokeHandler(
|
||||
'project:updateSettings',
|
||||
{},
|
||||
projectId,
|
||||
{ parallelEnabled: true, maxWorkers: 4 }
|
||||
);
|
||||
|
||||
expect(result).toEqual({ success: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('task:list handler', () => {
|
||||
it('should return empty array for project with no specs', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add a project first
|
||||
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
const projectId = (addResult as { data: { id: string } }).data.id;
|
||||
|
||||
const result = await ipcMain.invokeHandler('task:list', {}, projectId);
|
||||
|
||||
expect(result).toEqual({
|
||||
success: true,
|
||||
data: []
|
||||
});
|
||||
});
|
||||
|
||||
it('should return tasks when specs exist', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add a project first
|
||||
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
const projectId = (addResult as { data: { id: string } }).data.id;
|
||||
|
||||
// Create a spec directory with implementation plan
|
||||
const specDir = path.join(TEST_PROJECT_PATH, 'auto-claude', 'specs', '001-test-feature');
|
||||
mkdirSync(specDir, { recursive: true });
|
||||
writeFileSync(path.join(specDir, 'implementation_plan.json'), JSON.stringify({
|
||||
feature: 'Test Feature',
|
||||
workflow_type: 'feature',
|
||||
services_involved: [],
|
||||
phases: [{
|
||||
phase: 1,
|
||||
name: 'Test Phase',
|
||||
type: 'implementation',
|
||||
subtasks: [{ id: 'subtask-1', description: 'Test subtask', status: 'pending' }]
|
||||
}],
|
||||
final_acceptance: [],
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
spec_file: ''
|
||||
}));
|
||||
|
||||
const result = await ipcMain.invokeHandler('task:list', {}, projectId);
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: unknown[] }).data;
|
||||
expect(data).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('task:create handler', () => {
|
||||
it('should return error for non-existent project', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler(
|
||||
'task:create',
|
||||
{},
|
||||
'nonexistent-id',
|
||||
'Test Task',
|
||||
'Test description'
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
success: false,
|
||||
error: 'Project not found'
|
||||
});
|
||||
});
|
||||
|
||||
it('should create task and start spec creation', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
// Add a project first
|
||||
const addResult = await ipcMain.invokeHandler('project:add', {}, TEST_PROJECT_PATH);
|
||||
const projectId = (addResult as { data: { id: string } }).data.id;
|
||||
|
||||
const result = await ipcMain.invokeHandler(
|
||||
'task:create',
|
||||
{},
|
||||
projectId,
|
||||
'Test Task',
|
||||
'Test description'
|
||||
);
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
expect(mockAgentManager.startSpecCreation).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('settings:get handler', () => {
|
||||
it('should return default settings when no settings file exists', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler('settings:get', {});
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { theme: string } }).data;
|
||||
expect(data).toHaveProperty('theme', 'system');
|
||||
});
|
||||
});
|
||||
|
||||
describe('settings:save handler', () => {
|
||||
it('should save settings successfully', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler(
|
||||
'settings:save',
|
||||
{},
|
||||
{ theme: 'dark', defaultModel: 'opus' }
|
||||
);
|
||||
|
||||
expect(result).toEqual({ success: true });
|
||||
|
||||
// Verify settings were saved
|
||||
const getResult = await ipcMain.invokeHandler('settings:get', {});
|
||||
const data = (getResult as { data: { theme: string; defaultModel: string } }).data;
|
||||
expect(data.theme).toBe('dark');
|
||||
expect(data.defaultModel).toBe('opus');
|
||||
});
|
||||
|
||||
it('should configure agent manager when paths change', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
await ipcMain.invokeHandler(
|
||||
'settings:save',
|
||||
{},
|
||||
{ pythonPath: '/usr/bin/python3' }
|
||||
);
|
||||
|
||||
expect(mockAgentManager.configure).toHaveBeenCalledWith('/usr/bin/python3', undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('app:version handler', () => {
|
||||
it('should return app version', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
const result = await ipcMain.invokeHandler('app:version', {});
|
||||
|
||||
expect(result).toBe('0.1.0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Agent Manager event forwarding', () => {
|
||||
it('should forward log events to renderer', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
mockAgentManager.emit('log', 'task-1', 'Test log message');
|
||||
|
||||
expect(mockMainWindow.webContents.send).toHaveBeenCalledWith(
|
||||
'task:log',
|
||||
'task-1',
|
||||
'Test log message'
|
||||
);
|
||||
});
|
||||
|
||||
it('should forward error events to renderer', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
mockAgentManager.emit('error', 'task-1', 'Test error message');
|
||||
|
||||
expect(mockMainWindow.webContents.send).toHaveBeenCalledWith(
|
||||
'task:error',
|
||||
'task-1',
|
||||
'Test error message'
|
||||
);
|
||||
});
|
||||
|
||||
it('should forward exit events with status change', async () => {
|
||||
const { setupIpcHandlers } = await import('../ipc-handlers');
|
||||
setupIpcHandlers(mockAgentManager as never, mockTerminalManager as never, () => mockMainWindow as never);
|
||||
|
||||
mockAgentManager.emit('exit', 'task-1', 0);
|
||||
|
||||
expect(mockMainWindow.webContents.send).toHaveBeenCalledWith(
|
||||
'task:statusChange',
|
||||
'task-1',
|
||||
'ai_review'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,605 @@
|
||||
/**
|
||||
* Integration tests for Rate Limit Auto-Recovery System
|
||||
* Tests the complete flow: rate limit detection → account swap → task restart
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
// Mock data
|
||||
const mockProfiles = {
|
||||
mai: {
|
||||
id: 'profile-mai',
|
||||
name: 'MAI',
|
||||
email: 'mai@example.com',
|
||||
isDefault: true,
|
||||
oauthToken: 'encrypted-token-mai',
|
||||
createdAt: new Date(),
|
||||
rateLimitEvents: []
|
||||
},
|
||||
mu: {
|
||||
id: 'profile-mu',
|
||||
name: 'MU',
|
||||
email: 'mu@example.com',
|
||||
isDefault: false,
|
||||
oauthToken: 'encrypted-token-mu',
|
||||
createdAt: new Date(),
|
||||
rateLimitEvents: []
|
||||
}
|
||||
};
|
||||
|
||||
const mockAutoSwitchSettings = {
|
||||
enabled: true,
|
||||
proactiveSwapEnabled: true,
|
||||
sessionThreshold: 95,
|
||||
weeklyThreshold: 99,
|
||||
autoSwitchOnRateLimit: true,
|
||||
usageCheckInterval: 30000
|
||||
};
|
||||
|
||||
// Create mock profile manager
|
||||
function createMockProfileManager(options: {
|
||||
activeProfileId?: string;
|
||||
profiles?: typeof mockProfiles;
|
||||
autoSwitchSettings?: typeof mockAutoSwitchSettings;
|
||||
bestAvailableProfile?: typeof mockProfiles.mai | null;
|
||||
} = {}) {
|
||||
const activeId = options.activeProfileId || 'profile-mai';
|
||||
const profiles = options.profiles || mockProfiles;
|
||||
const settings = options.autoSwitchSettings || mockAutoSwitchSettings;
|
||||
const bestProfile = options.bestAvailableProfile !== undefined
|
||||
? options.bestAvailableProfile
|
||||
: profiles.mu;
|
||||
|
||||
return {
|
||||
getActiveProfile: vi.fn(() => profiles[activeId === 'profile-mai' ? 'mai' : 'mu']),
|
||||
getProfile: vi.fn((id: string) => {
|
||||
if (id === 'profile-mai') return profiles.mai;
|
||||
if (id === 'profile-mu') return profiles.mu;
|
||||
return null;
|
||||
}),
|
||||
getBestAvailableProfile: vi.fn((_excludeProfileId?: string) => bestProfile),
|
||||
setActiveProfile: vi.fn(),
|
||||
recordRateLimitEvent: vi.fn(),
|
||||
getAutoSwitchSettings: vi.fn(() => settings),
|
||||
getProfileToken: vi.fn(() => 'decrypted-token'),
|
||||
getActiveProfileToken: vi.fn(() => 'decrypted-token')
|
||||
};
|
||||
}
|
||||
|
||||
describe('Rate Limit Auto-Recovery Integration', () => {
|
||||
let mockProfileManager: ReturnType<typeof createMockProfileManager>;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
mockProfileManager = createMockProfileManager();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Rate Limit Detection Patterns', () => {
|
||||
beforeEach(() => {
|
||||
vi.doMock('../claude-profile-manager', () => ({
|
||||
getClaudeProfileManager: vi.fn(() => mockProfileManager)
|
||||
}));
|
||||
});
|
||||
|
||||
it('should detect standard Claude rate limit message', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Limit reached · resets Dec 17 at 6am (Europe/Oslo)';
|
||||
const result = detectRateLimit(output);
|
||||
|
||||
expect(result.isRateLimited).toBe(true);
|
||||
expect(result.resetTime).toBe('Dec 17 at 6am (Europe/Oslo)');
|
||||
expect(result.limitType).toBe('weekly');
|
||||
});
|
||||
|
||||
it('should detect session limit (time only reset)', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Limit reached • resets 11:59pm';
|
||||
const result = detectRateLimit(output);
|
||||
|
||||
expect(result.isRateLimited).toBe(true);
|
||||
expect(result.limitType).toBe('session');
|
||||
});
|
||||
|
||||
it('should detect rate limit in multiline output', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
const output = `Processing task...
|
||||
Some output here
|
||||
Limit reached · resets Dec 20 at 3pm (America/New_York)
|
||||
Stack trace follows`;
|
||||
|
||||
const result = detectRateLimit(output);
|
||||
|
||||
expect(result.isRateLimited).toBe(true);
|
||||
expect(result.resetTime).toBe('Dec 20 at 3pm (America/New_York)');
|
||||
});
|
||||
|
||||
it('should suggest alternative profile when rate limited', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Limit reached · resets Dec 17 at 6am';
|
||||
const result = detectRateLimit(output, 'profile-mai');
|
||||
|
||||
expect(result.isRateLimited).toBe(true);
|
||||
expect(result.suggestedProfile).toBeDefined();
|
||||
expect(result.suggestedProfile?.id).toBe('profile-mu');
|
||||
});
|
||||
|
||||
it('should record rate limit event in profile manager', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
detectRateLimit('Limit reached · resets Dec 17 at 6am', 'profile-mai');
|
||||
|
||||
expect(mockProfileManager.recordRateLimitEvent).toHaveBeenCalledWith(
|
||||
'profile-mai',
|
||||
'Dec 17 at 6am'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Auto-Switch Settings Verification', () => {
|
||||
it('should respect enabled flag', async () => {
|
||||
const disabledManager = createMockProfileManager({
|
||||
autoSwitchSettings: { ...mockAutoSwitchSettings, enabled: false }
|
||||
});
|
||||
|
||||
vi.doMock('../claude-profile-manager', () => ({
|
||||
getClaudeProfileManager: vi.fn(() => disabledManager)
|
||||
}));
|
||||
|
||||
const settings = disabledManager.getAutoSwitchSettings();
|
||||
|
||||
expect(settings.enabled).toBe(false);
|
||||
// When enabled is false, auto-swap should NOT happen even if autoSwitchOnRateLimit is true
|
||||
});
|
||||
|
||||
it('should respect autoSwitchOnRateLimit flag', async () => {
|
||||
const manualManager = createMockProfileManager({
|
||||
autoSwitchSettings: { ...mockAutoSwitchSettings, autoSwitchOnRateLimit: false }
|
||||
});
|
||||
|
||||
const settings = manualManager.getAutoSwitchSettings();
|
||||
|
||||
expect(settings.enabled).toBe(true);
|
||||
expect(settings.autoSwitchOnRateLimit).toBe(false);
|
||||
// When autoSwitchOnRateLimit is false, should show manual modal instead
|
||||
});
|
||||
|
||||
it('should have both enabled and autoSwitchOnRateLimit for auto-recovery', () => {
|
||||
const settings = mockProfileManager.getAutoSwitchSettings();
|
||||
|
||||
// Both must be true for automatic recovery
|
||||
const shouldAutoRecover = settings.enabled && settings.autoSwitchOnRateLimit;
|
||||
expect(shouldAutoRecover).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Profile Scoring and Selection', () => {
|
||||
it('should return alternative profile when one is available', () => {
|
||||
const bestProfile = mockProfileManager.getBestAvailableProfile('profile-mai');
|
||||
|
||||
expect(bestProfile).toBeDefined();
|
||||
expect(bestProfile?.id).toBe('profile-mu');
|
||||
});
|
||||
|
||||
it('should return null when no alternative profile is available', () => {
|
||||
const noAlternativeManager = createMockProfileManager({
|
||||
bestAvailableProfile: null
|
||||
});
|
||||
|
||||
const bestProfile = noAlternativeManager.getBestAvailableProfile('profile-mai');
|
||||
|
||||
expect(bestProfile).toBeNull();
|
||||
});
|
||||
|
||||
it('should not return the same profile that hit the limit', () => {
|
||||
const bestProfile = mockProfileManager.getBestAvailableProfile('profile-mai');
|
||||
|
||||
// Best profile should be different from the one that hit the limit
|
||||
expect(bestProfile?.id).not.toBe('profile-mai');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Auto-Recovery Flow Simulation', () => {
|
||||
/**
|
||||
* Simulates the flow in agent-process.ts lines 274-327
|
||||
*/
|
||||
function simulateRateLimitRecovery(
|
||||
output: string,
|
||||
exitCode: number,
|
||||
profileManager: ReturnType<typeof createMockProfileManager>
|
||||
): {
|
||||
rateLimitDetected: boolean;
|
||||
autoSwapped: boolean;
|
||||
taskRestarted: boolean;
|
||||
modalShown: boolean;
|
||||
swappedToProfile?: { id: string; name: string };
|
||||
} {
|
||||
const result = {
|
||||
rateLimitDetected: false,
|
||||
autoSwapped: false,
|
||||
taskRestarted: false,
|
||||
modalShown: false,
|
||||
swappedToProfile: undefined as { id: string; name: string } | undefined
|
||||
};
|
||||
|
||||
// Only check rate limit if process failed
|
||||
if (exitCode !== 0) {
|
||||
// Simulate detectRateLimit
|
||||
const rateLimitPattern = /Limit reached\s*[·•]\s*resets\s+(.+?)(?:\s*$|\n)/im;
|
||||
const rateIndicators = [/rate\s*limit/i, /usage\s*limit/i, /limit\s*reached/i];
|
||||
|
||||
const isRateLimited = rateLimitPattern.test(output) ||
|
||||
rateIndicators.some(p => p.test(output));
|
||||
|
||||
if (isRateLimited) {
|
||||
result.rateLimitDetected = true;
|
||||
|
||||
const settings = profileManager.getAutoSwitchSettings();
|
||||
|
||||
if (settings.enabled && settings.autoSwitchOnRateLimit) {
|
||||
const bestProfile = profileManager.getBestAvailableProfile('current-profile');
|
||||
|
||||
if (bestProfile) {
|
||||
// Auto-swap
|
||||
profileManager.setActiveProfile(bestProfile.id);
|
||||
result.autoSwapped = true;
|
||||
result.swappedToProfile = { id: bestProfile.id, name: bestProfile.name };
|
||||
result.taskRestarted = true;
|
||||
result.modalShown = true; // Notification modal
|
||||
} else {
|
||||
// No alternative - show manual modal
|
||||
result.modalShown = true;
|
||||
}
|
||||
} else {
|
||||
// Auto-switch disabled - show manual modal
|
||||
result.modalShown = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
it('should auto-swap and restart when all conditions met', () => {
|
||||
const result = simulateRateLimitRecovery(
|
||||
'Limit reached · resets Dec 17 at 6am',
|
||||
1, // non-zero exit
|
||||
mockProfileManager
|
||||
);
|
||||
|
||||
expect(result.rateLimitDetected).toBe(true);
|
||||
expect(result.autoSwapped).toBe(true);
|
||||
expect(result.taskRestarted).toBe(true);
|
||||
expect(result.modalShown).toBe(true);
|
||||
expect(result.swappedToProfile?.id).toBe('profile-mu');
|
||||
});
|
||||
|
||||
it('should NOT auto-swap when exit code is 0', () => {
|
||||
const result = simulateRateLimitRecovery(
|
||||
'Limit reached · resets Dec 17 at 6am',
|
||||
0, // success exit
|
||||
mockProfileManager
|
||||
);
|
||||
|
||||
expect(result.rateLimitDetected).toBe(false);
|
||||
expect(result.autoSwapped).toBe(false);
|
||||
expect(result.taskRestarted).toBe(false);
|
||||
});
|
||||
|
||||
it('should NOT auto-swap when enabled is false', () => {
|
||||
const disabledManager = createMockProfileManager({
|
||||
autoSwitchSettings: { ...mockAutoSwitchSettings, enabled: false }
|
||||
});
|
||||
|
||||
const result = simulateRateLimitRecovery(
|
||||
'Limit reached · resets Dec 17 at 6am',
|
||||
1,
|
||||
disabledManager
|
||||
);
|
||||
|
||||
expect(result.rateLimitDetected).toBe(true);
|
||||
expect(result.autoSwapped).toBe(false);
|
||||
expect(result.modalShown).toBe(true); // Manual modal
|
||||
});
|
||||
|
||||
it('should NOT auto-swap when autoSwitchOnRateLimit is false', () => {
|
||||
const manualManager = createMockProfileManager({
|
||||
autoSwitchSettings: { ...mockAutoSwitchSettings, autoSwitchOnRateLimit: false }
|
||||
});
|
||||
|
||||
const result = simulateRateLimitRecovery(
|
||||
'Limit reached · resets Dec 17 at 6am',
|
||||
1,
|
||||
manualManager
|
||||
);
|
||||
|
||||
expect(result.rateLimitDetected).toBe(true);
|
||||
expect(result.autoSwapped).toBe(false);
|
||||
expect(result.modalShown).toBe(true); // Manual modal
|
||||
});
|
||||
|
||||
it('should show manual modal when no alternative profile available', () => {
|
||||
const noAlternativeManager = createMockProfileManager({
|
||||
bestAvailableProfile: null
|
||||
});
|
||||
|
||||
const result = simulateRateLimitRecovery(
|
||||
'Limit reached · resets Dec 17 at 6am',
|
||||
1,
|
||||
noAlternativeManager
|
||||
);
|
||||
|
||||
expect(result.rateLimitDetected).toBe(true);
|
||||
expect(result.autoSwapped).toBe(false);
|
||||
expect(result.taskRestarted).toBe(false);
|
||||
expect(result.modalShown).toBe(true); // Manual modal because no alternative
|
||||
});
|
||||
|
||||
it('should NOT detect rate limit for normal errors', () => {
|
||||
const result = simulateRateLimitRecovery(
|
||||
'Error: File not found',
|
||||
1,
|
||||
mockProfileManager
|
||||
);
|
||||
|
||||
expect(result.rateLimitDetected).toBe(false);
|
||||
expect(result.autoSwapped).toBe(false);
|
||||
expect(result.modalShown).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Task Restart Context Preservation', () => {
|
||||
it('should preserve task context for restart', () => {
|
||||
// Simulate task execution context
|
||||
const taskContext = {
|
||||
taskId: 'task-123',
|
||||
projectPath: '/path/to/project',
|
||||
specId: 'spec-001',
|
||||
options: { qa: false },
|
||||
swapCount: 0,
|
||||
isSpecCreation: false
|
||||
};
|
||||
|
||||
// After swap, swapCount should increment
|
||||
taskContext.swapCount++;
|
||||
|
||||
expect(taskContext.swapCount).toBe(1);
|
||||
});
|
||||
|
||||
it('should limit swap retries to prevent infinite loops', () => {
|
||||
const MAX_SWAPS = 2;
|
||||
let swapCount = 0;
|
||||
|
||||
// Simulate multiple rate limits
|
||||
for (let i = 0; i < 5; i++) {
|
||||
if (swapCount >= MAX_SWAPS) {
|
||||
break; // Should stop after 2 swaps
|
||||
}
|
||||
swapCount++;
|
||||
}
|
||||
|
||||
expect(swapCount).toBe(MAX_SWAPS);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Event Emission Verification', () => {
|
||||
it('should emit sdk-rate-limit event on rate limit', () => {
|
||||
const emitter = new EventEmitter();
|
||||
const sdkRateLimitHandler = vi.fn();
|
||||
|
||||
emitter.on('sdk-rate-limit', sdkRateLimitHandler);
|
||||
|
||||
// Simulate rate limit detected with auto-swap
|
||||
const rateLimitInfo = {
|
||||
source: 'task' as const,
|
||||
taskId: 'task-123',
|
||||
resetTime: 'Dec 17 at 6am',
|
||||
limitType: 'weekly' as const,
|
||||
profileId: 'profile-mai',
|
||||
profileName: 'MAI',
|
||||
wasAutoSwapped: true,
|
||||
swappedToProfile: { id: 'profile-mu', name: 'MU' },
|
||||
swapReason: 'reactive' as const,
|
||||
detectedAt: new Date()
|
||||
};
|
||||
|
||||
emitter.emit('sdk-rate-limit', rateLimitInfo);
|
||||
|
||||
expect(sdkRateLimitHandler).toHaveBeenCalledWith(rateLimitInfo);
|
||||
expect(sdkRateLimitHandler).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should emit auto-swap-restart-task event for task restart', () => {
|
||||
const emitter = new EventEmitter();
|
||||
const restartHandler = vi.fn();
|
||||
|
||||
emitter.on('auto-swap-restart-task', restartHandler);
|
||||
|
||||
emitter.emit('auto-swap-restart-task', 'task-123', 'profile-mu');
|
||||
|
||||
expect(restartHandler).toHaveBeenCalledWith('task-123', 'profile-mu');
|
||||
});
|
||||
|
||||
it('should handle event chain: rate-limit → swap → restart', () => {
|
||||
const emitter = new EventEmitter();
|
||||
const events: string[] = [];
|
||||
|
||||
emitter.on('sdk-rate-limit', () => events.push('sdk-rate-limit'));
|
||||
emitter.on('auto-swap-restart-task', () => events.push('auto-swap-restart-task'));
|
||||
|
||||
// Simulate the flow
|
||||
emitter.emit('sdk-rate-limit', { /* info */ });
|
||||
emitter.emit('auto-swap-restart-task', 'task-123', 'profile-mu');
|
||||
|
||||
expect(events).toEqual(['sdk-rate-limit', 'auto-swap-restart-task']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Rate Limit Edge Cases', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Pattern Matching Edge Cases', () => {
|
||||
const mockManager = createMockProfileManager();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.doMock('../claude-profile-manager', () => ({
|
||||
getClaudeProfileManager: vi.fn(() => mockManager)
|
||||
}));
|
||||
});
|
||||
|
||||
it('should handle different bullet characters', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
// Middle dot (·)
|
||||
expect(detectRateLimit('Limit reached · resets 5pm').isRateLimited).toBe(true);
|
||||
|
||||
// Bullet (•)
|
||||
expect(detectRateLimit('Limit reached • resets 5pm').isRateLimited).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle different timezone formats', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
const timezones = [
|
||||
'Dec 17 at 6am (Europe/Oslo)',
|
||||
'Dec 17 at 6am (America/New_York)',
|
||||
'Dec 17 at 6am (Asia/Tokyo)',
|
||||
'Dec 17 at 6am (UTC)',
|
||||
'Dec 17 at 6am' // No timezone
|
||||
];
|
||||
|
||||
for (const tz of timezones) {
|
||||
const result = detectRateLimit(`Limit reached · resets ${tz}`);
|
||||
expect(result.isRateLimited).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle 12-hour and 24-hour time formats', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
expect(detectRateLimit('Limit reached · resets 11:59pm').isRateLimited).toBe(true);
|
||||
expect(detectRateLimit('Limit reached · resets 6am').isRateLimited).toBe(true);
|
||||
expect(detectRateLimit('Limit reached · resets 18:00').isRateLimited).toBe(true);
|
||||
});
|
||||
|
||||
it('should NOT false-positive on similar messages', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
// These should NOT trigger rate limit detection
|
||||
const falsePositives = [
|
||||
'Limit your requests to avoid issues', // Contains 'limit' but not rate limit
|
||||
'The speed limit is 60mph', // Unrelated limit
|
||||
'Character limit reached for input field' // Different kind of limit
|
||||
];
|
||||
|
||||
for (const msg of falsePositives) {
|
||||
const result = detectRateLimit(msg);
|
||||
// Note: Some may still match secondary indicators - that's intentional
|
||||
// The primary pattern should NOT match these
|
||||
const primaryPattern = /Limit reached\s*[·•]\s*resets/i;
|
||||
expect(primaryPattern.test(msg)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Both Profiles Rate Limited', () => {
|
||||
it('should return null when all profiles are rate limited', () => {
|
||||
const bothLimitedManager = createMockProfileManager({
|
||||
bestAvailableProfile: null
|
||||
});
|
||||
|
||||
const best = bothLimitedManager.getBestAvailableProfile('profile-mai');
|
||||
expect(best).toBeNull();
|
||||
});
|
||||
|
||||
it('should show manual modal when no profiles available', () => {
|
||||
// User must either wait or add a new account
|
||||
const bothLimitedManager = createMockProfileManager({
|
||||
bestAvailableProfile: null
|
||||
});
|
||||
|
||||
const settings = bothLimitedManager.getAutoSwitchSettings();
|
||||
const bestProfile = bothLimitedManager.getBestAvailableProfile('profile-mai');
|
||||
|
||||
// Even with auto-switch enabled, should show modal since no alternative
|
||||
const shouldShowManualModal = settings.enabled && settings.autoSwitchOnRateLimit && !bestProfile;
|
||||
expect(shouldShowManualModal).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Rapid Rate Limit Succession', () => {
|
||||
it('should enforce max swap count', () => {
|
||||
const MAX_SWAP_COUNT = 2;
|
||||
const context = { swapCount: 0 };
|
||||
|
||||
// First swap
|
||||
context.swapCount++;
|
||||
expect(context.swapCount < MAX_SWAP_COUNT).toBe(true);
|
||||
|
||||
// Second swap
|
||||
context.swapCount++;
|
||||
expect(context.swapCount >= MAX_SWAP_COUNT).toBe(true);
|
||||
|
||||
// Third swap should be blocked
|
||||
const shouldAllowSwap = context.swapCount < MAX_SWAP_COUNT;
|
||||
expect(shouldAllowSwap).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Modal Behavior with Reactive Recovery', () => {
|
||||
describe('Modal Content Variations', () => {
|
||||
it('should show notification-style modal when auto-swapped', () => {
|
||||
const rateLimitInfo = {
|
||||
source: 'task' as const,
|
||||
wasAutoSwapped: true,
|
||||
swappedToProfile: { id: 'profile-mu', name: 'MU' },
|
||||
swapReason: 'reactive' as const
|
||||
};
|
||||
|
||||
// When wasAutoSwapped is true, modal should be informational
|
||||
expect(rateLimitInfo.wasAutoSwapped).toBe(true);
|
||||
expect(rateLimitInfo.swapReason).toBe('reactive');
|
||||
});
|
||||
|
||||
it('should show action-required modal when NOT auto-swapped', () => {
|
||||
const rateLimitInfo = {
|
||||
source: 'task' as const,
|
||||
wasAutoSwapped: false,
|
||||
suggestedProfile: { id: 'profile-mu', name: 'MU' }
|
||||
};
|
||||
|
||||
// When wasAutoSwapped is false, user needs to take action
|
||||
expect(rateLimitInfo.wasAutoSwapped).toBe(false);
|
||||
});
|
||||
|
||||
it('should distinguish proactive vs reactive swaps', () => {
|
||||
const proactiveSwap = {
|
||||
wasAutoSwapped: true,
|
||||
swapReason: 'proactive' as const // Before limit hit
|
||||
};
|
||||
|
||||
const reactiveSwap = {
|
||||
wasAutoSwapped: true,
|
||||
swapReason: 'reactive' as const // After limit hit
|
||||
};
|
||||
|
||||
expect(proactiveSwap.swapReason).toBe('proactive');
|
||||
expect(reactiveSwap.swapReason).toBe('reactive');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,560 @@
|
||||
/**
|
||||
* Unit tests for rate limit and auth failure detection
|
||||
* Tests detection patterns for rate limiting and authentication failures
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
// Mock the claude-profile-manager before importing
|
||||
vi.mock('../claude-profile-manager', () => ({
|
||||
getClaudeProfileManager: vi.fn(() => ({
|
||||
getActiveProfile: vi.fn(() => ({
|
||||
id: 'test-profile-id',
|
||||
name: 'Test Profile',
|
||||
isDefault: true
|
||||
})),
|
||||
getProfile: vi.fn((id: string) => ({
|
||||
id,
|
||||
name: 'Test Profile',
|
||||
isDefault: true
|
||||
})),
|
||||
getBestAvailableProfile: vi.fn(() => null),
|
||||
recordRateLimitEvent: vi.fn()
|
||||
}))
|
||||
}));
|
||||
|
||||
describe('Rate Limit Detector', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('detectRateLimit', () => {
|
||||
it('should detect rate limit with reset time', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Limit reached · resets Dec 17 at 6am (Europe/Oslo)';
|
||||
const result = detectRateLimit(output);
|
||||
|
||||
expect(result.isRateLimited).toBe(true);
|
||||
expect(result.resetTime).toBe('Dec 17 at 6am (Europe/Oslo)');
|
||||
expect(result.limitType).toBe('weekly');
|
||||
});
|
||||
|
||||
it('should detect rate limit with bullet character', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Limit reached • resets 11:59pm';
|
||||
const result = detectRateLimit(output);
|
||||
|
||||
expect(result.isRateLimited).toBe(true);
|
||||
expect(result.resetTime).toBe('11:59pm');
|
||||
expect(result.limitType).toBe('session');
|
||||
});
|
||||
|
||||
it('should detect secondary rate limit indicators', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
const testCases = [
|
||||
'rate limit exceeded',
|
||||
'usage limit reached',
|
||||
'You have exceeded your limit',
|
||||
'too many requests'
|
||||
];
|
||||
|
||||
for (const output of testCases) {
|
||||
const result = detectRateLimit(output);
|
||||
expect(result.isRateLimited).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('should return false for non-rate-limit output', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Task completed successfully';
|
||||
const result = detectRateLimit(output);
|
||||
|
||||
expect(result.isRateLimited).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for empty output', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
const result = detectRateLimit('');
|
||||
|
||||
expect(result.isRateLimited).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isRateLimitError', () => {
|
||||
it('should return true for rate limit errors', async () => {
|
||||
const { isRateLimitError } = await import('../rate-limit-detector');
|
||||
|
||||
expect(isRateLimitError('Limit reached · resets Dec 17 at 6am')).toBe(true);
|
||||
expect(isRateLimitError('rate limit exceeded')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-rate-limit errors', async () => {
|
||||
const { isRateLimitError } = await import('../rate-limit-detector');
|
||||
|
||||
expect(isRateLimitError('authentication required')).toBe(false);
|
||||
expect(isRateLimitError('Task completed')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractResetTime', () => {
|
||||
it('should extract reset time from rate limit message', async () => {
|
||||
const { extractResetTime } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Limit reached · resets Dec 17 at 6am (Europe/Oslo)';
|
||||
const resetTime = extractResetTime(output);
|
||||
|
||||
expect(resetTime).toBe('Dec 17 at 6am (Europe/Oslo)');
|
||||
});
|
||||
|
||||
it('should return null for non-rate-limit output', async () => {
|
||||
const { extractResetTime } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Task completed successfully';
|
||||
const resetTime = extractResetTime(output);
|
||||
|
||||
expect(resetTime).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Auth Failure Detection', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('detectAuthFailure', () => {
|
||||
it('should detect "authentication required" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Error: authentication required';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('missing');
|
||||
expect(result.message).toContain('authentication required');
|
||||
});
|
||||
|
||||
it('should detect "authentication is required" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Authentication is required to proceed';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('missing');
|
||||
});
|
||||
|
||||
it('should detect "not authenticated" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Error: not authenticated';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('missing');
|
||||
});
|
||||
|
||||
it('should detect "not yet authenticated" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'You are not yet authenticated';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('missing');
|
||||
});
|
||||
|
||||
it('should detect "login required" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Login required';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('missing');
|
||||
});
|
||||
|
||||
it('should detect "oauth token invalid" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'OAuth token is invalid';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('invalid');
|
||||
});
|
||||
|
||||
it('should detect "oauth token expired" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'OAuth token expired';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('expired');
|
||||
});
|
||||
|
||||
it('should detect "oauth token missing" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'OAuth token missing';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('missing');
|
||||
});
|
||||
|
||||
it('should detect "unauthorized" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Error: Unauthorized';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('invalid');
|
||||
});
|
||||
|
||||
it('should detect "please log in" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Please log in to continue';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
// "please log in" doesn't contain 'required' keyword, so classified as 'unknown'
|
||||
expect(result.failureType).toBeDefined();
|
||||
});
|
||||
|
||||
it('should detect "please authenticate" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Please authenticate before proceeding';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
// "please authenticate" doesn't contain 'required' keyword, so classified as 'unknown'
|
||||
expect(result.failureType).toBeDefined();
|
||||
});
|
||||
|
||||
it('should detect "invalid credentials" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Invalid credentials provided';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('invalid');
|
||||
});
|
||||
|
||||
it('should detect "invalid token" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Invalid token';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('invalid');
|
||||
});
|
||||
|
||||
it('should detect "auth failed" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Auth failed';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect "authentication error" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Authentication error occurred';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect "session expired" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Your session expired';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('expired');
|
||||
});
|
||||
|
||||
it('should detect "access denied" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Access denied';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('invalid');
|
||||
});
|
||||
|
||||
it('should detect "permission denied" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Permission denied';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('invalid');
|
||||
});
|
||||
|
||||
it('should detect "401 unauthorized" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'HTTP 401 Unauthorized';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('invalid');
|
||||
});
|
||||
|
||||
it('should detect "credentials missing" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Credentials are missing';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('missing');
|
||||
});
|
||||
|
||||
it('should detect "credentials expired" pattern', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Credentials expired';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.failureType).toBe('expired');
|
||||
});
|
||||
|
||||
it('should return false for rate limit errors (not auth failure)', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Limit reached · resets Dec 17 at 6am';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for normal output', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Task completed successfully';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for empty output', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const result = detectAuthFailure('');
|
||||
|
||||
expect(result.isAuthFailure).toBe(false);
|
||||
});
|
||||
|
||||
it('should include profile ID in result', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const result = detectAuthFailure('authentication required', 'custom-profile');
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.profileId).toBe('custom-profile');
|
||||
});
|
||||
|
||||
it('should use active profile ID when not specified', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const result = detectAuthFailure('authentication required');
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.profileId).toBe('test-profile-id');
|
||||
});
|
||||
|
||||
it('should include original error in result', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = 'Error: authentication required for this action';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.originalError).toBe(output);
|
||||
});
|
||||
|
||||
it('should provide user-friendly message for missing auth', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const result = detectAuthFailure('authentication required');
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.message).toContain('Settings');
|
||||
expect(result.message).toContain('Claude Profiles');
|
||||
});
|
||||
|
||||
it('should provide user-friendly message for expired auth', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const result = detectAuthFailure('session expired');
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.message).toContain('expired');
|
||||
expect(result.message).toContain('re-authenticate');
|
||||
});
|
||||
|
||||
it('should provide user-friendly message for invalid auth', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const result = detectAuthFailure('unauthorized');
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
expect(result.message).toContain('Invalid');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isAuthFailureError', () => {
|
||||
it('should return true for auth failure errors', async () => {
|
||||
const { isAuthFailureError } = await import('../rate-limit-detector');
|
||||
|
||||
expect(isAuthFailureError('authentication required')).toBe(true);
|
||||
expect(isAuthFailureError('not authenticated')).toBe(true);
|
||||
expect(isAuthFailureError('unauthorized')).toBe(true);
|
||||
expect(isAuthFailureError('invalid token')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-auth-failure errors', async () => {
|
||||
const { isAuthFailureError } = await import('../rate-limit-detector');
|
||||
|
||||
expect(isAuthFailureError('Limit reached · resets Dec 17')).toBe(false);
|
||||
expect(isAuthFailureError('Task completed')).toBe(false);
|
||||
expect(isAuthFailureError('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('auth failure does not match rate limit patterns', () => {
|
||||
it('should not detect auth failure as rate limit', async () => {
|
||||
const { detectRateLimit } = await import('../rate-limit-detector');
|
||||
|
||||
const authErrors = [
|
||||
'authentication required',
|
||||
'not authenticated',
|
||||
'unauthorized',
|
||||
'invalid token',
|
||||
'session expired',
|
||||
'please log in'
|
||||
];
|
||||
|
||||
for (const error of authErrors) {
|
||||
const result = detectRateLimit(error);
|
||||
expect(result.isRateLimited).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('should not detect rate limit as auth failure', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const rateLimitErrors = [
|
||||
'Limit reached · resets Dec 17 at 6am',
|
||||
'rate limit exceeded',
|
||||
'too many requests',
|
||||
'usage limit reached'
|
||||
];
|
||||
|
||||
for (const error of rateLimitErrors) {
|
||||
const result = detectAuthFailure(error);
|
||||
expect(result.isAuthFailure).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('should handle multiline output with auth failure', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = `Starting task...
|
||||
Processing...
|
||||
Error: authentication required
|
||||
Please authenticate and try again.`;
|
||||
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle case-insensitive matching', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const testCases = [
|
||||
'AUTHENTICATION REQUIRED',
|
||||
'Authentication Required',
|
||||
'UNAUTHORIZED',
|
||||
'Unauthorized',
|
||||
'NOT AUTHENTICATED',
|
||||
'Not Authenticated'
|
||||
];
|
||||
|
||||
for (const output of testCases) {
|
||||
const result = detectAuthFailure(output);
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle partial matches correctly', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
// Should NOT match - word is part of a different context
|
||||
const falsePositives = [
|
||||
'The authenticated user can proceed', // has 'authenticated' but not an error
|
||||
'Authorization header set correctly' // different word
|
||||
];
|
||||
|
||||
// Note: Some false positives may still match due to pattern design
|
||||
// The patterns are intentionally broad to catch errors
|
||||
for (const output of falsePositives) {
|
||||
const result = detectAuthFailure(output);
|
||||
// Just verify it runs without error - actual match depends on pattern design
|
||||
expect(typeof result.isAuthFailure).toBe('boolean');
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle JSON error responses', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = '{"error": "unauthorized", "message": "Please authenticate"}';
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle error stack traces with auth failure', async () => {
|
||||
const { detectAuthFailure } = await import('../rate-limit-detector');
|
||||
|
||||
const output = `Error: authentication required
|
||||
at validateToken (/app/auth.js:42)
|
||||
at processRequest (/app/handler.js:15)
|
||||
at main (/app/index.js:8)`;
|
||||
|
||||
const result = detectAuthFailure(output);
|
||||
|
||||
expect(result.isAuthFailure).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -5,14 +5,13 @@ import { AgentState } from './agent-state';
|
||||
import { AgentEvents } from './agent-events';
|
||||
import { AgentProcessManager } from './agent-process';
|
||||
import { AgentQueueManager } from './agent-queue';
|
||||
import { getClaudeProfileManager } from '../claude-profile-manager';
|
||||
import {
|
||||
AgentManagerEvents,
|
||||
ExecutionProgressData,
|
||||
ProcessType,
|
||||
SpecCreationMetadata,
|
||||
TaskExecutionOptions,
|
||||
IdeationConfig
|
||||
RoadmapConfig
|
||||
} from './types';
|
||||
import type { IdeationConfig } from '../../shared/types';
|
||||
|
||||
/**
|
||||
* Main AgentManager - orchestrates agent process lifecycle
|
||||
@@ -45,8 +44,9 @@ export class AgentManager extends EventEmitter {
|
||||
|
||||
// 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.restartTask(taskId);
|
||||
console.log('[AgentManager] Received auto-swap-restart-task event:', { taskId, newProfileId });
|
||||
const success = this.restartTask(taskId, newProfileId);
|
||||
console.log('[AgentManager] Task restart result:', success ? 'SUCCESS' : 'FAILED');
|
||||
});
|
||||
|
||||
// Listen for task completion to clean up context (prevent memory leak)
|
||||
@@ -64,14 +64,12 @@ export class AgentManager extends EventEmitter {
|
||||
// If task completed successfully, always clean up
|
||||
if (code === 0) {
|
||||
this.taskExecutionContext.delete(taskId);
|
||||
console.log('[AgentManager] Cleaned up context for completed task:', taskId);
|
||||
return;
|
||||
}
|
||||
|
||||
// If task failed and hit max retries, clean up
|
||||
if (context.swapCount >= 2) {
|
||||
this.taskExecutionContext.delete(taskId);
|
||||
console.log('[AgentManager] Cleaned up context for max-retry task:', taskId);
|
||||
}
|
||||
// Otherwise keep context for potential restart
|
||||
}, 1000); // Delay to allow restart logic to run first
|
||||
@@ -95,6 +93,13 @@ export class AgentManager extends EventEmitter {
|
||||
specDir?: string,
|
||||
metadata?: SpecCreationMetadata
|
||||
): void {
|
||||
// Pre-flight auth check: Verify active profile has valid authentication
|
||||
const profileManager = getClaudeProfileManager();
|
||||
if (!profileManager.hasValidAuth()) {
|
||||
this.emit('error', taskId, 'Claude authentication required. Please authenticate in Settings > Claude Profiles before starting tasks.');
|
||||
return;
|
||||
}
|
||||
|
||||
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
|
||||
|
||||
if (!autoBuildSource) {
|
||||
@@ -126,6 +131,20 @@ export class AgentManager extends EventEmitter {
|
||||
args.push('--auto-approve');
|
||||
}
|
||||
|
||||
// Pass model and thinking level configuration
|
||||
// For auto profile, use phase-specific config; otherwise use single model/thinking
|
||||
if (metadata?.isAutoProfile && metadata.phaseModels && metadata.phaseThinking) {
|
||||
// Pass the spec phase model and thinking level to spec_runner
|
||||
args.push('--model', metadata.phaseModels.spec);
|
||||
args.push('--thinking-level', metadata.phaseThinking.spec);
|
||||
} else if (metadata?.model) {
|
||||
// Non-auto profile: use single model and thinking level
|
||||
args.push('--model', metadata.model);
|
||||
if (metadata.thinkingLevel) {
|
||||
args.push('--thinking-level', metadata.thinkingLevel);
|
||||
}
|
||||
}
|
||||
|
||||
// Store context for potential restart
|
||||
this.storeTaskContext(taskId, projectPath, '', {}, true, taskDescription, specDir, metadata);
|
||||
|
||||
@@ -142,21 +161,23 @@ export class AgentManager extends EventEmitter {
|
||||
specId: string,
|
||||
options: TaskExecutionOptions = {}
|
||||
): void {
|
||||
console.log('[AgentManager] startTaskExecution called for:', taskId, specId);
|
||||
// Pre-flight auth check: Verify active profile has valid authentication
|
||||
const profileManager = getClaudeProfileManager();
|
||||
if (!profileManager.hasValidAuth()) {
|
||||
this.emit('error', taskId, 'Claude authentication required. Please authenticate in Settings > Claude Profiles before starting tasks.');
|
||||
return;
|
||||
}
|
||||
|
||||
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
|
||||
|
||||
if (!autoBuildSource) {
|
||||
console.log('[AgentManager] ERROR: Auto-build source path not found');
|
||||
this.emit('error', taskId, 'Auto-build source path not found. Please configure it in App Settings.');
|
||||
return;
|
||||
}
|
||||
|
||||
const runPath = path.join(autoBuildSource, 'run.py');
|
||||
console.log('[AgentManager] runPath:', runPath);
|
||||
|
||||
if (!existsSync(runPath)) {
|
||||
console.log('[AgentManager] ERROR: Run script not found at:', runPath);
|
||||
this.emit('error', taskId, `Run script not found at: ${runPath}`);
|
||||
return;
|
||||
}
|
||||
@@ -179,11 +200,12 @@ export class AgentManager extends EventEmitter {
|
||||
|
||||
// Note: --parallel was removed from run.py CLI - parallel execution is handled internally by the agent
|
||||
// The options.parallel and options.workers are kept for future use or logging purposes
|
||||
// Note: Model configuration is read from task_metadata.json by the Python scripts,
|
||||
// which allows per-phase configuration for planner, coder, and QA phases
|
||||
|
||||
// Store context for potential restart
|
||||
this.storeTaskContext(taskId, projectPath, specId, options, false);
|
||||
|
||||
console.log('[AgentManager] Spawning process with args:', args);
|
||||
this.processManager.spawnProcess(taskId, autoBuildSource, args, combinedEnv, 'task-execution');
|
||||
}
|
||||
|
||||
@@ -224,9 +246,11 @@ export class AgentManager extends EventEmitter {
|
||||
projectId: string,
|
||||
projectPath: string,
|
||||
refresh: boolean = false,
|
||||
enableCompetitorAnalysis: boolean = false
|
||||
enableCompetitorAnalysis: boolean = false,
|
||||
refreshCompetitorAnalysis: boolean = false,
|
||||
config?: RoadmapConfig
|
||||
): void {
|
||||
this.queueManager.startRoadmapGeneration(projectId, projectPath, refresh, enableCompetitorAnalysis);
|
||||
this.queueManager.startRoadmapGeneration(projectId, projectPath, refresh, enableCompetitorAnalysis, refreshCompetitorAnalysis, config);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -262,6 +286,20 @@ export class AgentManager extends EventEmitter {
|
||||
return this.queueManager.isIdeationRunning(projectId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop roadmap generation for a project
|
||||
*/
|
||||
stopRoadmap(projectId: string): boolean {
|
||||
return this.queueManager.stopRoadmap(projectId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if roadmap is running for a project
|
||||
*/
|
||||
isRoadmapRunning(projectId: string): boolean {
|
||||
return this.queueManager.isRoadmapRunning(projectId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kill all running processes
|
||||
*/
|
||||
@@ -314,29 +352,56 @@ export class AgentManager extends EventEmitter {
|
||||
|
||||
/**
|
||||
* Restart task after profile swap
|
||||
* @param taskId - The task to restart
|
||||
* @param newProfileId - Optional new profile ID to apply (from auto-swap)
|
||||
*/
|
||||
restartTask(taskId: string): boolean {
|
||||
restartTask(taskId: string, newProfileId?: string): boolean {
|
||||
console.log('[AgentManager] restartTask called for:', taskId, 'with newProfileId:', newProfileId);
|
||||
|
||||
const context = this.taskExecutionContext.get(taskId);
|
||||
if (!context) {
|
||||
console.error('[AgentManager] No context for task:', taskId);
|
||||
console.log('[AgentManager] Available task contexts:', Array.from(this.taskExecutionContext.keys()));
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log('[AgentManager] Task context found:', {
|
||||
taskId,
|
||||
projectPath: context.projectPath,
|
||||
specId: context.specId,
|
||||
isSpecCreation: context.isSpecCreation,
|
||||
swapCount: context.swapCount
|
||||
});
|
||||
|
||||
// Prevent infinite swap loops
|
||||
if (context.swapCount >= 2) {
|
||||
console.error('[AgentManager] Max swap count reached for task:', taskId);
|
||||
console.error('[AgentManager] Max swap count reached for task:', taskId, '- stopping restart loop');
|
||||
return false;
|
||||
}
|
||||
|
||||
context.swapCount++;
|
||||
console.log('[AgentManager] Restarting task:', taskId, 'swap count:', context.swapCount);
|
||||
console.log('[AgentManager] Incremented swap count to:', context.swapCount);
|
||||
|
||||
// If a new profile was specified, ensure it's set as active before restart
|
||||
if (newProfileId) {
|
||||
const profileManager = getClaudeProfileManager();
|
||||
const currentActiveId = profileManager.getActiveProfile()?.id;
|
||||
if (currentActiveId !== newProfileId) {
|
||||
console.log('[AgentManager] Setting active profile to:', newProfileId);
|
||||
profileManager.setActiveProfile(newProfileId);
|
||||
}
|
||||
}
|
||||
|
||||
// Kill current process
|
||||
console.log('[AgentManager] Killing current process for task:', taskId);
|
||||
this.killTask(taskId);
|
||||
|
||||
// Wait for cleanup, then restart
|
||||
console.log('[AgentManager] Scheduling task restart in 500ms');
|
||||
setTimeout(() => {
|
||||
console.log('[AgentManager] Restarting task now:', taskId);
|
||||
if (context.isSpecCreation) {
|
||||
console.log('[AgentManager] Restarting as spec creation');
|
||||
this.startSpecCreation(
|
||||
taskId,
|
||||
context.projectPath,
|
||||
@@ -345,6 +410,7 @@ export class AgentManager extends EventEmitter {
|
||||
context.metadata
|
||||
);
|
||||
} else {
|
||||
console.log('[AgentManager] Restarting as task execution');
|
||||
this.startTaskExecution(
|
||||
taskId,
|
||||
context.projectPath,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { spawn, ChildProcess } from 'child_process';
|
||||
import { spawn } from 'child_process';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { app } from 'electron';
|
||||
@@ -6,9 +6,10 @@ import { EventEmitter } from 'events';
|
||||
import { AgentState } from './agent-state';
|
||||
import { AgentEvents } from './agent-events';
|
||||
import { ProcessType, ExecutionProgressData } from './types';
|
||||
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from '../rate-limit-detector';
|
||||
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv, detectAuthFailure } from '../rate-limit-detector';
|
||||
import { projectStore } from '../project-store';
|
||||
import { getClaudeProfileManager } from '../claude-profile-manager';
|
||||
import { findPythonCommand, parsePythonCommand } from '../python-detector';
|
||||
|
||||
/**
|
||||
* Process spawning and lifecycle management
|
||||
@@ -17,7 +18,8 @@ export class AgentProcessManager {
|
||||
private state: AgentState;
|
||||
private events: AgentEvents;
|
||||
private emitter: EventEmitter;
|
||||
private pythonPath: string = 'python3';
|
||||
// Auto-detect Python command on initialization
|
||||
private pythonPath: string = findPythonCommand() || 'python';
|
||||
private autoBuildSourcePath: string = '';
|
||||
|
||||
constructor(state: AgentState, events: AgentEvents, emitter: EventEmitter) {
|
||||
@@ -65,7 +67,8 @@ export class AgentProcessManager {
|
||||
];
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
|
||||
// Use requirements.txt as marker - it always exists in auto-claude source
|
||||
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -99,14 +102,11 @@ export class AgentProcessManager {
|
||||
loadAutoBuildEnv(): Record<string, string> {
|
||||
const autoBuildSource = this.getAutoBuildSourcePath();
|
||||
if (!autoBuildSource) {
|
||||
console.log('[loadAutoBuildEnv] No auto-build source path found');
|
||||
return {};
|
||||
}
|
||||
|
||||
const envPath = path.join(autoBuildSource, '.env');
|
||||
console.log('[loadAutoBuildEnv] Looking for .env at:', envPath);
|
||||
if (!existsSync(envPath)) {
|
||||
console.log('[loadAutoBuildEnv] .env file does not exist');
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -160,26 +160,23 @@ export class AgentProcessManager {
|
||||
// Generate unique spawn ID for this process instance
|
||||
const spawnId = this.state.generateSpawnId();
|
||||
|
||||
console.log('[spawnProcess] Spawning with pythonPath:', this.pythonPath);
|
||||
console.log('[spawnProcess] cwd:', cwd);
|
||||
console.log('[spawnProcess] processType:', processType);
|
||||
console.log('[spawnProcess] spawnId:', spawnId);
|
||||
|
||||
// Get active Claude profile environment (CLAUDE_CONFIG_DIR if not default)
|
||||
const profileEnv = getProfileEnv();
|
||||
|
||||
const childProcess = spawn(this.pythonPath, args, {
|
||||
// Parse Python command to handle space-separated commands like "py -3"
|
||||
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.pythonPath);
|
||||
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, ...args], {
|
||||
cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...extraEnv,
|
||||
...profileEnv, // Include active Claude profile config
|
||||
PYTHONUNBUFFERED: '1' // Ensure real-time output
|
||||
PYTHONUNBUFFERED: '1', // Ensure real-time output
|
||||
PYTHONIOENCODING: 'utf-8', // Ensure UTF-8 encoding on Windows
|
||||
PYTHONUTF8: '1' // Force Python UTF-8 mode on Windows (Python 3.7+)
|
||||
}
|
||||
});
|
||||
|
||||
console.log('[spawnProcess] Process spawned, pid:', childProcess.pid);
|
||||
|
||||
this.state.addProcess(taskId, {
|
||||
taskId,
|
||||
process: childProcess,
|
||||
@@ -239,66 +236,82 @@ export class AgentProcessManager {
|
||||
}
|
||||
};
|
||||
|
||||
// Handle stdout
|
||||
// Handle stdout - explicitly decode as UTF-8 for cross-platform Unicode support
|
||||
childProcess.stdout?.on('data', (data: Buffer) => {
|
||||
const log = data.toString();
|
||||
console.log('[spawnProcess] stdout:', log.substring(0, 200));
|
||||
const log = data.toString('utf8');
|
||||
this.emitter.emit('log', taskId, log);
|
||||
processLog(log);
|
||||
// Print to console when DEBUG is enabled (visible in pnpm dev terminal)
|
||||
if (['true', '1', 'yes', 'on'].includes(process.env.DEBUG?.toLowerCase() ?? '')) {
|
||||
console.log(`[Agent:${taskId}] ${log.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle stderr
|
||||
// Handle stderr - explicitly decode as UTF-8 for cross-platform Unicode support
|
||||
childProcess.stderr?.on('data', (data: Buffer) => {
|
||||
const log = data.toString();
|
||||
console.log('[spawnProcess] stderr:', log.substring(0, 200));
|
||||
const log = data.toString('utf8');
|
||||
// Some Python output goes to stderr (like progress bars)
|
||||
// so we treat it as log, not error
|
||||
this.emitter.emit('log', taskId, log);
|
||||
processLog(log);
|
||||
// Print to console when DEBUG is enabled (visible in pnpm dev terminal)
|
||||
if (['true', '1', 'yes', 'on'].includes(process.env.DEBUG?.toLowerCase() ?? '')) {
|
||||
console.log(`[Agent:${taskId}] ${log.trim()}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle process exit
|
||||
childProcess.on('exit', (code: number | null) => {
|
||||
console.log('[spawnProcess] Process exited with code:', code, 'spawnId:', spawnId);
|
||||
this.state.deleteProcess(taskId);
|
||||
|
||||
// Check if this specific spawn was killed (vs exited naturally)
|
||||
// If killed, don't emit exit event to prevent race condition with new process
|
||||
if (this.state.wasSpawnKilled(spawnId)) {
|
||||
console.log('[spawnProcess] Process was killed, skipping exit event for spawnId:', spawnId);
|
||||
this.state.clearKilledSpawn(spawnId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for rate limit if process failed
|
||||
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
|
||||
});
|
||||
console.log('[AgentProcess] Process failed with code:', code, 'for task:', taskId);
|
||||
console.log('[AgentProcess] Checking for rate limit in output (last 500 chars):', allOutput.slice(-500));
|
||||
|
||||
const rateLimitDetection = detectRateLimit(allOutput);
|
||||
console.log('[AgentProcess] Rate limit detection result:', {
|
||||
isRateLimited: rateLimitDetection.isRateLimited,
|
||||
resetTime: rateLimitDetection.resetTime,
|
||||
limitType: rateLimitDetection.limitType,
|
||||
profileId: rateLimitDetection.profileId,
|
||||
suggestedProfile: rateLimitDetection.suggestedProfile
|
||||
});
|
||||
|
||||
if (rateLimitDetection.isRateLimited) {
|
||||
// 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');
|
||||
console.log('[AgentProcess] Auto-switch settings:', {
|
||||
enabled: autoSwitchSettings.enabled,
|
||||
autoSwitchOnRateLimit: autoSwitchSettings.autoSwitchOnRateLimit,
|
||||
proactiveSwapEnabled: autoSwitchSettings.proactiveSwapEnabled
|
||||
});
|
||||
|
||||
if (autoSwitchSettings.enabled && autoSwitchSettings.autoSwitchOnRateLimit) {
|
||||
const currentProfileId = rateLimitDetection.profileId;
|
||||
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
|
||||
|
||||
if (bestProfile) {
|
||||
console.log('[spawnProcess] Reactive swap to:', bestProfile.name);
|
||||
console.log('[AgentProcess] Best available profile:', bestProfile ? {
|
||||
id: bestProfile.id,
|
||||
name: bestProfile.name
|
||||
} : 'NONE');
|
||||
|
||||
if (bestProfile) {
|
||||
// Switch active profile
|
||||
console.log('[AgentProcess] AUTO-SWAP: Switching from', currentProfileId, 'to', bestProfile.id);
|
||||
profileManager.setActiveProfile(bestProfile.id);
|
||||
|
||||
// Emit swap info (for modal)
|
||||
const source = processType === 'spec-creation' ? 'task' : 'task';
|
||||
const source = processType === 'spec-creation' ? 'roadmap' : 'task';
|
||||
const rateLimitInfo = createSDKRateLimitInfo(source, rateLimitDetection, {
|
||||
taskId
|
||||
});
|
||||
@@ -308,20 +321,43 @@ export class AgentProcessManager {
|
||||
name: bestProfile.name
|
||||
};
|
||||
rateLimitInfo.swapReason = 'reactive';
|
||||
|
||||
console.log('[AgentProcess] Emitting sdk-rate-limit event (auto-swapped):', rateLimitInfo);
|
||||
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
|
||||
|
||||
// Restart task
|
||||
console.log('[AgentProcess] Emitting auto-swap-restart-task event for task:', taskId);
|
||||
this.emitter.emit('auto-swap-restart-task', taskId, bestProfile.id);
|
||||
return;
|
||||
} else {
|
||||
console.log('[AgentProcess] No alternative profile available - falling back to manual modal');
|
||||
}
|
||||
} else {
|
||||
console.log('[AgentProcess] Auto-switch disabled - showing manual modal');
|
||||
}
|
||||
|
||||
// Fall back to manual modal (no auto-swap or no alternative profile)
|
||||
const source = processType === 'spec-creation' ? 'task' : 'task';
|
||||
const source = processType === 'spec-creation' ? 'roadmap' : 'task';
|
||||
const rateLimitInfo = createSDKRateLimitInfo(source, rateLimitDetection, {
|
||||
taskId
|
||||
});
|
||||
console.log('[AgentProcess] Emitting sdk-rate-limit event (manual):', rateLimitInfo);
|
||||
this.emitter.emit('sdk-rate-limit', rateLimitInfo);
|
||||
} else {
|
||||
console.log('[AgentProcess] No rate limit detected - checking for auth failure');
|
||||
// Not rate limited - check for authentication failure
|
||||
const authFailureDetection = detectAuthFailure(allOutput);
|
||||
if (authFailureDetection.isAuthFailure) {
|
||||
console.log('[AgentProcess] Auth failure detected:', authFailureDetection);
|
||||
this.emitter.emit('auth-failure', taskId, {
|
||||
profileId: authFailureDetection.profileId,
|
||||
failureType: authFailureDetection.failureType,
|
||||
message: authFailureDetection.message,
|
||||
originalError: authFailureDetection.originalError
|
||||
});
|
||||
} else {
|
||||
console.log('[AgentProcess] Process failed but no rate limit or auth failure detected');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -339,7 +375,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, {
|
||||
|
||||
@@ -5,8 +5,12 @@ import { EventEmitter } from 'events';
|
||||
import { AgentState } from './agent-state';
|
||||
import { AgentEvents } from './agent-events';
|
||||
import { AgentProcessManager } from './agent-process';
|
||||
import { IdeationConfig } from './types';
|
||||
import { RoadmapConfig } from './types';
|
||||
import type { IdeationConfig } from '../../shared/types';
|
||||
import { MODEL_ID_MAP } from '../../shared/constants';
|
||||
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from '../rate-limit-detector';
|
||||
import { debugLog, debugError } from '../../shared/utils/debug-logger';
|
||||
import { parsePythonCommand } from '../python-detector';
|
||||
|
||||
/**
|
||||
* Queue management for ideation and roadmap generation
|
||||
@@ -31,23 +35,40 @@ export class AgentQueueManager {
|
||||
|
||||
/**
|
||||
* Start roadmap generation process
|
||||
*
|
||||
* @param refreshCompetitorAnalysis - Force refresh competitor analysis even if it exists.
|
||||
* This allows refreshing competitor data independently of the general roadmap refresh.
|
||||
* Use when user explicitly wants new competitor research.
|
||||
*/
|
||||
startRoadmapGeneration(
|
||||
projectId: string,
|
||||
projectPath: string,
|
||||
refresh: boolean = false,
|
||||
enableCompetitorAnalysis: boolean = false
|
||||
enableCompetitorAnalysis: boolean = false,
|
||||
refreshCompetitorAnalysis: boolean = false,
|
||||
config?: RoadmapConfig
|
||||
): void {
|
||||
debugLog('[Agent Queue] Starting roadmap generation:', {
|
||||
projectId,
|
||||
projectPath,
|
||||
refresh,
|
||||
enableCompetitorAnalysis,
|
||||
refreshCompetitorAnalysis,
|
||||
config
|
||||
});
|
||||
|
||||
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
|
||||
|
||||
if (!autoBuildSource) {
|
||||
debugError('[Agent Queue] Auto-build source path not found');
|
||||
this.emitter.emit('roadmap-error', projectId, 'Auto-build source path not found. Please configure it in App Settings.');
|
||||
return;
|
||||
}
|
||||
|
||||
const roadmapRunnerPath = path.join(autoBuildSource, 'roadmap_runner.py');
|
||||
const roadmapRunnerPath = path.join(autoBuildSource, 'runners', 'roadmap_runner.py');
|
||||
|
||||
if (!existsSync(roadmapRunnerPath)) {
|
||||
debugError('[Agent Queue] Roadmap runner not found at:', roadmapRunnerPath);
|
||||
this.emitter.emit('roadmap-error', projectId, `Roadmap runner not found at: ${roadmapRunnerPath}`);
|
||||
return;
|
||||
}
|
||||
@@ -63,6 +84,22 @@ export class AgentQueueManager {
|
||||
args.push('--competitor-analysis');
|
||||
}
|
||||
|
||||
// Add refresh competitor analysis flag if user wants fresh competitor data
|
||||
if (refreshCompetitorAnalysis) {
|
||||
args.push('--refresh-competitor-analysis');
|
||||
}
|
||||
|
||||
// Add model and thinking level from config
|
||||
if (config?.model) {
|
||||
const modelId = MODEL_ID_MAP[config.model] || MODEL_ID_MAP['opus'];
|
||||
args.push('--model', modelId);
|
||||
}
|
||||
if (config?.thinkingLevel) {
|
||||
args.push('--thinking-level', config.thinkingLevel);
|
||||
}
|
||||
|
||||
debugLog('[Agent Queue] Spawning roadmap process with args:', args);
|
||||
|
||||
// Use projectId as taskId for roadmap operations
|
||||
this.spawnRoadmapProcess(projectId, projectPath, args);
|
||||
}
|
||||
@@ -76,16 +113,25 @@ export class AgentQueueManager {
|
||||
config: IdeationConfig,
|
||||
refresh: boolean = false
|
||||
): void {
|
||||
debugLog('[Agent Queue] Starting ideation generation:', {
|
||||
projectId,
|
||||
projectPath,
|
||||
config,
|
||||
refresh
|
||||
});
|
||||
|
||||
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
|
||||
|
||||
if (!autoBuildSource) {
|
||||
debugError('[Agent Queue] Auto-build source path not found');
|
||||
this.emitter.emit('ideation-error', projectId, 'Auto-build source path not found. Please configure it in App Settings.');
|
||||
return;
|
||||
}
|
||||
|
||||
const ideationRunnerPath = path.join(autoBuildSource, 'ideation_runner.py');
|
||||
const ideationRunnerPath = path.join(autoBuildSource, 'runners', 'ideation_runner.py');
|
||||
|
||||
if (!existsSync(ideationRunnerPath)) {
|
||||
debugError('[Agent Queue] Ideation runner not found at:', ideationRunnerPath);
|
||||
this.emitter.emit('ideation-error', projectId, `Ideation runner not found at: ${ideationRunnerPath}`);
|
||||
return;
|
||||
}
|
||||
@@ -119,6 +165,17 @@ export class AgentQueueManager {
|
||||
args.push('--append');
|
||||
}
|
||||
|
||||
// Add model and thinking level from config
|
||||
if (config.model) {
|
||||
const modelId = MODEL_ID_MAP[config.model] || MODEL_ID_MAP['opus'];
|
||||
args.push('--model', modelId);
|
||||
}
|
||||
if (config.thinkingLevel) {
|
||||
args.push('--thinking-level', config.thinkingLevel);
|
||||
}
|
||||
|
||||
debugLog('[Agent Queue] Spawning ideation process with args:', args);
|
||||
|
||||
// Use projectId as taskId for ideation operations
|
||||
this.spawnIdeationProcess(projectId, projectPath, args);
|
||||
}
|
||||
@@ -131,11 +188,17 @@ export class AgentQueueManager {
|
||||
projectPath: string,
|
||||
args: string[]
|
||||
): void {
|
||||
debugLog('[Agent Queue] Spawning ideation process:', { projectId, projectPath });
|
||||
|
||||
// Kill existing process for this project if any
|
||||
this.processManager.killProcess(projectId);
|
||||
const wasKilled = this.processManager.killProcess(projectId);
|
||||
if (wasKilled) {
|
||||
debugLog('[Agent Queue] Killed existing process for project:', projectId);
|
||||
}
|
||||
|
||||
// Generate unique spawn ID for this process instance
|
||||
const spawnId = this.state.generateSpawnId();
|
||||
debugLog('[Agent Queue] Generated spawn ID:', spawnId);
|
||||
|
||||
// Run from auto-claude source directory so imports work correctly
|
||||
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
|
||||
@@ -144,20 +207,44 @@ export class AgentQueueManager {
|
||||
// Get combined environment variables
|
||||
const combinedEnv = this.processManager.getCombinedEnv(projectPath);
|
||||
|
||||
// Get active Claude profile environment (CLAUDE_CONFIG_DIR if not default)
|
||||
// Get active Claude profile environment (CLAUDE_CODE_OAUTH_TOKEN if not default)
|
||||
const profileEnv = getProfileEnv();
|
||||
|
||||
// Get Python path from process manager (uses venv if configured)
|
||||
const pythonPath = this.processManager.getPythonPath();
|
||||
|
||||
const childProcess = spawn(pythonPath, args, {
|
||||
// Build final environment with proper precedence:
|
||||
// 1. process.env (system)
|
||||
// 2. combinedEnv (auto-claude/.env for CLI usage)
|
||||
// 3. profileEnv (Electron app OAuth token - highest priority)
|
||||
// 4. Our specific overrides
|
||||
const finalEnv = {
|
||||
...process.env,
|
||||
...combinedEnv,
|
||||
...profileEnv,
|
||||
PYTHONPATH: autoBuildSource || '', // Allow imports from auto-claude directory
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
};
|
||||
|
||||
// Debug: Show OAuth token source
|
||||
const tokenSource = profileEnv['CLAUDE_CODE_OAUTH_TOKEN']
|
||||
? 'Electron app profile'
|
||||
: (combinedEnv['CLAUDE_CODE_OAUTH_TOKEN'] ? 'auto-claude/.env' : 'not found');
|
||||
const oauthToken = (finalEnv as Record<string, string | undefined>)['CLAUDE_CODE_OAUTH_TOKEN'];
|
||||
const hasToken = !!oauthToken;
|
||||
debugLog('[Agent Queue] OAuth token status:', {
|
||||
source: tokenSource,
|
||||
hasToken,
|
||||
tokenPreview: hasToken ? oauthToken?.substring(0, 20) + '...' : 'none'
|
||||
});
|
||||
|
||||
// Parse Python command to handle space-separated commands like "py -3"
|
||||
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(pythonPath);
|
||||
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, ...args], {
|
||||
cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...combinedEnv,
|
||||
...profileEnv,
|
||||
PYTHONUNBUFFERED: '1'
|
||||
}
|
||||
env: finalEnv
|
||||
});
|
||||
|
||||
this.state.addProcess(projectId, {
|
||||
@@ -165,7 +252,8 @@ export class AgentQueueManager {
|
||||
process: childProcess,
|
||||
startedAt: new Date(),
|
||||
projectPath, // Store project path for loading session on completion
|
||||
spawnId
|
||||
spawnId,
|
||||
queueProcessType: 'ideation'
|
||||
});
|
||||
|
||||
// Track progress through output
|
||||
@@ -180,22 +268,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 +291,13 @@ export class AgentQueueManager {
|
||||
if (typeCompleteMatch) {
|
||||
const [, ideationType, ideasCount] = typeCompleteMatch;
|
||||
completedTypes.add(ideationType);
|
||||
console.log(`[Ideation] Type complete: ${ideationType} with ${ideasCount} ideas`);
|
||||
|
||||
debugLog('[Agent Queue] Ideation type completed:', {
|
||||
projectId,
|
||||
ideationType,
|
||||
ideasCount: parseInt(ideasCount, 10),
|
||||
totalCompleted: completedTypes.size
|
||||
});
|
||||
|
||||
// Emit event for UI to load this type's ideas immediately
|
||||
this.emitter.emit('ideation-type-complete', projectId, ideationType, parseInt(ideasCount, 10));
|
||||
@@ -217,7 +307,8 @@ export class AgentQueueManager {
|
||||
if (typeFailedMatch) {
|
||||
const [, ideationType] = typeFailedMatch;
|
||||
completedTypes.add(ideationType);
|
||||
console.log(`[Ideation] Type failed: ${ideationType}`);
|
||||
|
||||
debugError('[Agent Queue] Ideation type failed:', { projectId, ideationType });
|
||||
this.emitter.emit('ideation-type-failed', projectId, ideationType);
|
||||
}
|
||||
|
||||
@@ -242,9 +333,9 @@ export class AgentQueueManager {
|
||||
});
|
||||
});
|
||||
|
||||
// Handle stderr - also emit as logs
|
||||
// Handle stderr - also emit as logs, explicitly decode as UTF-8
|
||||
childProcess.stderr?.on('data', (data: Buffer) => {
|
||||
const log = data.toString();
|
||||
const log = data.toString('utf8');
|
||||
// Collect stderr for rate limit detection too
|
||||
allOutput = (allOutput + log).slice(-10000);
|
||||
console.error('[Ideation STDERR]', log);
|
||||
@@ -258,7 +349,16 @@ export class AgentQueueManager {
|
||||
|
||||
// Handle process exit
|
||||
childProcess.on('exit', (code: number | null) => {
|
||||
console.log('[Ideation] Process exited with code:', code);
|
||||
debugLog('[Agent Queue] Ideation process exited:', { projectId, code, spawnId });
|
||||
|
||||
// Check if this process was intentionally stopped by the user
|
||||
const wasIntentionallyStopped = this.state.wasSpawnKilled(spawnId);
|
||||
if (wasIntentionallyStopped) {
|
||||
debugLog('[Agent Queue] Ideation process was intentionally stopped, ignoring exit');
|
||||
this.state.clearKilledSpawn(spawnId);
|
||||
this.state.deleteProcess(projectId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the stored project path before deleting from map
|
||||
const processInfo = this.state.getProcess(projectId);
|
||||
@@ -267,8 +367,10 @@ export class AgentQueueManager {
|
||||
|
||||
// Check for rate limit if process failed
|
||||
if (code !== 0) {
|
||||
debugLog('[Agent Queue] Checking for rate limit (non-zero exit)');
|
||||
const rateLimitDetection = detectRateLimit(allOutput);
|
||||
if (rateLimitDetection.isRateLimited) {
|
||||
debugLog('[Agent Queue] Rate limit detected for ideation');
|
||||
const rateLimitInfo = createSDKRateLimitInfo('ideation', rateLimitDetection, {
|
||||
projectId
|
||||
});
|
||||
@@ -277,6 +379,7 @@ export class AgentQueueManager {
|
||||
}
|
||||
|
||||
if (code === 0) {
|
||||
debugLog('[Agent Queue] Ideation generation completed successfully');
|
||||
this.emitter.emit('ideation-progress', projectId, {
|
||||
phase: 'complete',
|
||||
progress: 100,
|
||||
@@ -292,19 +395,25 @@ export class AgentQueueManager {
|
||||
'ideation',
|
||||
'ideation.json'
|
||||
);
|
||||
debugLog('[Agent Queue] Loading ideation session from:', ideationFilePath);
|
||||
if (existsSync(ideationFilePath)) {
|
||||
const content = readFileSync(ideationFilePath, 'utf-8');
|
||||
const session = JSON.parse(content);
|
||||
console.log('[Ideation] Emitting ideation-complete with session data');
|
||||
debugLog('[Agent Queue] Loaded ideation session:', {
|
||||
totalIdeas: session.ideas?.length || 0
|
||||
});
|
||||
this.emitter.emit('ideation-complete', projectId, session);
|
||||
} else {
|
||||
debugError('[Ideation] ideation.json not found at:', ideationFilePath);
|
||||
console.warn('[Ideation] ideation.json not found at:', ideationFilePath);
|
||||
}
|
||||
} catch (err) {
|
||||
debugError('[Ideation] Failed to load ideation session:', err);
|
||||
console.error('[Ideation] Failed to load ideation session:', err);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
debugError('[Agent Queue] Ideation generation failed:', { projectId, code });
|
||||
this.emitter.emit('ideation-error', projectId, `Ideation generation failed with exit code ${code}`);
|
||||
}
|
||||
});
|
||||
@@ -325,11 +434,17 @@ export class AgentQueueManager {
|
||||
projectPath: string,
|
||||
args: string[]
|
||||
): void {
|
||||
debugLog('[Agent Queue] Spawning roadmap process:', { projectId, projectPath });
|
||||
|
||||
// Kill existing process for this project if any
|
||||
this.processManager.killProcess(projectId);
|
||||
const wasKilled = this.processManager.killProcess(projectId);
|
||||
if (wasKilled) {
|
||||
debugLog('[Agent Queue] Killed existing roadmap process for project:', projectId);
|
||||
}
|
||||
|
||||
// Generate unique spawn ID for this process instance
|
||||
const spawnId = this.state.generateSpawnId();
|
||||
debugLog('[Agent Queue] Generated roadmap spawn ID:', spawnId);
|
||||
|
||||
// Run from auto-claude source directory so imports work correctly
|
||||
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
|
||||
@@ -338,24 +453,44 @@ export class AgentQueueManager {
|
||||
// Get combined environment variables
|
||||
const combinedEnv = this.processManager.getCombinedEnv(projectPath);
|
||||
|
||||
// Get active Claude profile environment (CLAUDE_CONFIG_DIR if not default)
|
||||
// Get active Claude profile environment (CLAUDE_CODE_OAUTH_TOKEN if not default)
|
||||
const profileEnv = getProfileEnv();
|
||||
|
||||
// Get Python path from process manager (uses venv if configured)
|
||||
const pythonPath = this.processManager.getPythonPath();
|
||||
|
||||
console.log('[Roadmap] Starting roadmap process with args:', args);
|
||||
console.log('[Roadmap] CWD:', cwd);
|
||||
console.log('[Roadmap] Python path:', pythonPath);
|
||||
// Build final environment with proper precedence:
|
||||
// 1. process.env (system)
|
||||
// 2. combinedEnv (auto-claude/.env for CLI usage)
|
||||
// 3. profileEnv (Electron app OAuth token - highest priority)
|
||||
// 4. Our specific overrides
|
||||
const finalEnv = {
|
||||
...process.env,
|
||||
...combinedEnv,
|
||||
...profileEnv,
|
||||
PYTHONPATH: autoBuildSource || '', // Allow imports from auto-claude directory
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
};
|
||||
|
||||
const childProcess = spawn(pythonPath, args, {
|
||||
// Debug: Show OAuth token source
|
||||
const tokenSource = profileEnv['CLAUDE_CODE_OAUTH_TOKEN']
|
||||
? 'Electron app profile'
|
||||
: (combinedEnv['CLAUDE_CODE_OAUTH_TOKEN'] ? 'auto-claude/.env' : 'not found');
|
||||
const oauthToken = (finalEnv as Record<string, string | undefined>)['CLAUDE_CODE_OAUTH_TOKEN'];
|
||||
const hasToken = !!oauthToken;
|
||||
debugLog('[Agent Queue] OAuth token status:', {
|
||||
source: tokenSource,
|
||||
hasToken,
|
||||
tokenPreview: hasToken ? oauthToken?.substring(0, 20) + '...' : 'none'
|
||||
});
|
||||
|
||||
// Parse Python command to handle space-separated commands like "py -3"
|
||||
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(pythonPath);
|
||||
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, ...args], {
|
||||
cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...combinedEnv,
|
||||
...profileEnv,
|
||||
PYTHONUNBUFFERED: '1'
|
||||
}
|
||||
env: finalEnv
|
||||
});
|
||||
|
||||
this.state.addProcess(projectId, {
|
||||
@@ -363,7 +498,8 @@ export class AgentQueueManager {
|
||||
process: childProcess,
|
||||
startedAt: new Date(),
|
||||
projectPath, // Store project path for loading roadmap on completion
|
||||
spawnId
|
||||
spawnId,
|
||||
queueProcessType: 'roadmap'
|
||||
});
|
||||
|
||||
// Track progress through output
|
||||
@@ -378,15 +514,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 +541,9 @@ export class AgentQueueManager {
|
||||
});
|
||||
});
|
||||
|
||||
// Handle stderr
|
||||
// Handle stderr - explicitly decode as UTF-8
|
||||
childProcess.stderr?.on('data', (data: Buffer) => {
|
||||
const log = data.toString();
|
||||
const log = data.toString('utf8');
|
||||
// Collect stderr for rate limit detection too
|
||||
allRoadmapOutput = (allRoadmapOutput + log).slice(-10000);
|
||||
console.error('[Roadmap STDERR]', log);
|
||||
@@ -422,7 +557,16 @@ export class AgentQueueManager {
|
||||
|
||||
// Handle process exit
|
||||
childProcess.on('exit', (code: number | null) => {
|
||||
console.log('[Roadmap] Process exited with code:', code);
|
||||
debugLog('[Agent Queue] Roadmap process exited:', { projectId, code, spawnId });
|
||||
|
||||
// Check if this process was intentionally stopped by the user
|
||||
const wasIntentionallyStopped = this.state.wasSpawnKilled(spawnId);
|
||||
if (wasIntentionallyStopped) {
|
||||
debugLog('[Agent Queue] Roadmap process was intentionally stopped, ignoring exit');
|
||||
this.state.clearKilledSpawn(spawnId);
|
||||
this.state.deleteProcess(projectId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the stored project path before deleting from map
|
||||
const processInfo = this.state.getProcess(projectId);
|
||||
@@ -431,8 +575,10 @@ export class AgentQueueManager {
|
||||
|
||||
// Check for rate limit if process failed
|
||||
if (code !== 0) {
|
||||
debugLog('[Agent Queue] Checking for rate limit (non-zero exit)');
|
||||
const rateLimitDetection = detectRateLimit(allRoadmapOutput);
|
||||
if (rateLimitDetection.isRateLimited) {
|
||||
debugLog('[Agent Queue] Rate limit detected for roadmap');
|
||||
const rateLimitInfo = createSDKRateLimitInfo('roadmap', rateLimitDetection, {
|
||||
projectId
|
||||
});
|
||||
@@ -441,7 +587,7 @@ export class AgentQueueManager {
|
||||
}
|
||||
|
||||
if (code === 0) {
|
||||
console.log('[Roadmap] Roadmap generation completed successfully');
|
||||
debugLog('[Agent Queue] Roadmap generation completed successfully');
|
||||
this.emitter.emit('roadmap-progress', projectId, {
|
||||
phase: 'complete',
|
||||
progress: 100,
|
||||
@@ -457,20 +603,26 @@ export class AgentQueueManager {
|
||||
'roadmap',
|
||||
'roadmap.json'
|
||||
);
|
||||
debugLog('[Agent Queue] Loading roadmap from:', roadmapFilePath);
|
||||
if (existsSync(roadmapFilePath)) {
|
||||
const content = readFileSync(roadmapFilePath, 'utf-8');
|
||||
const roadmap = JSON.parse(content);
|
||||
console.log('[Roadmap] Emitting roadmap-complete with roadmap data');
|
||||
debugLog('[Agent Queue] Loaded roadmap:', {
|
||||
featuresCount: roadmap.features?.length || 0,
|
||||
phasesCount: roadmap.phases?.length || 0
|
||||
});
|
||||
this.emitter.emit('roadmap-complete', projectId, roadmap);
|
||||
} else {
|
||||
debugError('[Roadmap] roadmap.json not found at:', roadmapFilePath);
|
||||
console.warn('[Roadmap] roadmap.json not found at:', roadmapFilePath);
|
||||
}
|
||||
} catch (err) {
|
||||
debugError('[Roadmap] Failed to load roadmap:', err);
|
||||
console.error('[Roadmap] Failed to load roadmap:', err);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error('[Roadmap] Roadmap generation failed with exit code:', code);
|
||||
debugError('[Agent Queue] Roadmap generation failed:', { projectId, code });
|
||||
this.emitter.emit('roadmap-error', projectId, `Roadmap generation failed with exit code ${code}`);
|
||||
}
|
||||
});
|
||||
@@ -487,12 +639,19 @@ export class AgentQueueManager {
|
||||
* Stop ideation generation for a project
|
||||
*/
|
||||
stopIdeation(projectId: string): boolean {
|
||||
const wasRunning = this.state.hasProcess(projectId);
|
||||
if (wasRunning) {
|
||||
debugLog('[Agent Queue] Stop ideation requested:', { projectId });
|
||||
|
||||
const processInfo = this.state.getProcess(projectId);
|
||||
const isIdeation = processInfo?.queueProcessType === 'ideation';
|
||||
debugLog('[Agent Queue] Process running?', { projectId, isIdeation, processType: processInfo?.queueProcessType });
|
||||
|
||||
if (isIdeation) {
|
||||
debugLog('[Agent Queue] Killing ideation process:', projectId);
|
||||
this.processManager.killProcess(projectId);
|
||||
this.emitter.emit('ideation-stopped', projectId);
|
||||
return true;
|
||||
}
|
||||
debugLog('[Agent Queue] No running ideation process found for:', projectId);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -500,6 +659,35 @@ export class AgentQueueManager {
|
||||
* Check if ideation is running for a project
|
||||
*/
|
||||
isIdeationRunning(projectId: string): boolean {
|
||||
return this.state.hasProcess(projectId);
|
||||
const processInfo = this.state.getProcess(projectId);
|
||||
return processInfo?.queueProcessType === 'ideation';
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop roadmap generation for a project
|
||||
*/
|
||||
stopRoadmap(projectId: string): boolean {
|
||||
debugLog('[Agent Queue] Stop roadmap requested:', { projectId });
|
||||
|
||||
const processInfo = this.state.getProcess(projectId);
|
||||
const isRoadmap = processInfo?.queueProcessType === 'roadmap';
|
||||
debugLog('[Agent Queue] Roadmap process running?', { projectId, isRoadmap, processType: processInfo?.queueProcessType });
|
||||
|
||||
if (isRoadmap) {
|
||||
debugLog('[Agent Queue] Killing roadmap process:', projectId);
|
||||
this.processManager.killProcess(projectId);
|
||||
this.emitter.emit('roadmap-stopped', projectId);
|
||||
return true;
|
||||
}
|
||||
debugLog('[Agent Queue] No running roadmap process found for:', projectId);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if roadmap is running for a project
|
||||
*/
|
||||
isRoadmapRunning(projectId: string): boolean {
|
||||
const processInfo = this.state.getProcess(projectId);
|
||||
return processInfo?.queueProcessType === 'roadmap';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,9 +20,11 @@ export type {
|
||||
ExecutionProgressData,
|
||||
ProcessType,
|
||||
AgentManagerEvents,
|
||||
IdeationConfig,
|
||||
TaskExecutionOptions,
|
||||
SpecCreationMetadata,
|
||||
IdeationProgressData,
|
||||
RoadmapProgressData
|
||||
} from './types';
|
||||
|
||||
// Re-export IdeationConfig from shared types for consistency
|
||||
export type { IdeationConfig } from '../../shared/types';
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import { ChildProcess } from 'child_process';
|
||||
import type { IdeationConfig } from '../../shared/types';
|
||||
|
||||
/**
|
||||
* Agent-specific types for process and state management
|
||||
*/
|
||||
|
||||
export type QueueProcessType = 'ideation' | 'roadmap';
|
||||
|
||||
export interface AgentProcess {
|
||||
taskId: string;
|
||||
process: ChildProcess;
|
||||
startedAt: Date;
|
||||
projectPath?: string; // For ideation processes to load session on completion
|
||||
spawnId: number; // Unique ID to identify this specific spawn
|
||||
queueProcessType?: QueueProcessType; // Type of queue process (ideation or roadmap)
|
||||
}
|
||||
|
||||
export interface ExecutionProgressData {
|
||||
@@ -29,12 +33,11 @@ export interface AgentManagerEvents {
|
||||
'execution-progress': (taskId: string, progress: ExecutionProgressData) => void;
|
||||
}
|
||||
|
||||
export interface IdeationConfig {
|
||||
enabledTypes: string[];
|
||||
includeRoadmapContext: boolean;
|
||||
includeKanbanContext: boolean;
|
||||
maxIdeasPerType: number;
|
||||
append?: boolean;
|
||||
// IdeationConfig now imported from shared types to maintain consistency
|
||||
|
||||
export interface RoadmapConfig {
|
||||
model?: string; // Model shorthand (opus, sonnet, haiku)
|
||||
thinkingLevel?: string; // Thinking level (none, low, medium, high, ultrathink)
|
||||
}
|
||||
|
||||
export interface TaskExecutionOptions {
|
||||
@@ -45,6 +48,23 @@ export interface TaskExecutionOptions {
|
||||
|
||||
export interface SpecCreationMetadata {
|
||||
requireReviewBeforeCoding?: boolean;
|
||||
// Auto profile - phase-based model and thinking configuration
|
||||
isAutoProfile?: boolean;
|
||||
phaseModels?: {
|
||||
spec: 'haiku' | 'sonnet' | 'opus';
|
||||
planning: 'haiku' | 'sonnet' | 'opus';
|
||||
coding: 'haiku' | 'sonnet' | 'opus';
|
||||
qa: 'haiku' | 'sonnet' | 'opus';
|
||||
};
|
||||
phaseThinking?: {
|
||||
spec: 'none' | 'low' | 'medium' | 'high' | 'ultrathink';
|
||||
planning: 'none' | 'low' | 'medium' | 'high' | 'ultrathink';
|
||||
coding: 'none' | 'low' | 'medium' | 'high' | 'ultrathink';
|
||||
qa: 'none' | 'low' | 'medium' | 'high' | 'ultrathink';
|
||||
};
|
||||
// Non-auto profile - single model and thinking level
|
||||
model?: 'haiku' | 'sonnet' | 'opus';
|
||||
thinkingLevel?: 'none' | 'low' | 'medium' | 'high' | 'ultrathink';
|
||||
}
|
||||
|
||||
export interface IdeationProgressData {
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* API Validation Service
|
||||
*
|
||||
* Provides validation for external LLM API providers (OpenAI, Anthropic, Google, etc.)
|
||||
* Used by the Graphiti memory integration for embedding and LLM operations.
|
||||
*/
|
||||
|
||||
export interface ApiValidationResult {
|
||||
success: boolean;
|
||||
message: string;
|
||||
details?: {
|
||||
provider?: string;
|
||||
model?: string;
|
||||
latencyMs?: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate OpenAI API key by attempting to list models
|
||||
* @param apiKey - OpenAI API key
|
||||
*/
|
||||
export async function validateOpenAIApiKey(
|
||||
apiKey: string
|
||||
): Promise<ApiValidationResult> {
|
||||
if (!apiKey || !apiKey.trim()) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'API key is required',
|
||||
};
|
||||
}
|
||||
|
||||
// Basic format validation
|
||||
const trimmedKey = apiKey.trim();
|
||||
if (!trimmedKey.startsWith('sk-') && !trimmedKey.startsWith('sess-')) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Invalid API key format. OpenAI API keys should start with "sk-" or "sess-"',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const startTime = Date.now();
|
||||
|
||||
// Use native https module to avoid additional dependencies
|
||||
const result = await new Promise<ApiValidationResult>((resolve) => {
|
||||
const https = require('https');
|
||||
|
||||
const options = {
|
||||
hostname: 'api.openai.com',
|
||||
port: 443,
|
||||
path: '/v1/models',
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${trimmedKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: 15000,
|
||||
};
|
||||
|
||||
const req = https.request(options, (res: { statusCode: number; on: (event: string, callback: (chunk: Buffer) => void) => void }) => {
|
||||
let data = '';
|
||||
|
||||
res.on('data', (chunk: Buffer) => {
|
||||
data += chunk;
|
||||
});
|
||||
|
||||
res.on('end', () => {
|
||||
const latencyMs = Date.now() - startTime;
|
||||
|
||||
if (res.statusCode === 200) {
|
||||
resolve({
|
||||
success: true,
|
||||
message: 'OpenAI API key is valid',
|
||||
details: {
|
||||
provider: 'openai',
|
||||
latencyMs,
|
||||
},
|
||||
});
|
||||
} else if (res.statusCode === 401) {
|
||||
resolve({
|
||||
success: false,
|
||||
message: 'Invalid API key. Please check your OpenAI API key.',
|
||||
});
|
||||
} else if (res.statusCode === 429) {
|
||||
// Rate limited but key is valid
|
||||
resolve({
|
||||
success: true,
|
||||
message: 'OpenAI API key is valid (rate limited, please wait)',
|
||||
details: {
|
||||
provider: 'openai',
|
||||
latencyMs,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
const errorData = JSON.parse(data);
|
||||
resolve({
|
||||
success: false,
|
||||
message: errorData.error?.message || `API error: ${res.statusCode}`,
|
||||
});
|
||||
} catch {
|
||||
resolve({
|
||||
success: false,
|
||||
message: `API error: ${res.statusCode}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (error: Error) => {
|
||||
resolve({
|
||||
success: false,
|
||||
message: `Connection error: ${error.message}`,
|
||||
});
|
||||
});
|
||||
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
resolve({
|
||||
success: false,
|
||||
message: 'Connection timeout. Please check your network connection.',
|
||||
});
|
||||
});
|
||||
|
||||
req.end();
|
||||
});
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Unknown error occurred',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate Anthropic API key
|
||||
* @param apiKey - Anthropic API key
|
||||
*/
|
||||
export async function validateAnthropicApiKey(
|
||||
apiKey: string
|
||||
): Promise<ApiValidationResult> {
|
||||
if (!apiKey || !apiKey.trim()) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'API key is required',
|
||||
};
|
||||
}
|
||||
|
||||
const trimmedKey = apiKey.trim();
|
||||
if (!trimmedKey.startsWith('sk-ant-')) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Invalid API key format. Anthropic API keys should start with "sk-ant-"',
|
||||
};
|
||||
}
|
||||
|
||||
// For now, just validate format - full validation would require an API call
|
||||
return {
|
||||
success: true,
|
||||
message: 'Anthropic API key format is valid',
|
||||
details: {
|
||||
provider: 'anthropic',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate Google AI API key
|
||||
* @param apiKey - Google AI API key
|
||||
*/
|
||||
export async function validateGoogleApiKey(
|
||||
apiKey: string
|
||||
): Promise<ApiValidationResult> {
|
||||
if (!apiKey || !apiKey.trim()) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'API key is required',
|
||||
};
|
||||
}
|
||||
|
||||
const trimmedKey = apiKey.trim();
|
||||
if (!trimmedKey.startsWith('AIza')) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Invalid API key format. Google AI API keys should start with "AIza"',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'Google AI API key format is valid',
|
||||
details: {
|
||||
provider: 'google',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an LLM provider API key based on provider type
|
||||
* @param provider - The LLM provider (openai, anthropic, google, etc.)
|
||||
* @param apiKey - The API key to validate
|
||||
*/
|
||||
export async function validateLLMApiKey(
|
||||
provider: string,
|
||||
apiKey: string
|
||||
): Promise<ApiValidationResult> {
|
||||
switch (provider) {
|
||||
case 'openai':
|
||||
return validateOpenAIApiKey(apiKey);
|
||||
case 'anthropic':
|
||||
return validateAnthropicApiKey(apiKey);
|
||||
case 'google':
|
||||
return validateGoogleApiKey(apiKey);
|
||||
case 'ollama':
|
||||
// Ollama is local, no API key needed
|
||||
return {
|
||||
success: true,
|
||||
message: 'Ollama runs locally, no API key required',
|
||||
details: { provider: 'ollama' },
|
||||
};
|
||||
case 'azure_openai':
|
||||
// Azure OpenAI uses different auth, just validate presence
|
||||
if (!apiKey || !apiKey.trim()) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Azure OpenAI API key is required',
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
message: 'Azure OpenAI API key format accepted',
|
||||
details: { provider: 'azure_openai' },
|
||||
};
|
||||
default:
|
||||
return {
|
||||
success: false,
|
||||
message: `Unknown provider: ${provider}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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 - DEBUG_UPDATER=true or development mode
|
||||
const DEBUG_UPDATER = process.env.DEBUG_UPDATER === 'true' || process.env.NODE_ENV === 'development';
|
||||
|
||||
// Configure electron-updater
|
||||
autoUpdater.autoDownload = true; // Automatically download updates when available
|
||||
autoUpdater.autoInstallOnAppQuit = true; // Automatically install on app quit
|
||||
|
||||
// Enable more verbose logging in debug mode
|
||||
if (DEBUG_UPDATER) {
|
||||
autoUpdater.logger = {
|
||||
info: (msg: string) => console.warn('[app-updater:debug]', msg),
|
||||
warn: (msg: string) => console.warn('[app-updater:debug]', msg),
|
||||
error: (msg: string) => console.error('[app-updater:debug]', msg),
|
||||
debug: (msg: string) => console.warn('[app-updater:debug]', msg)
|
||||
};
|
||||
}
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
|
||||
/**
|
||||
* Initialize the app updater system
|
||||
*
|
||||
* Sets up event handlers and starts periodic update checks.
|
||||
* Should only be called in production (app.isPackaged).
|
||||
*
|
||||
* @param window - The main BrowserWindow for sending update events
|
||||
*/
|
||||
export function initializeAppUpdater(window: BrowserWindow): void {
|
||||
mainWindow = window;
|
||||
|
||||
// Log updater configuration
|
||||
console.warn('[app-updater] ========================================');
|
||||
console.warn('[app-updater] Initializing app auto-updater');
|
||||
console.warn('[app-updater] App packaged:', app.isPackaged);
|
||||
console.warn('[app-updater] Current version:', autoUpdater.currentVersion.version);
|
||||
console.warn('[app-updater] Auto-download enabled:', autoUpdater.autoDownload);
|
||||
console.warn('[app-updater] Debug mode:', DEBUG_UPDATER);
|
||||
console.warn('[app-updater] ========================================');
|
||||
|
||||
// ============================================
|
||||
// Event Handlers
|
||||
// ============================================
|
||||
|
||||
// Update available - new version found
|
||||
autoUpdater.on('update-available', (info) => {
|
||||
console.warn('[app-updater] Update available:', info.version);
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_AVAILABLE, {
|
||||
version: info.version,
|
||||
releaseNotes: info.releaseNotes,
|
||||
releaseDate: info.releaseDate
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Update downloaded - ready to install
|
||||
autoUpdater.on('update-downloaded', (info) => {
|
||||
console.warn('[app-updater] Update downloaded:', info.version);
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_DOWNLOADED, {
|
||||
version: info.version,
|
||||
releaseNotes: info.releaseNotes,
|
||||
releaseDate: info.releaseDate
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Download progress
|
||||
autoUpdater.on('download-progress', (progress) => {
|
||||
console.warn(`[app-updater] Download progress: ${progress.percent.toFixed(2)}%`);
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_PROGRESS, {
|
||||
percent: progress.percent,
|
||||
bytesPerSecond: progress.bytesPerSecond,
|
||||
transferred: progress.transferred,
|
||||
total: progress.total
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Error handling
|
||||
autoUpdater.on('error', (error) => {
|
||||
console.error('[app-updater] Update error:', error);
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.APP_UPDATE_ERROR, {
|
||||
message: error.message,
|
||||
stack: error.stack
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// No update available
|
||||
autoUpdater.on('update-not-available', (info) => {
|
||||
console.warn('[app-updater] No updates available - you are on the latest version');
|
||||
console.warn('[app-updater] Current version:', info.version);
|
||||
if (DEBUG_UPDATER) {
|
||||
console.warn('[app-updater:debug] Full info:', JSON.stringify(info, null, 2));
|
||||
}
|
||||
});
|
||||
|
||||
// Checking for updates
|
||||
autoUpdater.on('checking-for-update', () => {
|
||||
console.warn('[app-updater] Checking for updates...');
|
||||
});
|
||||
|
||||
// ============================================
|
||||
// Update Check Schedule
|
||||
// ============================================
|
||||
|
||||
// Check for updates 3 seconds after launch
|
||||
const INITIAL_DELAY = 3000;
|
||||
console.warn(`[app-updater] Will check for updates in ${INITIAL_DELAY / 1000} seconds...`);
|
||||
|
||||
setTimeout(() => {
|
||||
console.warn('[app-updater] Performing initial update check');
|
||||
autoUpdater.checkForUpdates().catch((error) => {
|
||||
console.error('[app-updater] ❌ Initial update check failed:', error.message);
|
||||
if (DEBUG_UPDATER) {
|
||||
console.error('[app-updater:debug] Full error:', error);
|
||||
}
|
||||
});
|
||||
}, INITIAL_DELAY);
|
||||
|
||||
// Check for updates every 4 hours
|
||||
const FOUR_HOURS = 4 * 60 * 60 * 1000;
|
||||
console.warn(`[app-updater] Periodic checks scheduled every ${FOUR_HOURS / 1000 / 60 / 60} hours`);
|
||||
|
||||
setInterval(() => {
|
||||
console.warn('[app-updater] Performing periodic update check');
|
||||
autoUpdater.checkForUpdates().catch((error) => {
|
||||
console.error('[app-updater] ❌ Periodic update check failed:', error.message);
|
||||
if (DEBUG_UPDATER) {
|
||||
console.error('[app-updater:debug] Full error:', error);
|
||||
}
|
||||
});
|
||||
}, FOUR_HOURS);
|
||||
|
||||
console.warn('[app-updater] Auto-updater initialized successfully');
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually check for updates
|
||||
* Called from IPC handler when user requests manual check
|
||||
*/
|
||||
export async function checkForUpdates(): Promise<AppUpdateInfo | null> {
|
||||
try {
|
||||
console.warn('[app-updater] Manual update check requested');
|
||||
const result = await autoUpdater.checkForUpdates();
|
||||
|
||||
if (!result) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const updateAvailable = result.updateInfo.version !== autoUpdater.currentVersion.version;
|
||||
|
||||
if (!updateAvailable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
version: result.updateInfo.version,
|
||||
releaseNotes: result.updateInfo.releaseNotes as string | undefined,
|
||||
releaseDate: result.updateInfo.releaseDate
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[app-updater] Manual update check failed:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually download update
|
||||
* Called from IPC handler when user requests manual download
|
||||
*/
|
||||
export async function downloadUpdate(): Promise<void> {
|
||||
try {
|
||||
console.warn('[app-updater] Manual update download requested');
|
||||
await autoUpdater.downloadUpdate();
|
||||
} catch (error) {
|
||||
console.error('[app-updater] Manual update download failed:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Quit and install update
|
||||
* Called from IPC handler when user confirms installation
|
||||
*/
|
||||
export function quitAndInstall(): void {
|
||||
console.warn('[app-updater] Quitting and installing update');
|
||||
autoUpdater.quitAndInstall(false, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current app version
|
||||
*/
|
||||
export function getCurrentVersion(): string {
|
||||
return autoUpdater.currentVersion.version;
|
||||
}
|
||||
@@ -27,7 +27,7 @@ export type {
|
||||
} from './updater/types';
|
||||
|
||||
// Export version management
|
||||
export { getBundledVersion } from './updater/version-manager';
|
||||
export { getBundledVersion, getEffectiveVersion } from './updater/version-manager';
|
||||
|
||||
// Export path resolution
|
||||
export {
|
||||
|
||||
@@ -27,13 +27,15 @@ import {
|
||||
getCommits,
|
||||
getBranchDiffCommits
|
||||
} from './git-integration';
|
||||
import { findPythonCommand } from '../python-detector';
|
||||
|
||||
/**
|
||||
* Main changelog service - orchestrates all changelog operations
|
||||
* Delegates to specialized modules for specific concerns
|
||||
*/
|
||||
export class ChangelogService extends EventEmitter {
|
||||
private pythonPath: string = 'python3';
|
||||
// Auto-detect Python command on initialization
|
||||
private pythonPath: string = findPythonCommand() || 'python';
|
||||
private claudePath: string = 'claude';
|
||||
private autoBuildSourcePath: string = '';
|
||||
private cachedEnv: Record<string, string> | null = null;
|
||||
@@ -89,7 +91,7 @@ export class ChangelogService extends EventEmitter {
|
||||
|
||||
/**
|
||||
* Check if debug mode is enabled
|
||||
* Checks DEBUG from auto-claude/.env and AUTO_CLAUDE_DEBUG from process.env
|
||||
* Checks DEBUG from auto-claude/.env and DEBUG from process.env
|
||||
*/
|
||||
private isDebugEnabled(): boolean {
|
||||
// Cache the result after first check
|
||||
@@ -101,8 +103,8 @@ export class ChangelogService extends EventEmitter {
|
||||
if (
|
||||
process.env.DEBUG === 'true' ||
|
||||
process.env.DEBUG === '1' ||
|
||||
process.env.AUTO_CLAUDE_DEBUG === 'true' ||
|
||||
process.env.AUTO_CLAUDE_DEBUG === '1'
|
||||
process.env.DEBUG === 'true' ||
|
||||
process.env.DEBUG === '1'
|
||||
) {
|
||||
this.debugEnabled = true;
|
||||
return true;
|
||||
@@ -115,11 +117,11 @@ export class ChangelogService extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Debug logging - only logs when DEBUG=true in auto-claude/.env or AUTO_CLAUDE_DEBUG is set
|
||||
* Debug logging - only logs when DEBUG=true in auto-claude/.env or DEBUG is set
|
||||
*/
|
||||
private debug(...args: unknown[]): void {
|
||||
if (this.isDebugEnabled()) {
|
||||
console.log('[ChangelogService]', ...args);
|
||||
console.warn('[ChangelogService]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +152,8 @@ export class ChangelogService extends EventEmitter {
|
||||
];
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
|
||||
// Use requirements.txt as marker - it always exists in auto-claude source
|
||||
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,11 @@ const FORMAT_TEMPLATES = {
|
||||
|
||||
## What's Changed
|
||||
|
||||
- type: description by @contributor in commit-hash`
|
||||
- type: description by @contributor in commit-hash
|
||||
|
||||
## Thanks to all contributors
|
||||
|
||||
@contributor1, @contributor2`
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -274,7 +278,15 @@ PART 2 - "What's Changed" (raw commit list):
|
||||
- Example: "- feat: add dark mode support by @contributor in def5678"
|
||||
- Include the commit type prefix (feat:, fix:, docs:, etc.)
|
||||
- Show the author name with @ prefix
|
||||
- Show the short commit hash at the end`;
|
||||
- Show the short commit hash at the end
|
||||
|
||||
PART 3 - "Thanks to all contributors" (deduplicated list):
|
||||
- Add this section after "What's Changed"
|
||||
- Extract all unique contributor names from the commits
|
||||
- List them in a comma-separated format with @ prefix
|
||||
- Example: "## Thanks to all contributors\\n\\n@contributor1, @contributor2, @contributor3"
|
||||
- Only include unique names (no duplicates)
|
||||
- This acknowledges everyone who contributed to this release`;
|
||||
}
|
||||
|
||||
return `${audienceInstruction}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { buildChangelogPrompt, buildGitPrompt, createGenerationScript } from './
|
||||
import { extractChangelog } from './parser';
|
||||
import { getCommits, getBranchDiffCommits } from './git-integration';
|
||||
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from '../rate-limit-detector';
|
||||
import { parsePythonCommand } from '../python-detector';
|
||||
|
||||
/**
|
||||
* Core changelog generation logic
|
||||
@@ -34,7 +35,7 @@ export class ChangelogGenerator extends EventEmitter {
|
||||
|
||||
private debug(...args: unknown[]): void {
|
||||
if (this.debugEnabled) {
|
||||
console.log('[ChangelogGenerator]', ...args);
|
||||
console.warn('[ChangelogGenerator]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,7 +140,9 @@ export class ChangelogGenerator extends EventEmitter {
|
||||
// Build environment with explicit critical variables
|
||||
const spawnEnv = this.buildSpawnEnvironment();
|
||||
|
||||
const childProcess = spawn(this.pythonPath, ['-c', script], {
|
||||
// Parse Python command to handle space-separated commands like "py -3"
|
||||
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.pythonPath);
|
||||
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, '-c', script], {
|
||||
cwd: this.autoBuildSourcePath,
|
||||
env: spawnEnv
|
||||
});
|
||||
@@ -277,7 +280,9 @@ export class ChangelogGenerator extends EventEmitter {
|
||||
USER: process.env.USER || process.env.USERNAME || 'user',
|
||||
// Add common binary locations to PATH for claude CLI
|
||||
PATH: [process.env.PATH || '', ...pathAdditions].filter(Boolean).join(path.delimiter),
|
||||
PYTHONUNBUFFERED: '1'
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
};
|
||||
|
||||
this.debug('Spawn environment', {
|
||||
|
||||
@@ -13,7 +13,7 @@ import { parseGitLogOutput } from './parser';
|
||||
*/
|
||||
function debug(enabled: boolean, ...args: unknown[]): void {
|
||||
if (enabled) {
|
||||
console.log('[GitIntegration]', ...args);
|
||||
console.warn('[GitIntegration]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export function extractSpecOverview(spec: string): string {
|
||||
// Handle both Unix (\n) and Windows (\r\n) line endings
|
||||
const lines = spec.split(/\r?\n/);
|
||||
let inOverview = false;
|
||||
let overview: string[] = [];
|
||||
const overview: string[] = [];
|
||||
|
||||
for (const line of lines) {
|
||||
// Start capturing at Overview heading
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import type { GitCommit } from '../../shared/types';
|
||||
import { getProfileEnv } from '../rate-limit-detector';
|
||||
import { parsePythonCommand } from '../python-detector';
|
||||
|
||||
interface VersionSuggestion {
|
||||
version: string;
|
||||
@@ -28,7 +29,7 @@ export class VersionSuggester {
|
||||
|
||||
private debug(...args: unknown[]): void {
|
||||
if (this.debugEnabled) {
|
||||
console.log('[VersionSuggester]', ...args);
|
||||
console.warn('[VersionSuggester]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,8 +52,10 @@ export class VersionSuggester {
|
||||
// Build environment
|
||||
const spawnEnv = this.buildSpawnEnvironment();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const childProcess = spawn(this.pythonPath, ['-c', script], {
|
||||
return new Promise((resolve, _reject) => {
|
||||
// Parse Python command to handle space-separated commands like "py -3"
|
||||
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.pythonPath);
|
||||
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, '-c', script], {
|
||||
cwd: this.autoBuildSourcePath,
|
||||
env: spawnEnv
|
||||
});
|
||||
@@ -237,7 +240,9 @@ except Exception as e:
|
||||
...(isWindows ? { USERPROFILE: homeDir } : { HOME: homeDir }),
|
||||
USER: process.env.USER || process.env.USERNAME || 'user',
|
||||
PATH: [process.env.PATH || '', ...pathAdditions].filter(Boolean).join(path.delimiter),
|
||||
PYTHONUNBUFFERED: '1'
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
};
|
||||
|
||||
return spawnEnv;
|
||||
|
||||
@@ -240,7 +240,7 @@ export class ClaudeProfileManager {
|
||||
|
||||
profile.name = newName.trim();
|
||||
this.save();
|
||||
console.log('[ClaudeProfileManager] Renamed profile:', profileId, 'to:', newName);
|
||||
console.warn('[ClaudeProfileManager] Renamed profile:', profileId, 'to:', newName);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -317,7 +317,7 @@ export class ClaudeProfileManager {
|
||||
this.save();
|
||||
|
||||
const isEncrypted = profile.oauthToken.startsWith('enc:');
|
||||
console.log('[ClaudeProfileManager] Set OAuth token for profile:', profile.name, {
|
||||
console.warn('[ClaudeProfileManager] Set OAuth token for profile:', profile.name, {
|
||||
email: email || '(not captured)',
|
||||
encrypted: isEncrypted,
|
||||
tokenLength: token.length
|
||||
@@ -350,14 +350,14 @@ export class ClaudeProfileManager {
|
||||
const decryptedToken = decryptToken(profile.oauthToken);
|
||||
if (decryptedToken) {
|
||||
env.CLAUDE_CODE_OAUTH_TOKEN = decryptedToken;
|
||||
console.log('[ClaudeProfileManager] Using OAuth token for profile:', profile.name);
|
||||
console.warn('[ClaudeProfileManager] Using OAuth token for profile:', profile.name);
|
||||
} else {
|
||||
console.warn('[ClaudeProfileManager] Failed to decrypt token for profile:', profile.name);
|
||||
}
|
||||
} else if (profile?.configDir && !profile.isDefault) {
|
||||
// Fallback to configDir for backward compatibility
|
||||
env.CLAUDE_CONFIG_DIR = profile.configDir;
|
||||
console.log('[ClaudeProfileManager] Using configDir for profile:', profile.name);
|
||||
console.warn('[ClaudeProfileManager] Using configDir for profile:', profile.name);
|
||||
}
|
||||
|
||||
return env;
|
||||
@@ -376,7 +376,7 @@ export class ClaudeProfileManager {
|
||||
profile.usage = usage;
|
||||
this.save();
|
||||
|
||||
console.log('[ClaudeProfileManager] Updated usage for', profile.name, ':', usage);
|
||||
console.warn('[ClaudeProfileManager] Updated usage for', profile.name, ':', usage);
|
||||
return usage;
|
||||
}
|
||||
|
||||
@@ -392,7 +392,7 @@ export class ClaudeProfileManager {
|
||||
const event = recordRateLimitEventImpl(profile, resetTimeStr);
|
||||
this.save();
|
||||
|
||||
console.log('[ClaudeProfileManager] Recorded rate limit event for', profile.name, ':', event);
|
||||
console.warn('[ClaudeProfileManager] Recorded rate limit event for', profile.name, ':', event);
|
||||
return event;
|
||||
}
|
||||
|
||||
@@ -451,6 +451,34 @@ export class ClaudeProfileManager {
|
||||
return isProfileAuthenticatedImpl(profile);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a profile has valid authentication for starting tasks.
|
||||
* A profile is considered authenticated if:
|
||||
* 1) It has a valid OAuth token (not expired), OR
|
||||
* 2) It has an authenticated configDir (credential files exist)
|
||||
*
|
||||
* @param profileId - Optional profile ID to check. If not provided, checks active profile.
|
||||
* @returns true if the profile can authenticate, false otherwise
|
||||
*/
|
||||
hasValidAuth(profileId?: string): boolean {
|
||||
const profile = profileId ? this.getProfile(profileId) : this.getActiveProfile();
|
||||
if (!profile) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check 1: Profile has a valid OAuth token
|
||||
if (hasValidToken(profile)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check 2 & 3: Profile has authenticated configDir (works for both default and non-default)
|
||||
if (this.isProfileAuthenticated(profile)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get environment variables for invoking Claude with a specific profile
|
||||
*/
|
||||
|
||||
@@ -86,12 +86,12 @@ export function getBestAvailableProfile(
|
||||
// Return the best candidate if it has a positive score
|
||||
const best = scoredProfiles[0];
|
||||
if (best && best.score > 0) {
|
||||
console.log('[ProfileScorer] Best available profile:', best.profile.name, 'score:', best.score);
|
||||
console.warn('[ProfileScorer] Best available profile:', best.profile.name, 'score:', best.score);
|
||||
return best.profile;
|
||||
}
|
||||
|
||||
// All profiles are rate-limited or have issues
|
||||
console.log('[ProfileScorer] No good profile available, all are rate-limited or have issues');
|
||||
console.warn('[ProfileScorer] No good profile available, all are rate-limited or have issues');
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -143,7 +143,7 @@ export function shouldProactivelySwitch(
|
||||
* Get profiles sorted by availability (best first)
|
||||
*/
|
||||
export function getProfilesSortedByAvailability(profiles: ClaudeProfile[]): ClaudeProfile[] {
|
||||
const now = new Date();
|
||||
const _now = new Date();
|
||||
|
||||
return [...profiles].sort((a, b) => {
|
||||
// Not rate-limited profiles first
|
||||
|
||||
@@ -117,7 +117,7 @@ export function hasValidToken(profile: ClaudeProfile): boolean {
|
||||
const oneYearAgo = new Date();
|
||||
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
|
||||
if (new Date(profile.tokenCreatedAt) < oneYearAgo) {
|
||||
console.log('[ProfileUtils] Token expired for profile:', profile.name);
|
||||
console.warn('[ProfileUtils] Token expired for profile:', profile.name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
|
||||
private constructor() {
|
||||
super();
|
||||
console.log('[UsageMonitor] Initialized');
|
||||
console.warn('[UsageMonitor] Initialized');
|
||||
}
|
||||
|
||||
static getInstance(): UsageMonitor {
|
||||
@@ -40,17 +40,17 @@ export class UsageMonitor extends EventEmitter {
|
||||
const settings = profileManager.getAutoSwitchSettings();
|
||||
|
||||
if (!settings.enabled || !settings.proactiveSwapEnabled) {
|
||||
console.log('[UsageMonitor] Proactive monitoring disabled');
|
||||
console.warn('[UsageMonitor] Proactive monitoring disabled');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.intervalId) {
|
||||
console.log('[UsageMonitor] Already running');
|
||||
console.warn('[UsageMonitor] Already running');
|
||||
return;
|
||||
}
|
||||
|
||||
const interval = settings.usageCheckInterval || 30000;
|
||||
console.log('[UsageMonitor] Starting with interval:', interval, 'ms');
|
||||
console.warn('[UsageMonitor] Starting with interval:', interval, 'ms');
|
||||
|
||||
// Check immediately
|
||||
this.checkUsageAndSwap();
|
||||
@@ -68,7 +68,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
if (this.intervalId) {
|
||||
clearInterval(this.intervalId);
|
||||
this.intervalId = null;
|
||||
console.log('[UsageMonitor] Stopped');
|
||||
console.warn('[UsageMonitor] Stopped');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,14 +94,16 @@ export class UsageMonitor extends EventEmitter {
|
||||
const activeProfile = profileManager.getActiveProfile();
|
||||
|
||||
if (!activeProfile) {
|
||||
console.log('[UsageMonitor] No active profile');
|
||||
console.warn('[UsageMonitor] No active profile');
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch current usage (hybrid approach)
|
||||
const usage = await this.fetchUsage(activeProfile.id, activeProfile.oauthToken);
|
||||
// Get decrypted token from ProfileManager (activeProfile.oauthToken is encrypted)
|
||||
const decryptedToken = profileManager.getProfileToken(activeProfile.id);
|
||||
const usage = await this.fetchUsage(activeProfile.id, decryptedToken ?? undefined);
|
||||
if (!usage) {
|
||||
console.log('[UsageMonitor] Failed to fetch usage');
|
||||
console.warn('[UsageMonitor] Failed to fetch usage');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -116,7 +118,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
const weeklyExceeded = usage.weeklyPercent >= settings.weeklyThreshold;
|
||||
|
||||
if (sessionExceeded || weeklyExceeded) {
|
||||
console.log('[UsageMonitor] Threshold exceeded:', {
|
||||
console.warn('[UsageMonitor] Threshold exceeded:', {
|
||||
sessionPercent: usage.sessionPercent,
|
||||
sessionThreshold: settings.sessionThreshold,
|
||||
weeklyPercent: usage.weeklyPercent,
|
||||
@@ -154,12 +156,12 @@ export class UsageMonitor extends EventEmitter {
|
||||
if (this.useApiMethod && oauthToken) {
|
||||
const apiUsage = await this.fetchUsageViaAPI(oauthToken, profileId, profile.name);
|
||||
if (apiUsage) {
|
||||
console.log('[UsageMonitor] Successfully fetched via API');
|
||||
console.warn('[UsageMonitor] Successfully fetched via API');
|
||||
return apiUsage;
|
||||
}
|
||||
|
||||
// API failed - switch to CLI method for future calls
|
||||
console.log('[UsageMonitor] API method failed, falling back to CLI');
|
||||
console.warn('[UsageMonitor] API method failed, falling back to CLI');
|
||||
this.useApiMethod = false;
|
||||
}
|
||||
|
||||
@@ -191,7 +193,12 @@ export class UsageMonitor extends EventEmitter {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data: any = await response.json();
|
||||
const data = await response.json() as {
|
||||
five_hour_utilization?: number;
|
||||
seven_day_utilization?: number;
|
||||
five_hour_reset_at?: string;
|
||||
seven_day_reset_at?: string;
|
||||
};
|
||||
|
||||
// Expected response format:
|
||||
// {
|
||||
@@ -232,7 +239,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
// CLI-based usage fetching is not implemented yet.
|
||||
// The API method should handle most cases. If we need CLI fallback,
|
||||
// we would need to spawn a Claude process with /usage command and parse the output.
|
||||
console.log('[UsageMonitor] CLI fallback not implemented, API method should be used');
|
||||
console.warn('[UsageMonitor] CLI fallback not implemented, API method should be used');
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -256,7 +263,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
const remainingHours = diffHours % 24;
|
||||
return `${diffDays}d ${remainingHours}h`;
|
||||
} catch (error) {
|
||||
} catch (_error) {
|
||||
return isoTimestamp;
|
||||
}
|
||||
}
|
||||
@@ -272,7 +279,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
const bestProfile = profileManager.getBestAvailableProfile(currentProfileId);
|
||||
|
||||
if (!bestProfile) {
|
||||
console.log('[UsageMonitor] No alternative profile for proactive swap');
|
||||
console.warn('[UsageMonitor] No alternative profile for proactive swap');
|
||||
this.emit('proactive-swap-failed', {
|
||||
reason: 'no_alternative',
|
||||
currentProfile: currentProfileId
|
||||
@@ -280,7 +287,7 @@ export class UsageMonitor extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[UsageMonitor] Proactive swap:', {
|
||||
console.warn('[UsageMonitor] Proactive swap:', {
|
||||
from: currentProfileId,
|
||||
to: bestProfile.id,
|
||||
reason: limitType
|
||||
|
||||
@@ -1,586 +0,0 @@
|
||||
/**
|
||||
* Docker & FalkorDB Service
|
||||
*
|
||||
* Provides automatic detection and management of Docker and FalkorDB
|
||||
* for non-technical users. This eliminates the need for manual
|
||||
* "docker --version" verification steps.
|
||||
*/
|
||||
|
||||
import { exec, spawn } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
// FalkorDB container configuration
|
||||
const FALKORDB_CONTAINER_NAME = 'auto-claude-falkordb';
|
||||
const FALKORDB_IMAGE = 'falkordb/falkordb:latest';
|
||||
const FALKORDB_DEFAULT_PORT = 6380;
|
||||
|
||||
export interface DockerStatus {
|
||||
installed: boolean;
|
||||
running: boolean;
|
||||
version?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface FalkorDBStatus {
|
||||
containerExists: boolean;
|
||||
containerRunning: boolean;
|
||||
containerName: string;
|
||||
port: number;
|
||||
healthy: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface InfrastructureStatus {
|
||||
docker: DockerStatus;
|
||||
falkordb: FalkorDBStatus;
|
||||
ready: boolean; // True if both Docker is running and FalkorDB is healthy
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if Docker is installed and running
|
||||
*/
|
||||
export async function checkDockerStatus(): Promise<DockerStatus> {
|
||||
try {
|
||||
// Check if Docker CLI is available
|
||||
const { stdout: versionOutput } = await execAsync('docker --version', {
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
const version = versionOutput.trim();
|
||||
|
||||
// Check if Docker daemon is running by trying to ping it
|
||||
try {
|
||||
await execAsync('docker info', { timeout: 10000 });
|
||||
return {
|
||||
installed: true,
|
||||
running: true,
|
||||
version,
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
installed: true,
|
||||
running: false,
|
||||
version,
|
||||
error: 'Docker is installed but not running. Please start Docker Desktop.',
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||
|
||||
// Check if it's a "command not found" type error
|
||||
if (
|
||||
errorMsg.includes('not found') ||
|
||||
errorMsg.includes('ENOENT') ||
|
||||
errorMsg.includes('not recognized')
|
||||
) {
|
||||
return {
|
||||
installed: false,
|
||||
running: false,
|
||||
error: 'Docker is not installed. Please install Docker Desktop.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
installed: false,
|
||||
running: false,
|
||||
error: `Docker check failed: ${errorMsg}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the actual port mapping for the FalkorDB container from Docker
|
||||
*/
|
||||
async function getContainerPortMapping(): Promise<number | null> {
|
||||
try {
|
||||
// Get the port mapping from Docker - format: "0.0.0.0:6380->6379/tcp"
|
||||
const { stdout } = await execAsync(
|
||||
`docker port ${FALKORDB_CONTAINER_NAME} 6379`,
|
||||
{ timeout: 5000 }
|
||||
);
|
||||
|
||||
const portMatch = stdout.trim().match(/:(\d+)/);
|
||||
if (portMatch) {
|
||||
return parseInt(portMatch[1], 10);
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check FalkorDB container status
|
||||
*/
|
||||
export async function checkFalkorDBStatus(port: number = FALKORDB_DEFAULT_PORT): Promise<FalkorDBStatus> {
|
||||
const status: FalkorDBStatus = {
|
||||
containerExists: false,
|
||||
containerRunning: false,
|
||||
containerName: FALKORDB_CONTAINER_NAME,
|
||||
port,
|
||||
healthy: false,
|
||||
};
|
||||
|
||||
try {
|
||||
// Check if container exists and get its status
|
||||
const { stdout } = await execAsync(
|
||||
`docker ps -a --filter "name=${FALKORDB_CONTAINER_NAME}" --format "{{.Status}}"`,
|
||||
{ timeout: 5000 }
|
||||
);
|
||||
|
||||
const containerStatus = stdout.trim();
|
||||
|
||||
if (containerStatus) {
|
||||
status.containerExists = true;
|
||||
status.containerRunning = containerStatus.toLowerCase().startsWith('up');
|
||||
|
||||
if (status.containerRunning) {
|
||||
// Get the actual port mapping from Docker
|
||||
const actualPort = await getContainerPortMapping();
|
||||
if (actualPort) {
|
||||
status.port = actualPort;
|
||||
}
|
||||
|
||||
// Check if FalkorDB is responding
|
||||
status.healthy = await checkFalkorDBHealth(status.port);
|
||||
}
|
||||
}
|
||||
|
||||
return status;
|
||||
} catch (error) {
|
||||
status.error = error instanceof Error ? error.message : String(error);
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if FalkorDB is responding to connections
|
||||
*/
|
||||
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
|
||||
await execAsync(`docker exec ${FALKORDB_CONTAINER_NAME} redis-cli PING`, {
|
||||
timeout: 5000,
|
||||
});
|
||||
return true;
|
||||
} catch {
|
||||
// Fallback: just check if container is running (less accurate)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get combined infrastructure status
|
||||
*/
|
||||
export async function getInfrastructureStatus(
|
||||
falkordbPort: number = FALKORDB_DEFAULT_PORT
|
||||
): Promise<InfrastructureStatus> {
|
||||
const [docker, falkordb] = await Promise.all([
|
||||
checkDockerStatus(),
|
||||
checkFalkorDBStatus(falkordbPort),
|
||||
]);
|
||||
|
||||
return {
|
||||
docker,
|
||||
falkordb,
|
||||
ready: docker.running && falkordb.containerRunning && falkordb.healthy,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Start FalkorDB container
|
||||
* Creates a new container if it doesn't exist, or starts the existing one
|
||||
*/
|
||||
export async function startFalkorDB(
|
||||
port: number = FALKORDB_DEFAULT_PORT
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
// First, check Docker status
|
||||
const dockerStatus = await checkDockerStatus();
|
||||
if (!dockerStatus.running) {
|
||||
return {
|
||||
success: false,
|
||||
error: dockerStatus.error || 'Docker is not running',
|
||||
};
|
||||
}
|
||||
|
||||
// Check if container already exists
|
||||
const falkordbStatus = await checkFalkorDBStatus(port);
|
||||
|
||||
if (falkordbStatus.containerExists) {
|
||||
if (falkordbStatus.containerRunning) {
|
||||
// Already running
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
// Start existing container
|
||||
await execAsync(`docker start ${FALKORDB_CONTAINER_NAME}`, { timeout: 30000 });
|
||||
} else {
|
||||
// Create and start new container
|
||||
await execAsync(
|
||||
`docker run -d --name ${FALKORDB_CONTAINER_NAME} -p ${port}:6379 ${FALKORDB_IMAGE}`,
|
||||
{ timeout: 60000 }
|
||||
);
|
||||
}
|
||||
|
||||
// Wait for FalkorDB to be ready (up to 30 seconds)
|
||||
const ready = await waitForFalkorDB(port, 30000);
|
||||
|
||||
if (!ready) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'FalkorDB container started but is not responding. Please check Docker logs.',
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop FalkorDB container
|
||||
*/
|
||||
export async function stopFalkorDB(): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
await execAsync(`docker stop ${FALKORDB_CONTAINER_NAME}`, { timeout: 30000 });
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for FalkorDB to be ready
|
||||
*/
|
||||
async function waitForFalkorDB(port: number, timeoutMs: number): Promise<boolean> {
|
||||
const startTime = Date.now();
|
||||
const checkInterval = 1000; // Check every second
|
||||
|
||||
while (Date.now() - startTime < timeoutMs) {
|
||||
const status = await checkFalkorDBStatus(port);
|
||||
if (status.containerRunning && status.healthy) {
|
||||
return true;
|
||||
}
|
||||
// If container is running but not healthy yet, wait
|
||||
if (status.containerRunning) {
|
||||
await new Promise((resolve) => setTimeout(resolve, checkInterval));
|
||||
} else {
|
||||
// Container stopped unexpectedly
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open Docker Desktop application (macOS/Windows)
|
||||
*/
|
||||
export async function openDockerDesktop(): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
if (process.platform === 'darwin') {
|
||||
// macOS
|
||||
await execAsync('open -a Docker', { timeout: 5000 });
|
||||
} else if (process.platform === 'win32') {
|
||||
// Windows
|
||||
spawn('cmd', ['/c', 'start', '', 'Docker Desktop'], {
|
||||
detached: true,
|
||||
stdio: 'ignore',
|
||||
});
|
||||
} else {
|
||||
// Linux - Docker doesn't have a GUI, suggest starting daemon
|
||||
return {
|
||||
success: false,
|
||||
error: 'On Linux, start Docker with: sudo systemctl start docker',
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get download URL for Docker Desktop
|
||||
*/
|
||||
export function getDockerDownloadUrl(): string {
|
||||
if (process.platform === 'darwin') {
|
||||
return 'https://www.docker.com/products/docker-desktop/';
|
||||
} else if (process.platform === 'win32') {
|
||||
return 'https://www.docker.com/products/docker-desktop/';
|
||||
}
|
||||
return 'https://docs.docker.com/engine/install/';
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Graphiti Validation Functions
|
||||
// ============================================
|
||||
|
||||
export interface GraphitiValidationResult {
|
||||
success: boolean;
|
||||
message: string;
|
||||
details?: {
|
||||
provider?: string;
|
||||
model?: string;
|
||||
latencyMs?: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate FalkorDB connection by attempting to connect and ping
|
||||
* @param uri - FalkorDB URI (e.g., "bolt://localhost:6380" or "redis://localhost:6380")
|
||||
*/
|
||||
export async function validateFalkorDBConnection(
|
||||
uri: string
|
||||
): Promise<GraphitiValidationResult> {
|
||||
try {
|
||||
// Parse the URI to extract host and port
|
||||
let host = 'localhost';
|
||||
let port = FALKORDB_DEFAULT_PORT;
|
||||
|
||||
// Support both bolt:// and redis:// protocols
|
||||
const uriMatch = uri.match(/^(?:bolt|redis):\/\/([^:]+):(\d+)/);
|
||||
if (uriMatch) {
|
||||
host = uriMatch[1];
|
||||
port = parseInt(uriMatch[2], 10);
|
||||
} else {
|
||||
// Try simple host:port format
|
||||
const simpleMatch = uri.match(/^([^:]+):(\d+)/);
|
||||
if (simpleMatch) {
|
||||
host = simpleMatch[1];
|
||||
port = parseInt(simpleMatch[2], 10);
|
||||
}
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
// First, check the actual FalkorDB container status to get the correct port
|
||||
const falkorStatus = await checkFalkorDBStatus(port);
|
||||
|
||||
// If container exists but user specified wrong port, try to detect the actual port
|
||||
if (!falkorStatus.containerRunning) {
|
||||
// Check if container is running on default port
|
||||
const defaultStatus = await checkFalkorDBStatus(FALKORDB_DEFAULT_PORT);
|
||||
if (defaultStatus.containerRunning && defaultStatus.healthy) {
|
||||
return {
|
||||
success: false,
|
||||
message: `FalkorDB is running on port ${FALKORDB_DEFAULT_PORT}, but you specified port ${port}. Please update the URI to bolt://localhost:${FALKORDB_DEFAULT_PORT}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
message: `FalkorDB container is not running. Please start FalkorDB first using Docker.`,
|
||||
};
|
||||
}
|
||||
|
||||
// Try to ping FalkorDB using redis-cli in Docker container
|
||||
try {
|
||||
const { stdout } = await execAsync(
|
||||
`docker exec ${FALKORDB_CONTAINER_NAME} redis-cli PING`,
|
||||
{ timeout: 10000 }
|
||||
);
|
||||
|
||||
if (stdout.trim().toUpperCase() === 'PONG') {
|
||||
const latencyMs = Date.now() - startTime;
|
||||
return {
|
||||
success: true,
|
||||
message: `Connected to FalkorDB at ${host}:${port}`,
|
||||
details: { latencyMs },
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// redis-cli failed, try port check as fallback
|
||||
}
|
||||
|
||||
// Fallback: check if the port is open using nc or direct connection
|
||||
try {
|
||||
// Check if we can connect to the mapped port from the host
|
||||
await execAsync(`nc -z -w 5 ${host} ${port}`, { timeout: 10000 });
|
||||
const latencyMs = Date.now() - startTime;
|
||||
return {
|
||||
success: true,
|
||||
message: `FalkorDB port ${port} is reachable at ${host}`,
|
||||
details: { latencyMs },
|
||||
};
|
||||
} catch {
|
||||
// Port check failed, but container is running - might be a different port mapping
|
||||
if (falkorStatus.containerRunning) {
|
||||
return {
|
||||
success: false,
|
||||
message: `FalkorDB container is running but port ${port} is not reachable. The container may be mapped to a different port.`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
message: `Cannot connect to FalkorDB at ${host}:${port}. Make sure FalkorDB is running.`,
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Unknown error occurred',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate OpenAI API key by attempting to list models
|
||||
* @param apiKey - OpenAI API key
|
||||
*/
|
||||
export async function validateOpenAIApiKey(
|
||||
apiKey: string
|
||||
): Promise<GraphitiValidationResult> {
|
||||
if (!apiKey || !apiKey.trim()) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'API key is required',
|
||||
};
|
||||
}
|
||||
|
||||
// Basic format validation
|
||||
const trimmedKey = apiKey.trim();
|
||||
if (!trimmedKey.startsWith('sk-') && !trimmedKey.startsWith('sess-')) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Invalid API key format. OpenAI API keys should start with "sk-"',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const startTime = Date.now();
|
||||
|
||||
// Use native https module to avoid additional dependencies
|
||||
const result = await new Promise<GraphitiValidationResult>((resolve) => {
|
||||
const https = require('https');
|
||||
|
||||
const options = {
|
||||
hostname: 'api.openai.com',
|
||||
port: 443,
|
||||
path: '/v1/models',
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${trimmedKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: 15000,
|
||||
};
|
||||
|
||||
const req = https.request(options, (res: any) => {
|
||||
let data = '';
|
||||
|
||||
res.on('data', (chunk: any) => {
|
||||
data += chunk;
|
||||
});
|
||||
|
||||
res.on('end', () => {
|
||||
const latencyMs = Date.now() - startTime;
|
||||
|
||||
if (res.statusCode === 200) {
|
||||
resolve({
|
||||
success: true,
|
||||
message: 'OpenAI API key is valid',
|
||||
details: {
|
||||
provider: 'openai',
|
||||
latencyMs,
|
||||
},
|
||||
});
|
||||
} else if (res.statusCode === 401) {
|
||||
resolve({
|
||||
success: false,
|
||||
message: 'Invalid API key. Please check your OpenAI API key.',
|
||||
});
|
||||
} else if (res.statusCode === 429) {
|
||||
// Rate limited but key is valid
|
||||
resolve({
|
||||
success: true,
|
||||
message: 'OpenAI API key is valid (rate limited, please wait)',
|
||||
details: {
|
||||
provider: 'openai',
|
||||
latencyMs,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
const errorData = JSON.parse(data);
|
||||
resolve({
|
||||
success: false,
|
||||
message: errorData.error?.message || `API error: ${res.statusCode}`,
|
||||
});
|
||||
} catch {
|
||||
resolve({
|
||||
success: false,
|
||||
message: `API error: ${res.statusCode}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (error: any) => {
|
||||
resolve({
|
||||
success: false,
|
||||
message: `Connection error: ${error.message}`,
|
||||
});
|
||||
});
|
||||
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
resolve({
|
||||
success: false,
|
||||
message: 'Connection timeout. Please check your network connection.',
|
||||
});
|
||||
});
|
||||
|
||||
req.end();
|
||||
});
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Unknown error occurred',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the full Graphiti connection (FalkorDB + OpenAI)
|
||||
* @param falkorDbUri - FalkorDB URI
|
||||
* @param openAiApiKey - OpenAI API key
|
||||
*/
|
||||
export async function testGraphitiConnection(
|
||||
falkorDbUri: string,
|
||||
openAiApiKey: string
|
||||
): Promise<{
|
||||
falkordb: GraphitiValidationResult;
|
||||
openai: GraphitiValidationResult;
|
||||
ready: boolean;
|
||||
}> {
|
||||
const [falkordb, openai] = await Promise.all([
|
||||
validateFalkorDBConnection(falkorDbUri),
|
||||
validateOpenAIApiKey(openAiApiKey),
|
||||
]);
|
||||
|
||||
return {
|
||||
falkordb,
|
||||
openai,
|
||||
ready: falkordb.success && openai.success,
|
||||
};
|
||||
}
|
||||
@@ -1,365 +0,0 @@
|
||||
/**
|
||||
* FalkorDB Service
|
||||
*
|
||||
* Queries the FalkorDB graph database for memories stored by Graphiti.
|
||||
* Uses ioredis to communicate with FalkorDB via Redis protocol.
|
||||
*/
|
||||
|
||||
import Redis from 'ioredis';
|
||||
import type { MemoryEpisode } from '../shared/types';
|
||||
|
||||
interface FalkorDBConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
password?: string;
|
||||
}
|
||||
|
||||
interface EpisodicNode {
|
||||
uuid: string;
|
||||
name: string;
|
||||
created_at: string;
|
||||
content?: string;
|
||||
source_description?: string;
|
||||
}
|
||||
|
||||
interface EntityNode {
|
||||
uuid: string;
|
||||
name: string;
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse FalkorDB GRAPH.QUERY results into structured data
|
||||
*/
|
||||
function parseGraphResult(result: unknown[]): Record<string, unknown>[] {
|
||||
if (!Array.isArray(result) || result.length < 2) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Result format: [headers, [row1, row2, ...], stats]
|
||||
const headers = result[0] as string[];
|
||||
const rows = result[1] as unknown[][];
|
||||
|
||||
if (!Array.isArray(headers) || !Array.isArray(rows)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return rows.map(row => {
|
||||
const obj: Record<string, unknown> = {};
|
||||
headers.forEach((header, idx) => {
|
||||
obj[header] = row[idx];
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* FalkorDB Service for querying graph memories
|
||||
*/
|
||||
export class FalkorDBService {
|
||||
private config: FalkorDBConfig;
|
||||
private redis: Redis | null = null;
|
||||
|
||||
constructor(config: FalkorDBConfig) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a Redis connection (lazy initialization)
|
||||
*/
|
||||
private async getConnection(): Promise<Redis> {
|
||||
if (this.redis) {
|
||||
return this.redis;
|
||||
}
|
||||
|
||||
this.redis = new Redis({
|
||||
host: this.config.host,
|
||||
port: this.config.port,
|
||||
password: this.config.password,
|
||||
lazyConnect: true,
|
||||
connectTimeout: 5000,
|
||||
maxRetriesPerRequest: 1,
|
||||
});
|
||||
|
||||
await this.redis.connect();
|
||||
return this.redis;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the Redis connection
|
||||
*/
|
||||
async close(): Promise<void> {
|
||||
if (this.redis) {
|
||||
await this.redis.quit();
|
||||
this.redis = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List all available graphs in the database
|
||||
*/
|
||||
async listGraphs(): Promise<string[]> {
|
||||
try {
|
||||
const redis = await this.getConnection();
|
||||
const result = await redis.call('GRAPH.LIST') as string[];
|
||||
return result || [];
|
||||
} catch (error) {
|
||||
console.error('Failed to list graphs:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Query episodic memories from a specific graph
|
||||
*/
|
||||
async getEpisodicMemories(graphName: string, limit: number = 20): Promise<MemoryEpisode[]> {
|
||||
try {
|
||||
const redis = await this.getConnection();
|
||||
|
||||
// Query episodic nodes with their details
|
||||
const query = `
|
||||
MATCH (e:Episodic)
|
||||
RETURN e.uuid as uuid, e.name as name, e.created_at as created_at,
|
||||
e.content as content, e.source_description as description
|
||||
ORDER BY e.created_at DESC
|
||||
LIMIT ${limit}
|
||||
`;
|
||||
|
||||
const result = await redis.call('GRAPH.QUERY', graphName, query) as unknown[];
|
||||
const episodes = parseGraphResult(result) as unknown as EpisodicNode[];
|
||||
|
||||
return episodes.map(ep => ({
|
||||
id: ep.uuid || ep.name,
|
||||
type: this.inferEpisodeType(ep.name, ep.content),
|
||||
timestamp: ep.created_at || new Date().toISOString(),
|
||||
content: ep.content || ep.source_description || ep.name,
|
||||
session_number: this.extractSessionNumber(ep.name),
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error(`Failed to get episodic memories from ${graphName}:`, error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Query entity memories (patterns, gotchas, etc.) from a graph
|
||||
*/
|
||||
async getEntityMemories(graphName: string, limit: number = 20): Promise<MemoryEpisode[]> {
|
||||
try {
|
||||
const redis = await this.getConnection();
|
||||
|
||||
// Query entity nodes
|
||||
const query = `
|
||||
MATCH (e:Entity)
|
||||
RETURN e.uuid as uuid, e.name as name, e.summary as summary, e.created_at as created_at
|
||||
ORDER BY e.created_at DESC
|
||||
LIMIT ${limit}
|
||||
`;
|
||||
|
||||
const result = await redis.call('GRAPH.QUERY', graphName, query) as unknown[];
|
||||
const entities = parseGraphResult(result) as unknown as EntityNode[];
|
||||
|
||||
return entities
|
||||
.filter(ent => ent.summary) // Only include entities with summaries
|
||||
.map(ent => ({
|
||||
id: ent.uuid || ent.name,
|
||||
type: this.inferEntityType(ent.name),
|
||||
timestamp: new Date().toISOString(),
|
||||
content: ent.summary || ent.name,
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error(`Failed to get entity memories from ${graphName}:`, error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all memories from all spec-related graphs
|
||||
*/
|
||||
async getAllMemories(limit: number = 20): Promise<MemoryEpisode[]> {
|
||||
const graphs = await this.listGraphs();
|
||||
const memories: MemoryEpisode[] = [];
|
||||
|
||||
// Filter to spec-related graphs (exclude auto_build_memory and project_ prefixed)
|
||||
const specGraphs = graphs.filter(g =>
|
||||
!g.startsWith('project_') &&
|
||||
g !== 'auto_build_memory' &&
|
||||
g !== 'default_db'
|
||||
);
|
||||
|
||||
for (const graph of specGraphs) {
|
||||
const episodic = await this.getEpisodicMemories(graph, Math.ceil(limit / specGraphs.length));
|
||||
memories.push(...episodic.map(m => ({ ...m, id: `${graph}:${m.id}` })));
|
||||
}
|
||||
|
||||
// Sort by timestamp descending
|
||||
memories.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
|
||||
|
||||
return memories.slice(0, limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search memories across all graphs
|
||||
*/
|
||||
async searchMemories(query: string, limit: number = 20): Promise<MemoryEpisode[]> {
|
||||
const graphs = await this.listGraphs();
|
||||
const results: MemoryEpisode[] = [];
|
||||
const queryLower = query.toLowerCase();
|
||||
|
||||
// Filter to spec-related graphs
|
||||
const specGraphs = graphs.filter(g =>
|
||||
!g.startsWith('project_') &&
|
||||
g !== 'auto_build_memory' &&
|
||||
g !== 'default_db'
|
||||
);
|
||||
|
||||
for (const graph of specGraphs) {
|
||||
try {
|
||||
const redis = await this.getConnection();
|
||||
|
||||
// Search in episodic nodes
|
||||
const episodicQuery = `
|
||||
MATCH (e:Episodic)
|
||||
WHERE toLower(e.name) CONTAINS '${queryLower}' OR toLower(e.content) CONTAINS '${queryLower}'
|
||||
RETURN e.uuid as uuid, e.name as name, e.created_at as created_at,
|
||||
e.content as content, e.source_description as description
|
||||
LIMIT ${Math.ceil(limit / specGraphs.length)}
|
||||
`;
|
||||
|
||||
const episodicResult = await redis.call('GRAPH.QUERY', graph, episodicQuery) as unknown[];
|
||||
const episodes = parseGraphResult(episodicResult) as unknown as EpisodicNode[];
|
||||
|
||||
results.push(...episodes.map(ep => ({
|
||||
id: `${graph}:${ep.uuid || ep.name}`,
|
||||
type: this.inferEpisodeType(ep.name, ep.content),
|
||||
timestamp: ep.created_at || new Date().toISOString(),
|
||||
content: ep.content || ep.source_description || ep.name,
|
||||
session_number: this.extractSessionNumber(ep.name),
|
||||
score: 1.0,
|
||||
})));
|
||||
|
||||
// Search in entity nodes
|
||||
const entityQuery = `
|
||||
MATCH (e:Entity)
|
||||
WHERE toLower(e.name) CONTAINS '${queryLower}' OR toLower(e.summary) CONTAINS '${queryLower}'
|
||||
RETURN e.uuid as uuid, e.name as name, e.summary as summary
|
||||
LIMIT ${Math.ceil(limit / specGraphs.length)}
|
||||
`;
|
||||
|
||||
const entityResult = await redis.call('GRAPH.QUERY', graph, entityQuery) as unknown[];
|
||||
const entities = parseGraphResult(entityResult) as unknown as EntityNode[];
|
||||
|
||||
results.push(...entities
|
||||
.filter(ent => ent.summary)
|
||||
.map(ent => ({
|
||||
id: `${graph}:${ent.uuid || ent.name}`,
|
||||
type: this.inferEntityType(ent.name),
|
||||
timestamp: new Date().toISOString(),
|
||||
content: ent.summary || ent.name,
|
||||
score: 1.0,
|
||||
})));
|
||||
} catch (error) {
|
||||
console.error(`Failed to search memories in ${graph}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return results.slice(0, limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test connection to FalkorDB
|
||||
*/
|
||||
async testConnection(): Promise<{ success: boolean; message: string }> {
|
||||
try {
|
||||
const redis = await this.getConnection();
|
||||
await redis.ping();
|
||||
const graphs = await this.listGraphs();
|
||||
return {
|
||||
success: true,
|
||||
message: `Connected to FalkorDB with ${graphs.length} graphs`,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Connection failed',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer the episode type from its name
|
||||
*/
|
||||
private inferEpisodeType(name: string, content?: string): MemoryEpisode['type'] {
|
||||
const nameLower = (name || '').toLowerCase();
|
||||
const contentLower = (content || '').toLowerCase();
|
||||
|
||||
if (nameLower.includes('session_') || contentLower.includes('"type": "session_insight"')) {
|
||||
return 'session_insight';
|
||||
}
|
||||
if (nameLower.includes('pattern') || contentLower.includes('"type": "pattern"')) {
|
||||
return 'pattern';
|
||||
}
|
||||
if (nameLower.includes('gotcha') || contentLower.includes('"type": "gotcha"')) {
|
||||
return 'gotcha';
|
||||
}
|
||||
if (nameLower.includes('codebase') || contentLower.includes('"type": "codebase_discovery"')) {
|
||||
return 'codebase_discovery';
|
||||
}
|
||||
return 'session_insight';
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer the entity type from its name
|
||||
*/
|
||||
private inferEntityType(name: string): MemoryEpisode['type'] {
|
||||
const nameLower = (name || '').toLowerCase();
|
||||
|
||||
if (nameLower.includes('pattern')) {
|
||||
return 'pattern';
|
||||
}
|
||||
if (nameLower.includes('gotcha')) {
|
||||
return 'gotcha';
|
||||
}
|
||||
if (nameLower.includes('file_insight') || nameLower.includes('codebase')) {
|
||||
return 'codebase_discovery';
|
||||
}
|
||||
return 'session_insight';
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract session number from episode name
|
||||
*/
|
||||
private extractSessionNumber(name: string): number | undefined {
|
||||
const match = name.match(/session_(\d+)/i);
|
||||
return match ? parseInt(match[1], 10) : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton instance for reuse
|
||||
let serviceInstance: FalkorDBService | null = null;
|
||||
|
||||
/**
|
||||
* Get or create a FalkorDB service instance
|
||||
*/
|
||||
export function getFalkorDBService(config: FalkorDBConfig): FalkorDBService {
|
||||
if (!serviceInstance ||
|
||||
serviceInstance['config'].host !== config.host ||
|
||||
serviceInstance['config'].port !== config.port) {
|
||||
// Close existing connection if config changed
|
||||
if (serviceInstance) {
|
||||
serviceInstance.close().catch(() => {});
|
||||
}
|
||||
serviceInstance = new FalkorDBService(config);
|
||||
}
|
||||
return serviceInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the singleton service instance
|
||||
*/
|
||||
export async function closeFalkorDBService(): Promise<void> {
|
||||
if (serviceInstance) {
|
||||
await serviceInstance.close();
|
||||
serviceInstance = null;
|
||||
}
|
||||
}
|
||||
@@ -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,32 @@ app.whenReady().then(() => {
|
||||
// Start the usage monitor
|
||||
const usageMonitor = getUsageMonitor();
|
||||
usageMonitor.start();
|
||||
console.log('[main] Usage monitor initialized and started');
|
||||
console.warn('[main] Usage monitor initialized and started');
|
||||
|
||||
// Log debug mode status
|
||||
const isDebugMode = process.env.DEBUG === 'true';
|
||||
if (isDebugMode) {
|
||||
console.warn('[main] ========================================');
|
||||
console.warn('[main] DEBUG MODE ENABLED (DEBUG=true)');
|
||||
console.warn('[main] ========================================');
|
||||
}
|
||||
|
||||
// Initialize app auto-updater (only in production, or when DEBUG_UPDATER is set)
|
||||
const forceUpdater = process.env.DEBUG_UPDATER === 'true';
|
||||
if (app.isPackaged || forceUpdater) {
|
||||
initializeAppUpdater(mainWindow);
|
||||
console.warn('[main] App auto-updater initialized');
|
||||
if (forceUpdater && !app.isPackaged) {
|
||||
console.warn('[main] Updater forced in dev mode via DEBUG_UPDATER=true');
|
||||
console.warn('[main] Note: Updates won\'t actually work in dev mode');
|
||||
}
|
||||
} else {
|
||||
console.warn('[main] ========================================');
|
||||
console.warn('[main] App auto-updater DISABLED (development mode)');
|
||||
console.warn('[main] To test updater logging, set DEBUG_UPDATER=true');
|
||||
console.warn('[main] Note: Actual updates only work in packaged builds');
|
||||
console.warn('[main] ========================================');
|
||||
}
|
||||
}
|
||||
|
||||
// macOS: re-create window when dock icon is clicked
|
||||
@@ -159,7 +185,7 @@ app.on('before-quit', async () => {
|
||||
// Stop usage monitor
|
||||
const usageMonitor = getUsageMonitor();
|
||||
usageMonitor.stop();
|
||||
console.log('[main] Usage monitor stopped');
|
||||
console.warn('[main] Usage monitor stopped');
|
||||
|
||||
// Kill all running agent processes
|
||||
if (agentManager) {
|
||||
|
||||
@@ -3,9 +3,7 @@ import type {
|
||||
InsightsSession,
|
||||
InsightsSessionSummary,
|
||||
InsightsChatMessage,
|
||||
InsightsChatStatus,
|
||||
InsightsStreamChunk,
|
||||
InsightsToolUsage
|
||||
InsightsModelConfig
|
||||
} from '../shared/types';
|
||||
import { InsightsConfig } from './insights/config';
|
||||
import { InsightsPaths } from './insights/paths';
|
||||
@@ -114,7 +112,12 @@ export class InsightsService extends EventEmitter {
|
||||
/**
|
||||
* Send a message and get AI response
|
||||
*/
|
||||
async sendMessage(projectId: string, projectPath: string, message: string): Promise<void> {
|
||||
async sendMessage(
|
||||
projectId: string,
|
||||
projectPath: string,
|
||||
message: string,
|
||||
modelConfig?: InsightsModelConfig
|
||||
): Promise<void> {
|
||||
// Cancel any existing session
|
||||
this.executor.cancelSession(projectId);
|
||||
|
||||
@@ -153,13 +156,17 @@ export class InsightsService extends EventEmitter {
|
||||
content: m.content
|
||||
}));
|
||||
|
||||
// Use provided modelConfig or fall back to session's config
|
||||
const configToUse = modelConfig || session.modelConfig;
|
||||
|
||||
try {
|
||||
// Execute insights query
|
||||
const result = await this.executor.execute(
|
||||
projectId,
|
||||
projectPath,
|
||||
message,
|
||||
conversationHistory
|
||||
conversationHistory,
|
||||
configToUse
|
||||
);
|
||||
|
||||
// Add assistant message to session
|
||||
@@ -180,6 +187,13 @@ export class InsightsService extends EventEmitter {
|
||||
console.error('[InsightsService] Error executing insights:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update model configuration for a session
|
||||
*/
|
||||
updateSessionModelConfig(projectPath: string, sessionId: string, modelConfig: InsightsModelConfig): boolean {
|
||||
return this.sessionManager.updateSessionModelConfig(projectPath, sessionId, modelConfig);
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton instance
|
||||
|
||||
@@ -2,13 +2,15 @@ import path from 'path';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { app } from 'electron';
|
||||
import { getProfileEnv } from '../rate-limit-detector';
|
||||
import { findPythonCommand } from '../python-detector';
|
||||
|
||||
/**
|
||||
* Configuration manager for insights service
|
||||
* Handles path detection and environment variable loading
|
||||
*/
|
||||
export class InsightsConfig {
|
||||
private pythonPath: string = 'python3';
|
||||
// Auto-detect Python command on initialization
|
||||
private pythonPath: string = findPythonCommand() || 'python';
|
||||
private autoBuildSourcePath: string = '';
|
||||
|
||||
/**
|
||||
@@ -45,7 +47,8 @@ export class InsightsConfig {
|
||||
];
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
|
||||
// Use requirements.txt as marker - it always exists in auto-claude source
|
||||
if (existsSync(p) && existsSync(path.join(p, 'requirements.txt'))) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
@@ -103,7 +106,9 @@ export class InsightsConfig {
|
||||
...process.env as Record<string, string>,
|
||||
...autoBuildEnv,
|
||||
...profileEnv,
|
||||
PYTHONUNBUFFERED: '1'
|
||||
PYTHONUNBUFFERED: '1',
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { spawn, ChildProcess } from 'child_process';
|
||||
import { existsSync } from 'fs';
|
||||
import { existsSync, writeFileSync, unlinkSync } from 'fs';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import { EventEmitter } from 'events';
|
||||
import type {
|
||||
InsightsChatMessage,
|
||||
InsightsChatStatus,
|
||||
InsightsStreamChunk,
|
||||
InsightsToolUsage
|
||||
InsightsToolUsage,
|
||||
InsightsModelConfig
|
||||
} from '../../shared/types';
|
||||
import { MODEL_ID_MAP } from '../../shared/constants';
|
||||
import { InsightsConfig } from './config';
|
||||
import { detectRateLimit, createSDKRateLimitInfo } from '../rate-limit-detector';
|
||||
|
||||
@@ -59,7 +62,8 @@ export class InsightsExecutor extends EventEmitter {
|
||||
projectId: string,
|
||||
projectPath: string,
|
||||
message: string,
|
||||
conversationHistory: Array<{ role: string; content: string }>
|
||||
conversationHistory: Array<{ role: string; content: string }>,
|
||||
modelConfig?: InsightsModelConfig
|
||||
): Promise<ProcessorResult> {
|
||||
// Cancel any existing session
|
||||
this.cancelSession(projectId);
|
||||
@@ -69,7 +73,7 @@ export class InsightsExecutor extends EventEmitter {
|
||||
throw new Error('Auto Claude source not found');
|
||||
}
|
||||
|
||||
const runnerPath = path.join(autoBuildSource, 'insights_runner.py');
|
||||
const runnerPath = path.join(autoBuildSource, 'runners', 'insights_runner.py');
|
||||
if (!existsSync(runnerPath)) {
|
||||
throw new Error('insights_runner.py not found in auto-claude directory');
|
||||
}
|
||||
@@ -83,13 +87,38 @@ export class InsightsExecutor extends EventEmitter {
|
||||
// Get process environment
|
||||
const processEnv = this.config.getProcessEnv();
|
||||
|
||||
// Spawn Python process
|
||||
const proc = spawn(this.config.getPythonPath(), [
|
||||
// Write conversation history to temp file to avoid Windows command-line length limit
|
||||
const historyFile = path.join(
|
||||
os.tmpdir(),
|
||||
`insights-history-${projectId}-${Date.now()}.json`
|
||||
);
|
||||
|
||||
let historyFileCreated = false;
|
||||
try {
|
||||
writeFileSync(historyFile, JSON.stringify(conversationHistory), 'utf-8');
|
||||
historyFileCreated = true;
|
||||
} catch (err) {
|
||||
console.error('[Insights] Failed to write history file:', err);
|
||||
throw new Error('Failed to write conversation history to temp file');
|
||||
}
|
||||
|
||||
// Build command arguments
|
||||
const args = [
|
||||
runnerPath,
|
||||
'--project-dir', projectPath,
|
||||
'--message', message,
|
||||
'--history', JSON.stringify(conversationHistory)
|
||||
], {
|
||||
'--history-file', historyFile
|
||||
];
|
||||
|
||||
// Add model config if provided
|
||||
if (modelConfig) {
|
||||
const modelId = MODEL_ID_MAP[modelConfig.model] || MODEL_ID_MAP['sonnet'];
|
||||
args.push('--model', modelId);
|
||||
args.push('--thinking-level', modelConfig.thinkingLevel);
|
||||
}
|
||||
|
||||
// Spawn Python process
|
||||
const proc = spawn(this.config.getPythonPath(), args, {
|
||||
cwd: autoBuildSource,
|
||||
env: processEnv
|
||||
});
|
||||
@@ -138,6 +167,15 @@ export class InsightsExecutor extends EventEmitter {
|
||||
proc.on('close', (code) => {
|
||||
this.activeSessions.delete(projectId);
|
||||
|
||||
// Cleanup temp file
|
||||
if (historyFileCreated && existsSync(historyFile)) {
|
||||
try {
|
||||
unlinkSync(historyFile);
|
||||
} catch (cleanupErr) {
|
||||
console.error('[Insights] Failed to cleanup history file:', cleanupErr);
|
||||
}
|
||||
}
|
||||
|
||||
// Check for rate limit if process failed
|
||||
if (code !== 0) {
|
||||
this.handleRateLimit(projectId, allInsightsOutput);
|
||||
@@ -171,6 +209,16 @@ export class InsightsExecutor extends EventEmitter {
|
||||
|
||||
proc.on('error', (err) => {
|
||||
this.activeSessions.delete(projectId);
|
||||
|
||||
// Cleanup temp file
|
||||
if (historyFileCreated && existsSync(historyFile)) {
|
||||
try {
|
||||
unlinkSync(historyFile);
|
||||
} catch (cleanupErr) {
|
||||
console.error('[Insights] Failed to cleanup history file:', cleanupErr);
|
||||
}
|
||||
}
|
||||
|
||||
this.emit('error', projectId, err.message);
|
||||
reject(err);
|
||||
});
|
||||
@@ -251,7 +299,7 @@ export class InsightsExecutor extends EventEmitter {
|
||||
private handleRateLimit(projectId: string, output: string): void {
|
||||
const rateLimitDetection = detectRateLimit(output);
|
||||
if (rateLimitDetection.isRateLimited) {
|
||||
console.log('[Insights] Rate limit detected:', {
|
||||
console.warn('[Insights] Rate limit detected:', {
|
||||
projectId,
|
||||
resetTime: rateLimitDetection.resetTime,
|
||||
limitType: rateLimitDetection.limitType,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { InsightsSession, InsightsSessionSummary } from '../../shared/types';
|
||||
import type { InsightsSession, InsightsSessionSummary, InsightsModelConfig } from '../../shared/types';
|
||||
import { SessionStorage } from './session-storage';
|
||||
import { InsightsPaths } from './paths';
|
||||
|
||||
@@ -119,6 +119,30 @@ export class SessionManager {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update model configuration for a session
|
||||
*/
|
||||
updateSessionModelConfig(projectPath: string, sessionId: string, modelConfig: InsightsModelConfig): boolean {
|
||||
const session = this.storage.loadSessionById(projectPath, sessionId);
|
||||
if (!session) return false;
|
||||
|
||||
session.modelConfig = modelConfig;
|
||||
session.updatedAt = new Date();
|
||||
this.storage.saveSession(projectPath, session);
|
||||
|
||||
// Update cache if this session is cached
|
||||
for (const [projectId, cachedSession] of this.sessions) {
|
||||
if (cachedSession.id === sessionId) {
|
||||
cachedSession.modelConfig = modelConfig;
|
||||
cachedSession.updatedAt = new Date();
|
||||
this.sessions.set(projectId, cachedSession);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save session to disk and update cache
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Integration module for external roadmap/feedback services
|
||||
*
|
||||
* Currently provides architecture for future integrations with:
|
||||
* - Canny.io (feedback management)
|
||||
* - GitHub Issues
|
||||
*
|
||||
* To add a new integration:
|
||||
* 1. Implement the IntegrationAdapter interface
|
||||
* 2. Add status mapping constants
|
||||
* 3. Register the adapter in this module
|
||||
*/
|
||||
|
||||
export * from './types';
|
||||
|
||||
// Future: Export concrete adapter implementations
|
||||
// export { CannyAdapter } from './canny-adapter';
|
||||
// export { GitHubIssuesAdapter } from './github-issues-adapter';
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Integration provider types for external roadmap services (Canny, GitHub Issues, etc.)
|
||||
*
|
||||
* This architecture allows bidirectional sync with external feedback/roadmap systems:
|
||||
* - Import: Fetch feature requests from external services
|
||||
* - Export: Push status updates back when features progress
|
||||
*/
|
||||
|
||||
import type { RoadmapFeatureStatus } from '../../shared/types';
|
||||
|
||||
/**
|
||||
* Represents an item from an external feedback/roadmap system
|
||||
*/
|
||||
export interface FeedbackItem {
|
||||
externalId: string;
|
||||
title: string;
|
||||
description: string;
|
||||
votes: number;
|
||||
status: string; // Provider-specific status
|
||||
url: string;
|
||||
createdAt: Date;
|
||||
updatedAt?: Date;
|
||||
author?: string;
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Connection status for a provider
|
||||
*/
|
||||
export interface ProviderConnection {
|
||||
id: string;
|
||||
name: string;
|
||||
connected: boolean;
|
||||
lastSync?: Date;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for a provider
|
||||
*/
|
||||
export interface ProviderConfig {
|
||||
enabled: boolean;
|
||||
apiKey?: string;
|
||||
boardId?: string;
|
||||
autoSync?: boolean;
|
||||
syncIntervalMinutes?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract interface for integration adapters
|
||||
*
|
||||
* Implement this interface to add support for new external services.
|
||||
* Each adapter handles mapping between internal and external status systems.
|
||||
*/
|
||||
export interface IntegrationAdapter {
|
||||
/** Unique identifier for this provider */
|
||||
readonly providerId: string;
|
||||
|
||||
/** Display name for the provider */
|
||||
readonly providerName: string;
|
||||
|
||||
/**
|
||||
* Test the connection to the external service
|
||||
*/
|
||||
testConnection(): Promise<{ success: boolean; error?: string }>;
|
||||
|
||||
/**
|
||||
* Fetch all items from the external service
|
||||
*/
|
||||
fetchItems(): Promise<FeedbackItem[]>;
|
||||
|
||||
/**
|
||||
* Update the status of an item in the external service
|
||||
*/
|
||||
updateStatus(externalId: string, status: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Map internal roadmap status to provider-specific status
|
||||
*/
|
||||
mapStatusToProvider(internalStatus: RoadmapFeatureStatus): string;
|
||||
|
||||
/**
|
||||
* Map provider-specific status to internal roadmap status
|
||||
*/
|
||||
mapStatusFromProvider(externalStatus: string): RoadmapFeatureStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Canny-specific status mapping
|
||||
* Reference: https://developers.canny.io/api-reference
|
||||
*/
|
||||
export const CANNY_STATUS_MAP = {
|
||||
toProvider: {
|
||||
under_review: 'under review',
|
||||
planned: 'planned',
|
||||
in_progress: 'in progress',
|
||||
done: 'complete'
|
||||
} as Record<RoadmapFeatureStatus, string>,
|
||||
|
||||
fromProvider: {
|
||||
'open': 'under_review',
|
||||
'under review': 'under_review',
|
||||
'planned': 'planned',
|
||||
'in progress': 'in_progress',
|
||||
'complete': 'done',
|
||||
'closed': 'done'
|
||||
} as Record<string, RoadmapFeatureStatus>
|
||||
};
|
||||
|
||||
/**
|
||||
* GitHub Issues status mapping
|
||||
*/
|
||||
export const GITHUB_ISSUES_STATUS_MAP = {
|
||||
toProvider: {
|
||||
under_review: 'open',
|
||||
planned: 'open',
|
||||
in_progress: 'open',
|
||||
done: 'closed'
|
||||
} as Record<RoadmapFeatureStatus, string>,
|
||||
|
||||
fromProvider: {
|
||||
'open': 'under_review',
|
||||
'closed': 'done'
|
||||
} as Record<string, RoadmapFeatureStatus>
|
||||
};
|
||||
@@ -1256,7 +1256,7 @@ export function setupIpcHandlers(
|
||||
try {
|
||||
// Set status to in_progress for the restart
|
||||
newStatus = 'in_progress';
|
||||
|
||||
|
||||
// Update plan status for restart
|
||||
if (plan) {
|
||||
plan.status = 'in_progress';
|
||||
@@ -1277,7 +1277,7 @@ export function setupIpcHandlers(
|
||||
const specsBaseDir = getSpecsDir(project.autoBuildPath);
|
||||
const specDirForWatcher = path.join(project.path, specsBaseDir, task.specId);
|
||||
fileWatcher.watch(taskId, specDirForWatcher);
|
||||
|
||||
|
||||
agentManager.startTaskExecution(
|
||||
taskId,
|
||||
project.path,
|
||||
@@ -1312,7 +1312,7 @@ export function setupIpcHandlers(
|
||||
taskId,
|
||||
recovered: true,
|
||||
newStatus,
|
||||
message: autoRestarted
|
||||
message: autoRestarted
|
||||
? 'Task recovered and restarted successfully'
|
||||
: `Task recovered successfully and moved to ${newStatus}`,
|
||||
autoRestarted
|
||||
@@ -2418,12 +2418,12 @@ export function setupIpcHandlers(
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import { ipcMain } from 'electron';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
||||
import { IPC_CHANNELS, getSpecsDir, AUTO_BUILD_PATHS } from '../../shared/constants';
|
||||
import type {
|
||||
IPCResult,
|
||||
SDKRateLimitInfo,
|
||||
Task,
|
||||
TaskStatus,
|
||||
Project,
|
||||
ImplementationPlan,
|
||||
ExecutionProgress
|
||||
ImplementationPlan
|
||||
} from '../../shared/types';
|
||||
import { AgentManager } from '../agent';
|
||||
import type { ProcessType, ExecutionProgressData } from '../agent';
|
||||
@@ -82,7 +79,7 @@ export function registerAgenteventsHandlers(
|
||||
} else if (processType === 'spec-creation') {
|
||||
// Pure spec creation (shouldn't happen with current flow, but handle it)
|
||||
// Stay in backlog/planning
|
||||
console.log(`[Task ${taskId}] Spec creation completed with code ${code}`);
|
||||
console.warn(`[Task ${taskId}] Spec creation completed with code ${code}`);
|
||||
return;
|
||||
} else {
|
||||
// Unknown process type
|
||||
@@ -130,7 +127,7 @@ export function registerAgenteventsHandlers(
|
||||
plan.planStatus = 'review';
|
||||
plan.updated_at = new Date().toISOString();
|
||||
writeFileSync(planPath, JSON.stringify(plan, null, 2));
|
||||
console.log(`[Task ${taskId}] Persisted status '${newStatus}' to implementation_plan.json`);
|
||||
console.warn(`[Task ${taskId}] Persisted status '${newStatus}' to implementation_plan.json`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,7 +138,7 @@ export function registerAgenteventsHandlers(
|
||||
// Send notifications based on task completion status
|
||||
if (task && project) {
|
||||
const taskTitle = task.title || task.specId;
|
||||
|
||||
|
||||
if (code === 0) {
|
||||
// Task completed successfully - ready for review
|
||||
notificationService.notifyReviewNeeded(taskTitle, project.id, taskId);
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* App Update IPC Handlers
|
||||
*
|
||||
* Handles IPC communication for Electron app auto-updates.
|
||||
* Provides manual controls for checking, downloading, and installing updates.
|
||||
*/
|
||||
|
||||
import { ipcMain } from 'electron';
|
||||
import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import type { IPCResult, AppUpdateInfo } from '../../shared/types';
|
||||
import {
|
||||
checkForUpdates,
|
||||
downloadUpdate,
|
||||
quitAndInstall,
|
||||
getCurrentVersion
|
||||
} from '../app-updater';
|
||||
|
||||
/**
|
||||
* Register all app-update-related IPC handlers
|
||||
*/
|
||||
export function registerAppUpdateHandlers(): void {
|
||||
console.warn('[IPC] Registering app update handlers');
|
||||
|
||||
// ============================================
|
||||
// App Update Operations
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* APP_UPDATE_CHECK: Manually check for updates
|
||||
* Returns update availability and version information
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.APP_UPDATE_CHECK,
|
||||
async (): Promise<IPCResult<AppUpdateInfo | null>> => {
|
||||
try {
|
||||
const result = await checkForUpdates();
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
console.error('[app-update-handlers] Check for updates failed:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to check for updates'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* APP_UPDATE_DOWNLOAD: Manually download update
|
||||
* Triggers download of available update
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.APP_UPDATE_DOWNLOAD,
|
||||
async (): Promise<IPCResult> => {
|
||||
try {
|
||||
await downloadUpdate();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('[app-update-handlers] Download update failed:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to download update'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* APP_UPDATE_INSTALL: Quit and install update
|
||||
* Quits the app and installs the downloaded update
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.APP_UPDATE_INSTALL,
|
||||
async (): Promise<IPCResult> => {
|
||||
try {
|
||||
quitAndInstall();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('[app-update-handlers] Install update failed:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to install update'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* APP_UPDATE_GET_VERSION: Get current app version
|
||||
* Returns the current application version
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.APP_UPDATE_GET_VERSION,
|
||||
async (): Promise<string> => {
|
||||
try {
|
||||
const version = getCurrentVersion();
|
||||
return version;
|
||||
} catch (error) {
|
||||
console.error('[app-update-handlers] Get version failed:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
console.warn('[IPC] App update handlers registered successfully');
|
||||
}
|
||||
@@ -5,7 +5,8 @@ import type { IPCResult } from '../../shared/types';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
||||
import type { AutoBuildSourceUpdateProgress, SourceEnvConfig, SourceEnvCheckResult } from '../../shared/types';
|
||||
import { checkForUpdates as checkSourceUpdates, downloadAndApplyUpdate, getBundledVersion, getEffectiveSourcePath } from '../auto-claude-updater';
|
||||
import { checkForUpdates as checkSourceUpdates, downloadAndApplyUpdate, getBundledVersion, getEffectiveVersion, getEffectiveSourcePath } from '../auto-claude-updater';
|
||||
import { debugLog } from '../../shared/utils/debug-logger';
|
||||
|
||||
|
||||
/**
|
||||
@@ -21,10 +22,16 @@ export function registerAutobuildSourceHandlers(
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.AUTOBUILD_SOURCE_CHECK,
|
||||
async (): Promise<IPCResult<{ updateAvailable: boolean; currentVersion: string; latestVersion?: string; releaseNotes?: string; releaseUrl?: string; error?: string }>> => {
|
||||
console.log('[autobuild-source] Check for updates called');
|
||||
debugLog('[IPC] AUTOBUILD_SOURCE_CHECK called');
|
||||
try {
|
||||
const result = await checkSourceUpdates();
|
||||
console.log('[autobuild-source] Check result:', JSON.stringify(result, null, 2));
|
||||
debugLog('[IPC] AUTOBUILD_SOURCE_CHECK result:', result);
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
console.error('[autobuild-source] Check error:', error);
|
||||
debugLog('[IPC] AUTOBUILD_SOURCE_CHECK error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to check for updates'
|
||||
@@ -36,25 +43,33 @@ export function registerAutobuildSourceHandlers(
|
||||
ipcMain.on(
|
||||
IPC_CHANNELS.AUTOBUILD_SOURCE_DOWNLOAD,
|
||||
() => {
|
||||
debugLog('[IPC] Autobuild source download requested');
|
||||
const mainWindow = getMainWindow();
|
||||
if (!mainWindow) return;
|
||||
if (!mainWindow) {
|
||||
debugLog('[IPC] No main window available, aborting update');
|
||||
return;
|
||||
}
|
||||
|
||||
// Start download in background
|
||||
downloadAndApplyUpdate((progress) => {
|
||||
debugLog('[IPC] Update progress:', progress.stage, progress.message);
|
||||
mainWindow.webContents.send(
|
||||
IPC_CHANNELS.AUTOBUILD_SOURCE_PROGRESS,
|
||||
progress
|
||||
);
|
||||
}).then((result) => {
|
||||
if (result.success) {
|
||||
debugLog('[IPC] Update completed successfully, version:', result.version);
|
||||
mainWindow.webContents.send(
|
||||
IPC_CHANNELS.AUTOBUILD_SOURCE_PROGRESS,
|
||||
{
|
||||
stage: 'complete',
|
||||
message: `Updated to version ${result.version}`
|
||||
message: `Updated to version ${result.version}`,
|
||||
newVersion: result.version // Include new version for UI refresh
|
||||
} as AutoBuildSourceUpdateProgress
|
||||
);
|
||||
} else {
|
||||
debugLog('[IPC] Update failed:', result.error);
|
||||
mainWindow.webContents.send(
|
||||
IPC_CHANNELS.AUTOBUILD_SOURCE_PROGRESS,
|
||||
{
|
||||
@@ -64,6 +79,7 @@ export function registerAutobuildSourceHandlers(
|
||||
);
|
||||
}
|
||||
}).catch((error) => {
|
||||
debugLog('[IPC] Update error:', error instanceof Error ? error.message : error);
|
||||
mainWindow.webContents.send(
|
||||
IPC_CHANNELS.AUTOBUILD_SOURCE_PROGRESS,
|
||||
{
|
||||
@@ -88,7 +104,9 @@ export function registerAutobuildSourceHandlers(
|
||||
IPC_CHANNELS.AUTOBUILD_SOURCE_VERSION,
|
||||
async (): Promise<IPCResult<string>> => {
|
||||
try {
|
||||
const version = getBundledVersion();
|
||||
// Use effective version which accounts for source updates
|
||||
const version = getEffectiveVersion();
|
||||
debugLog('[IPC] Returning effective version:', version);
|
||||
return { success: true, data: version };
|
||||
} catch (error) {
|
||||
return {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { ipcMain } from 'electron';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
|
||||
import { execSync } from 'child_process';
|
||||
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';
|
||||
import { IPC_CHANNELS, getSpecsDir } from '../../shared/constants';
|
||||
import type {
|
||||
IPCResult,
|
||||
@@ -376,6 +375,46 @@ export function registerChangelogHandlers(
|
||||
}
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.CHANGELOG_READ_LOCAL_IMAGE,
|
||||
async (_, projectPath: string, relativePath: string): Promise<IPCResult<string>> => {
|
||||
try {
|
||||
// Construct full path from project path and relative path
|
||||
const fullPath = path.join(projectPath, relativePath);
|
||||
|
||||
// Verify the file exists
|
||||
if (!existsSync(fullPath)) {
|
||||
return { success: false, error: `Image not found: ${relativePath}` };
|
||||
}
|
||||
|
||||
// Read the file and convert to base64
|
||||
const buffer = readFileSync(fullPath);
|
||||
const base64 = buffer.toString('base64');
|
||||
|
||||
// Determine MIME type from extension
|
||||
const ext = path.extname(relativePath).toLowerCase();
|
||||
const mimeTypes: Record<string, string> = {
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.svg': 'image/svg+xml'
|
||||
};
|
||||
const mimeType = mimeTypes[ext] || 'image/png';
|
||||
|
||||
// Return as data URL
|
||||
const dataUrl = `data:${mimeType};base64,${base64}`;
|
||||
return { success: true, data: dataUrl };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to read image'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// ============================================
|
||||
// Changelog Agent Events → Renderer
|
||||
}
|
||||
|
||||
@@ -9,11 +9,11 @@ import type {
|
||||
ContextSearchResult
|
||||
} from '../../../shared/types';
|
||||
import { projectStore } from '../../project-store';
|
||||
import { getFalkorDBService } from '../../falkordb-service';
|
||||
import { getMemoryService, isKuzuAvailable } from '../../memory-service';
|
||||
import {
|
||||
loadProjectEnvVars,
|
||||
isGraphitiEnabled,
|
||||
getGraphitiConnectionDetails
|
||||
getGraphitiDatabaseDetails
|
||||
} from './utils';
|
||||
|
||||
/**
|
||||
@@ -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(
|
||||
@@ -169,20 +169,20 @@ export function registerMemoryDataHandlers(
|
||||
const projectEnvVars = loadProjectEnvVars(project.path, project.autoBuildPath);
|
||||
const graphitiEnabled = isGraphitiEnabled(projectEnvVars);
|
||||
|
||||
// Try FalkorDB first if available
|
||||
if (graphitiEnabled) {
|
||||
// Try LadybugDB first if available
|
||||
if (graphitiEnabled && isKuzuAvailable()) {
|
||||
try {
|
||||
const connDetails = getGraphitiConnectionDetails(projectEnvVars);
|
||||
const falkorService = getFalkorDBService({
|
||||
host: connDetails.host,
|
||||
port: connDetails.port,
|
||||
const dbDetails = getGraphitiDatabaseDetails(projectEnvVars);
|
||||
const memoryService = getMemoryService({
|
||||
dbPath: dbDetails.dbPath,
|
||||
database: dbDetails.database,
|
||||
});
|
||||
const falkorMemories = await falkorService.getAllMemories(limit);
|
||||
if (falkorMemories.length > 0) {
|
||||
return { success: true, data: falkorMemories };
|
||||
const graphMemories = await memoryService.getEpisodicMemories(limit);
|
||||
if (graphMemories.length > 0) {
|
||||
return { success: true, data: graphMemories };
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to get memories from FalkorDB, falling back to file-based:', error);
|
||||
console.warn('Failed to get memories from LadybugDB, falling back to file-based:', error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,19 +207,19 @@ export function registerMemoryDataHandlers(
|
||||
const projectEnvVars = loadProjectEnvVars(project.path, project.autoBuildPath);
|
||||
const graphitiEnabled = isGraphitiEnabled(projectEnvVars);
|
||||
|
||||
// Try FalkorDB search if available
|
||||
if (graphitiEnabled) {
|
||||
// Try LadybugDB search if available
|
||||
if (graphitiEnabled && isKuzuAvailable()) {
|
||||
try {
|
||||
const connDetails = getGraphitiConnectionDetails(projectEnvVars);
|
||||
const falkorService = getFalkorDBService({
|
||||
host: connDetails.host,
|
||||
port: connDetails.port,
|
||||
const dbDetails = getGraphitiDatabaseDetails(projectEnvVars);
|
||||
const memoryService = getMemoryService({
|
||||
dbPath: dbDetails.dbPath,
|
||||
database: dbDetails.database,
|
||||
});
|
||||
const falkorResults = await falkorService.searchMemories(query, 20);
|
||||
if (falkorResults.length > 0) {
|
||||
const graphResults = await memoryService.searchMemories(query, 20);
|
||||
if (graphResults.length > 0) {
|
||||
return {
|
||||
success: true,
|
||||
data: falkorResults.map(r => ({
|
||||
data: graphResults.map(r => ({
|
||||
content: r.content,
|
||||
score: r.score || 1.0,
|
||||
type: r.type
|
||||
@@ -227,7 +227,7 @@ export function registerMemoryDataHandlers(
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to search FalkorDB, falling back to file-based:', error);
|
||||
console.warn('Failed to search LadybugDB, falling back to file-based:', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
loadGlobalSettings,
|
||||
isGraphitiEnabled,
|
||||
hasOpenAIKey,
|
||||
getGraphitiConnectionDetails
|
||||
getGraphitiDatabaseDetails
|
||||
} from './utils';
|
||||
|
||||
/**
|
||||
@@ -65,13 +65,12 @@ export function buildMemoryStatus(
|
||||
|
||||
// If we have initialized state from specs, use it
|
||||
if (memoryState?.initialized) {
|
||||
const connDetails = getGraphitiConnectionDetails(projectEnvVars);
|
||||
const dbDetails = getGraphitiDatabaseDetails(projectEnvVars);
|
||||
return {
|
||||
enabled: true,
|
||||
available: true,
|
||||
database: memoryState.database || 'auto_claude_memory',
|
||||
host: connDetails.host,
|
||||
port: connDetails.port
|
||||
dbPath: dbDetails.dbPath
|
||||
};
|
||||
}
|
||||
|
||||
@@ -95,13 +94,12 @@ export function buildMemoryStatus(
|
||||
};
|
||||
}
|
||||
|
||||
const connDetails = getGraphitiConnectionDetails(projectEnvVars);
|
||||
const dbDetails = getGraphitiDatabaseDetails(projectEnvVars);
|
||||
return {
|
||||
enabled: true,
|
||||
available: true,
|
||||
host: connDetails.host,
|
||||
port: connDetails.port,
|
||||
database: connDetails.database
|
||||
dbPath: dbDetails.dbPath,
|
||||
database: dbDetails.database
|
||||
};
|
||||
}
|
||||
|
||||
@@ -109,7 +107,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,
|
||||
|
||||
@@ -11,13 +11,11 @@ import type {
|
||||
MemoryEpisode
|
||||
} from '../../../shared/types';
|
||||
import { projectStore } from '../../project-store';
|
||||
import { getFalkorDBService } from '../../falkordb-service';
|
||||
import { getMemoryService, isKuzuAvailable } from '../../memory-service';
|
||||
import {
|
||||
getAutoBuildSourcePath,
|
||||
loadProjectEnvVars,
|
||||
isGraphitiEnabled,
|
||||
getGraphitiConnectionDetails
|
||||
getGraphitiDatabaseDetails
|
||||
} from './utils';
|
||||
import { getEffectiveSourcePath } from '../../updater/path-resolver';
|
||||
import {
|
||||
loadGraphitiStateFromSpecs,
|
||||
buildMemoryStatus
|
||||
@@ -42,34 +40,34 @@ function loadProjectIndex(projectPath: string): ProjectIndex | null {
|
||||
}
|
||||
|
||||
/**
|
||||
* Load recent memories with FalkorDB fallback
|
||||
* Load recent memories from LadybugDB with file-based fallback
|
||||
*/
|
||||
async function loadRecentMemories(
|
||||
projectPath: string,
|
||||
autoBuildPath: string | undefined,
|
||||
memoryStatusAvailable: boolean,
|
||||
memoryHost?: string,
|
||||
memoryPort?: number
|
||||
dbPath?: string,
|
||||
database?: string
|
||||
): Promise<MemoryEpisode[]> {
|
||||
let recentMemories: MemoryEpisode[] = [];
|
||||
|
||||
// Try to load from FalkorDB first if Graphiti is available
|
||||
if (memoryStatusAvailable && memoryHost && memoryPort) {
|
||||
// Try to load from LadybugDB first if Graphiti is available and Kuzu is installed
|
||||
if (memoryStatusAvailable && isKuzuAvailable() && dbPath && database) {
|
||||
try {
|
||||
const falkorService = getFalkorDBService({
|
||||
host: memoryHost,
|
||||
port: memoryPort,
|
||||
const memoryService = getMemoryService({
|
||||
dbPath,
|
||||
database,
|
||||
});
|
||||
const falkorMemories = await falkorService.getAllMemories(20);
|
||||
if (falkorMemories.length > 0) {
|
||||
recentMemories = falkorMemories;
|
||||
const graphMemories = await memoryService.getEpisodicMemories(20);
|
||||
if (graphMemories.length > 0) {
|
||||
recentMemories = graphMemories;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load memories from FalkorDB, falling back to file-based:', error);
|
||||
console.warn('Failed to load memories from LadybugDB, falling back to file-based:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to file-based memory if no FalkorDB memories found
|
||||
// Fall back to file-based memory if no graph memories found
|
||||
if (recentMemories.length === 0) {
|
||||
const specsBaseDir = getSpecsDir(autoBuildPath);
|
||||
const specsDir = path.join(projectPath, specsBaseDir);
|
||||
@@ -83,7 +81,7 @@ async function loadRecentMemories(
|
||||
* Register project context handlers
|
||||
*/
|
||||
export function registerProjectContextHandlers(
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
_getMainWindow: () => BrowserWindow | null
|
||||
): void {
|
||||
// Get full project context
|
||||
ipcMain.handle(
|
||||
@@ -113,8 +111,8 @@ export function registerProjectContextHandlers(
|
||||
project.path,
|
||||
project.autoBuildPath,
|
||||
memoryStatus.available,
|
||||
memoryStatus.host,
|
||||
memoryStatus.port
|
||||
memoryStatus.dbPath,
|
||||
memoryStatus.database
|
||||
);
|
||||
|
||||
return {
|
||||
@@ -147,7 +145,7 @@ export function registerProjectContextHandlers(
|
||||
|
||||
try {
|
||||
// Run the analyzer script to regenerate project_index.json
|
||||
const autoBuildSource = getAutoBuildSourcePath();
|
||||
const autoBuildSource = getEffectiveSourcePath();
|
||||
|
||||
if (!autoBuildSource) {
|
||||
return {
|
||||
|
||||
@@ -120,29 +120,21 @@ export function hasOpenAIKey(projectEnvVars: EnvironmentVars, globalSettings: Gl
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Graphiti connection details
|
||||
* Get Graphiti database details (LadybugDB - embedded database)
|
||||
*/
|
||||
export interface GraphitiConnectionDetails {
|
||||
host: string;
|
||||
port: number;
|
||||
export interface GraphitiDatabaseDetails {
|
||||
dbPath: string;
|
||||
database: string;
|
||||
}
|
||||
|
||||
export function getGraphitiConnectionDetails(projectEnvVars: EnvironmentVars): GraphitiConnectionDetails {
|
||||
const host = projectEnvVars['GRAPHITI_FALKORDB_HOST'] ||
|
||||
process.env.GRAPHITI_FALKORDB_HOST ||
|
||||
'localhost';
|
||||
|
||||
const port = parseInt(
|
||||
projectEnvVars['GRAPHITI_FALKORDB_PORT'] ||
|
||||
process.env.GRAPHITI_FALKORDB_PORT ||
|
||||
'6380',
|
||||
10
|
||||
);
|
||||
export function getGraphitiDatabaseDetails(projectEnvVars: EnvironmentVars): GraphitiDatabaseDetails {
|
||||
const dbPath = projectEnvVars['GRAPHITI_DB_PATH'] ||
|
||||
process.env.GRAPHITI_DB_PATH ||
|
||||
require('path').join(require('os').homedir(), '.auto-claude', 'memories');
|
||||
|
||||
const database = projectEnvVars['GRAPHITI_DATABASE'] ||
|
||||
process.env.GRAPHITI_DATABASE ||
|
||||
'auto_claude_memory';
|
||||
|
||||
return { host, port, database };
|
||||
return { dbPath, database };
|
||||
}
|
||||
|
||||
@@ -1,156 +1,20 @@
|
||||
/**
|
||||
* Docker & FalkorDB IPC Handlers
|
||||
* Docker & Infrastructure IPC Handlers
|
||||
*
|
||||
* Provides automatic infrastructure detection for non-technical users.
|
||||
* When Graphiti is enabled, the UI can check Docker/FalkorDB status
|
||||
* and offer one-click solutions instead of manual terminal commands.
|
||||
* DEPRECATED: This file is kept for backward compatibility.
|
||||
* Memory infrastructure has moved to LadybugDB (no Docker required).
|
||||
* See memory-handlers.ts for the new implementation.
|
||||
*
|
||||
* This file now re-exports from memory-handlers.ts
|
||||
*/
|
||||
|
||||
import { ipcMain } from 'electron';
|
||||
import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import type { IPCResult, InfrastructureStatus } from '../../shared/types';
|
||||
import {
|
||||
getInfrastructureStatus,
|
||||
startFalkorDB,
|
||||
stopFalkorDB,
|
||||
openDockerDesktop,
|
||||
getDockerDownloadUrl,
|
||||
validateFalkorDBConnection,
|
||||
validateOpenAIApiKey,
|
||||
testGraphitiConnection,
|
||||
type GraphitiValidationResult,
|
||||
} from '../docker-service';
|
||||
import { registerMemoryHandlers } from './memory-handlers';
|
||||
|
||||
/**
|
||||
* Register all Docker-related IPC handlers
|
||||
* @deprecated Use registerMemoryHandlers() instead
|
||||
*/
|
||||
export function registerDockerHandlers(): void {
|
||||
// Get infrastructure status (Docker + FalkorDB)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.DOCKER_STATUS,
|
||||
async (_, port?: number): Promise<IPCResult<InfrastructureStatus>> => {
|
||||
try {
|
||||
const status = await getInfrastructureStatus(port);
|
||||
return { success: true, data: status };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to check Docker status',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Start FalkorDB container
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.DOCKER_START_FALKORDB,
|
||||
async (_, port?: number): Promise<IPCResult<{ success: boolean; error?: string }>> => {
|
||||
try {
|
||||
const result = await startFalkorDB(port);
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to start FalkorDB',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Stop FalkorDB container
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.DOCKER_STOP_FALKORDB,
|
||||
async (): Promise<IPCResult<{ success: boolean; error?: string }>> => {
|
||||
try {
|
||||
const result = await stopFalkorDB();
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to stop FalkorDB',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Open Docker Desktop application
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.DOCKER_OPEN_DESKTOP,
|
||||
async (): Promise<IPCResult<{ success: boolean; error?: string }>> => {
|
||||
try {
|
||||
const result = await openDockerDesktop();
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to open Docker Desktop',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Get Docker download URL
|
||||
ipcMain.handle(IPC_CHANNELS.DOCKER_GET_DOWNLOAD_URL, async (): Promise<string> => {
|
||||
return getDockerDownloadUrl();
|
||||
});
|
||||
|
||||
// ============================================
|
||||
// Graphiti Validation Handlers
|
||||
// ============================================
|
||||
|
||||
// Validate FalkorDB connection
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GRAPHITI_VALIDATE_FALKORDB,
|
||||
async (_, uri: string): Promise<IPCResult<GraphitiValidationResult>> => {
|
||||
try {
|
||||
const result = await validateFalkorDBConnection(uri);
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to validate FalkorDB connection',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Validate OpenAI API key
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GRAPHITI_VALIDATE_OPENAI,
|
||||
async (_, apiKey: string): Promise<IPCResult<GraphitiValidationResult>> => {
|
||||
try {
|
||||
const result = await validateOpenAIApiKey(apiKey);
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to validate OpenAI API key',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Test full Graphiti connection (FalkorDB + OpenAI)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GRAPHITI_TEST_CONNECTION,
|
||||
async (
|
||||
_,
|
||||
falkorDbUri: string,
|
||||
openAiApiKey: string
|
||||
): Promise<IPCResult<{
|
||||
falkordb: GraphitiValidationResult;
|
||||
openai: GraphitiValidationResult;
|
||||
ready: boolean;
|
||||
}>> => {
|
||||
try {
|
||||
const result = await testGraphitiConnection(falkorDbUri, openAiApiKey);
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to test Graphiti connection',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
// Register the new memory handlers instead
|
||||
registerMemoryHandlers();
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { IPCResult, ProjectEnvConfig, ClaudeAuthResult, AppSettings } from
|
||||
import path from 'path';
|
||||
import { app } from 'electron';
|
||||
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
||||
import { execSync, spawn } from 'child_process';
|
||||
import { spawn } from 'child_process';
|
||||
import { projectStore } from '../project-store';
|
||||
import { parseEnvFile } from './utils';
|
||||
|
||||
@@ -14,7 +14,7 @@ import { parseEnvFile } from './utils';
|
||||
* Register all env-related IPC handlers
|
||||
*/
|
||||
export function registerEnvHandlers(
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
_getMainWindow: () => BrowserWindow | null
|
||||
): void {
|
||||
// ============================================
|
||||
// Environment Configuration Operations
|
||||
@@ -62,30 +62,55 @@ export function registerEnvHandlers(
|
||||
if (config.githubAutoSync !== undefined) {
|
||||
existingVars['GITHUB_AUTO_SYNC'] = config.githubAutoSync ? 'true' : 'false';
|
||||
}
|
||||
// Git/Worktree Settings
|
||||
if (config.defaultBranch !== undefined) {
|
||||
existingVars['DEFAULT_BRANCH'] = config.defaultBranch;
|
||||
}
|
||||
if (config.graphitiEnabled !== undefined) {
|
||||
existingVars['GRAPHITI_ENABLED'] = config.graphitiEnabled ? 'true' : 'false';
|
||||
}
|
||||
// Memory Provider Configuration (embeddings only - LLM uses Claude SDK)
|
||||
if (config.graphitiProviderConfig) {
|
||||
const pc = config.graphitiProviderConfig;
|
||||
// Embedding provider only (LLM provider removed - Claude SDK handles RAG)
|
||||
if (pc.embeddingProvider) existingVars['GRAPHITI_EMBEDDER_PROVIDER'] = pc.embeddingProvider;
|
||||
// OpenAI Embeddings
|
||||
if (pc.openaiApiKey) existingVars['OPENAI_API_KEY'] = pc.openaiApiKey;
|
||||
if (pc.openaiEmbeddingModel) existingVars['OPENAI_EMBEDDING_MODEL'] = pc.openaiEmbeddingModel;
|
||||
// Azure OpenAI Embeddings
|
||||
if (pc.azureOpenaiApiKey) existingVars['AZURE_OPENAI_API_KEY'] = pc.azureOpenaiApiKey;
|
||||
if (pc.azureOpenaiBaseUrl) existingVars['AZURE_OPENAI_BASE_URL'] = pc.azureOpenaiBaseUrl;
|
||||
if (pc.azureOpenaiEmbeddingDeployment) existingVars['AZURE_OPENAI_EMBEDDING_DEPLOYMENT'] = pc.azureOpenaiEmbeddingDeployment;
|
||||
// Voyage Embeddings
|
||||
if (pc.voyageApiKey) existingVars['VOYAGE_API_KEY'] = pc.voyageApiKey;
|
||||
if (pc.voyageEmbeddingModel) existingVars['VOYAGE_EMBEDDING_MODEL'] = pc.voyageEmbeddingModel;
|
||||
// Google Embeddings
|
||||
if (pc.googleApiKey) existingVars['GOOGLE_API_KEY'] = pc.googleApiKey;
|
||||
if (pc.googleEmbeddingModel) existingVars['GOOGLE_EMBEDDING_MODEL'] = pc.googleEmbeddingModel;
|
||||
// Ollama Embeddings
|
||||
if (pc.ollamaBaseUrl) existingVars['OLLAMA_BASE_URL'] = pc.ollamaBaseUrl;
|
||||
if (pc.ollamaEmbeddingModel) existingVars['OLLAMA_EMBEDDING_MODEL'] = pc.ollamaEmbeddingModel;
|
||||
if (pc.ollamaEmbeddingDim) existingVars['OLLAMA_EMBEDDING_DIM'] = String(pc.ollamaEmbeddingDim);
|
||||
// LadybugDB (embedded database)
|
||||
if (pc.dbPath) existingVars['GRAPHITI_DB_PATH'] = pc.dbPath;
|
||||
if (pc.database) existingVars['GRAPHITI_DATABASE'] = pc.database;
|
||||
}
|
||||
// Legacy fields (still supported)
|
||||
if (config.openaiApiKey !== undefined) {
|
||||
existingVars['OPENAI_API_KEY'] = config.openaiApiKey;
|
||||
}
|
||||
if (config.graphitiFalkorDbHost !== undefined) {
|
||||
existingVars['GRAPHITI_FALKORDB_HOST'] = config.graphitiFalkorDbHost;
|
||||
}
|
||||
if (config.graphitiFalkorDbPort !== undefined) {
|
||||
existingVars['GRAPHITI_FALKORDB_PORT'] = String(config.graphitiFalkorDbPort);
|
||||
}
|
||||
if (config.graphitiFalkorDbPassword !== undefined) {
|
||||
existingVars['GRAPHITI_FALKORDB_PASSWORD'] = config.graphitiFalkorDbPassword;
|
||||
}
|
||||
if (config.graphitiDatabase !== undefined) {
|
||||
existingVars['GRAPHITI_DATABASE'] = config.graphitiDatabase;
|
||||
}
|
||||
if (config.graphitiDbPath !== undefined) {
|
||||
existingVars['GRAPHITI_DB_PATH'] = config.graphitiDbPath;
|
||||
}
|
||||
if (config.enableFancyUi !== undefined) {
|
||||
existingVars['ENABLE_FANCY_UI'] = config.enableFancyUi ? 'true' : 'false';
|
||||
}
|
||||
|
||||
// Generate content with sections
|
||||
let content = `# Auto Claude Framework Environment Variables
|
||||
const content = `# Auto Claude Framework Environment Variables
|
||||
# Managed by Auto Claude UI
|
||||
|
||||
# Claude Code OAuth Token (REQUIRED)
|
||||
@@ -109,20 +134,52 @@ ${existingVars['GITHUB_TOKEN'] ? `GITHUB_TOKEN=${existingVars['GITHUB_TOKEN']}`
|
||||
${existingVars['GITHUB_REPO'] ? `GITHUB_REPO=${existingVars['GITHUB_REPO']}` : '# GITHUB_REPO=owner/repo'}
|
||||
${existingVars['GITHUB_AUTO_SYNC'] !== undefined ? `GITHUB_AUTO_SYNC=${existingVars['GITHUB_AUTO_SYNC']}` : '# GITHUB_AUTO_SYNC=false'}
|
||||
|
||||
# =============================================================================
|
||||
# GIT/WORKTREE SETTINGS (OPTIONAL)
|
||||
# =============================================================================
|
||||
# Default base branch for worktree creation
|
||||
# If not set, Auto Claude will auto-detect main/master, or fall back to current branch
|
||||
${existingVars['DEFAULT_BRANCH'] ? `DEFAULT_BRANCH=${existingVars['DEFAULT_BRANCH']}` : '# DEFAULT_BRANCH=main'}
|
||||
|
||||
# =============================================================================
|
||||
# UI SETTINGS (OPTIONAL)
|
||||
# =============================================================================
|
||||
${existingVars['ENABLE_FANCY_UI'] !== undefined ? `ENABLE_FANCY_UI=${existingVars['ENABLE_FANCY_UI']}` : '# ENABLE_FANCY_UI=true'}
|
||||
|
||||
# =============================================================================
|
||||
# GRAPHITI MEMORY INTEGRATION (OPTIONAL)
|
||||
# MEMORY INTEGRATION
|
||||
# Embedding providers: OpenAI, Google AI, Azure OpenAI, Ollama, Voyage
|
||||
# =============================================================================
|
||||
${existingVars['GRAPHITI_ENABLED'] ? `GRAPHITI_ENABLED=${existingVars['GRAPHITI_ENABLED']}` : '# GRAPHITI_ENABLED=false'}
|
||||
${existingVars['GRAPHITI_ENABLED'] ? `GRAPHITI_ENABLED=${existingVars['GRAPHITI_ENABLED']}` : '# GRAPHITI_ENABLED=true'}
|
||||
|
||||
# Embedding Provider (for semantic search - optional, keyword search works without)
|
||||
${existingVars['GRAPHITI_EMBEDDER_PROVIDER'] ? `GRAPHITI_EMBEDDER_PROVIDER=${existingVars['GRAPHITI_EMBEDDER_PROVIDER']}` : '# GRAPHITI_EMBEDDER_PROVIDER=ollama'}
|
||||
|
||||
# OpenAI Embeddings
|
||||
${existingVars['OPENAI_API_KEY'] ? `OPENAI_API_KEY=${existingVars['OPENAI_API_KEY']}` : '# OPENAI_API_KEY='}
|
||||
${existingVars['GRAPHITI_FALKORDB_HOST'] ? `GRAPHITI_FALKORDB_HOST=${existingVars['GRAPHITI_FALKORDB_HOST']}` : '# GRAPHITI_FALKORDB_HOST=localhost'}
|
||||
${existingVars['GRAPHITI_FALKORDB_PORT'] ? `GRAPHITI_FALKORDB_PORT=${existingVars['GRAPHITI_FALKORDB_PORT']}` : '# GRAPHITI_FALKORDB_PORT=6380'}
|
||||
${existingVars['GRAPHITI_FALKORDB_PASSWORD'] ? `GRAPHITI_FALKORDB_PASSWORD=${existingVars['GRAPHITI_FALKORDB_PASSWORD']}` : '# GRAPHITI_FALKORDB_PASSWORD='}
|
||||
${existingVars['OPENAI_EMBEDDING_MODEL'] ? `OPENAI_EMBEDDING_MODEL=${existingVars['OPENAI_EMBEDDING_MODEL']}` : '# OPENAI_EMBEDDING_MODEL=text-embedding-3-small'}
|
||||
|
||||
# Azure OpenAI Embeddings
|
||||
${existingVars['AZURE_OPENAI_API_KEY'] ? `AZURE_OPENAI_API_KEY=${existingVars['AZURE_OPENAI_API_KEY']}` : '# AZURE_OPENAI_API_KEY='}
|
||||
${existingVars['AZURE_OPENAI_BASE_URL'] ? `AZURE_OPENAI_BASE_URL=${existingVars['AZURE_OPENAI_BASE_URL']}` : '# AZURE_OPENAI_BASE_URL='}
|
||||
${existingVars['AZURE_OPENAI_EMBEDDING_DEPLOYMENT'] ? `AZURE_OPENAI_EMBEDDING_DEPLOYMENT=${existingVars['AZURE_OPENAI_EMBEDDING_DEPLOYMENT']}` : '# AZURE_OPENAI_EMBEDDING_DEPLOYMENT='}
|
||||
|
||||
# Voyage AI Embeddings
|
||||
${existingVars['VOYAGE_API_KEY'] ? `VOYAGE_API_KEY=${existingVars['VOYAGE_API_KEY']}` : '# VOYAGE_API_KEY='}
|
||||
${existingVars['VOYAGE_EMBEDDING_MODEL'] ? `VOYAGE_EMBEDDING_MODEL=${existingVars['VOYAGE_EMBEDDING_MODEL']}` : '# VOYAGE_EMBEDDING_MODEL=voyage-3'}
|
||||
|
||||
# Google AI Embeddings
|
||||
${existingVars['GOOGLE_API_KEY'] ? `GOOGLE_API_KEY=${existingVars['GOOGLE_API_KEY']}` : '# GOOGLE_API_KEY='}
|
||||
${existingVars['GOOGLE_EMBEDDING_MODEL'] ? `GOOGLE_EMBEDDING_MODEL=${existingVars['GOOGLE_EMBEDDING_MODEL']}` : '# GOOGLE_EMBEDDING_MODEL=text-embedding-004'}
|
||||
|
||||
# Ollama Embeddings (Local - free)
|
||||
${existingVars['OLLAMA_BASE_URL'] ? `OLLAMA_BASE_URL=${existingVars['OLLAMA_BASE_URL']}` : '# OLLAMA_BASE_URL=http://localhost:11434'}
|
||||
${existingVars['OLLAMA_EMBEDDING_MODEL'] ? `OLLAMA_EMBEDDING_MODEL=${existingVars['OLLAMA_EMBEDDING_MODEL']}` : '# OLLAMA_EMBEDDING_MODEL=embeddinggemma'}
|
||||
${existingVars['OLLAMA_EMBEDDING_DIM'] ? `OLLAMA_EMBEDDING_DIM=${existingVars['OLLAMA_EMBEDDING_DIM']}` : '# OLLAMA_EMBEDDING_DIM=768'}
|
||||
|
||||
# LadybugDB Database (embedded - no Docker required)
|
||||
${existingVars['GRAPHITI_DATABASE'] ? `GRAPHITI_DATABASE=${existingVars['GRAPHITI_DATABASE']}` : '# GRAPHITI_DATABASE=auto_claude_memory'}
|
||||
${existingVars['GRAPHITI_DB_PATH'] ? `GRAPHITI_DB_PATH=${existingVars['GRAPHITI_DB_PATH']}` : '# GRAPHITI_DB_PATH=~/.auto-claude/memories'}
|
||||
`;
|
||||
|
||||
return content;
|
||||
@@ -216,6 +273,11 @@ ${existingVars['GRAPHITI_DATABASE'] ? `GRAPHITI_DATABASE=${existingVars['GRAPHIT
|
||||
config.githubAutoSync = true;
|
||||
}
|
||||
|
||||
// Git/Worktree config
|
||||
if (vars['DEFAULT_BRANCH']) {
|
||||
config.defaultBranch = vars['DEFAULT_BRANCH'];
|
||||
}
|
||||
|
||||
if (vars['GRAPHITI_ENABLED']?.toLowerCase() === 'true') {
|
||||
config.graphitiEnabled = true;
|
||||
}
|
||||
@@ -229,23 +291,46 @@ ${existingVars['GRAPHITI_DATABASE'] ? `GRAPHITI_DATABASE=${existingVars['GRAPHIT
|
||||
config.openaiKeyIsGlobal = true;
|
||||
}
|
||||
|
||||
if (vars['GRAPHITI_FALKORDB_HOST']) {
|
||||
config.graphitiFalkorDbHost = vars['GRAPHITI_FALKORDB_HOST'];
|
||||
}
|
||||
if (vars['GRAPHITI_FALKORDB_PORT']) {
|
||||
config.graphitiFalkorDbPort = parseInt(vars['GRAPHITI_FALKORDB_PORT'], 10);
|
||||
}
|
||||
if (vars['GRAPHITI_FALKORDB_PASSWORD']) {
|
||||
config.graphitiFalkorDbPassword = vars['GRAPHITI_FALKORDB_PASSWORD'];
|
||||
}
|
||||
if (vars['GRAPHITI_DATABASE']) {
|
||||
config.graphitiDatabase = vars['GRAPHITI_DATABASE'];
|
||||
}
|
||||
if (vars['GRAPHITI_DB_PATH']) {
|
||||
config.graphitiDbPath = vars['GRAPHITI_DB_PATH'];
|
||||
}
|
||||
|
||||
if (vars['ENABLE_FANCY_UI']?.toLowerCase() === 'false') {
|
||||
config.enableFancyUi = false;
|
||||
}
|
||||
|
||||
// Populate graphitiProviderConfig from .env file (embeddings only - no LLM provider)
|
||||
const embeddingProvider = vars['GRAPHITI_EMBEDDER_PROVIDER'];
|
||||
if (embeddingProvider || vars['AZURE_OPENAI_API_KEY'] ||
|
||||
vars['VOYAGE_API_KEY'] || vars['GOOGLE_API_KEY'] || vars['OLLAMA_BASE_URL']) {
|
||||
config.graphitiProviderConfig = {
|
||||
embeddingProvider: (embeddingProvider as 'openai' | 'voyage' | 'azure_openai' | 'ollama' | 'google') || 'ollama',
|
||||
// OpenAI Embeddings
|
||||
openaiApiKey: vars['OPENAI_API_KEY'],
|
||||
openaiEmbeddingModel: vars['OPENAI_EMBEDDING_MODEL'],
|
||||
// Azure OpenAI Embeddings
|
||||
azureOpenaiApiKey: vars['AZURE_OPENAI_API_KEY'],
|
||||
azureOpenaiBaseUrl: vars['AZURE_OPENAI_BASE_URL'],
|
||||
azureOpenaiEmbeddingDeployment: vars['AZURE_OPENAI_EMBEDDING_DEPLOYMENT'],
|
||||
// Voyage Embeddings
|
||||
voyageApiKey: vars['VOYAGE_API_KEY'],
|
||||
voyageEmbeddingModel: vars['VOYAGE_EMBEDDING_MODEL'],
|
||||
// Google Embeddings
|
||||
googleApiKey: vars['GOOGLE_API_KEY'],
|
||||
googleEmbeddingModel: vars['GOOGLE_EMBEDDING_MODEL'],
|
||||
// Ollama Embeddings
|
||||
ollamaBaseUrl: vars['OLLAMA_BASE_URL'],
|
||||
ollamaEmbeddingModel: vars['OLLAMA_EMBEDDING_MODEL'],
|
||||
ollamaEmbeddingDim: vars['OLLAMA_EMBEDDING_DIM'] ? parseInt(vars['OLLAMA_EMBEDDING_DIM'], 10) : undefined,
|
||||
// LadybugDB
|
||||
database: vars['GRAPHITI_DATABASE'],
|
||||
dbPath: vars['GRAPHITI_DB_PATH'],
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, data: config };
|
||||
}
|
||||
);
|
||||
@@ -304,15 +389,15 @@ ${existingVars['GRAPHITI_DATABASE'] ? `GRAPHITI_DATABASE=${existingVars['GRAPHIT
|
||||
shell: true
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let _stdout = '';
|
||||
let _stderr = '';
|
||||
|
||||
proc.stdout?.on('data', (data: Buffer) => {
|
||||
stdout += data.toString();
|
||||
_stdout += data.toString();
|
||||
});
|
||||
|
||||
proc.stderr?.on('data', (data: Buffer) => {
|
||||
stderr += data.toString();
|
||||
_stderr += data.toString();
|
||||
});
|
||||
|
||||
proc.on('close', (code: number | null) => {
|
||||
|
||||
@@ -8,8 +8,8 @@ import type { IPCResult, FileNode } from '../../shared/types';
|
||||
const IGNORED_DIRS = new Set([
|
||||
'node_modules', '.git', '__pycache__', 'dist', 'build',
|
||||
'.next', '.nuxt', 'coverage', '.cache', '.venv', 'venv',
|
||||
'.idea', '.vscode', 'out', '.turbo', '.auto-claude',
|
||||
'.worktrees', 'vendor', 'target', '.gradle', '.maven'
|
||||
'out', '.turbo', '.worktrees',
|
||||
'vendor', 'target', '.gradle', '.maven'
|
||||
]);
|
||||
|
||||
/**
|
||||
@@ -29,8 +29,11 @@ export function registerFileHandlers(): void {
|
||||
// Filter and map entries
|
||||
const nodes: FileNode[] = [];
|
||||
for (const entry of entries) {
|
||||
// Skip hidden files (except .env which is often useful)
|
||||
if (entry.name.startsWith('.') && entry.name !== '.env') continue;
|
||||
// Skip hidden files (not directories) except useful ones like .env, .gitignore
|
||||
if (!entry.isDirectory() && entry.name.startsWith('.') &&
|
||||
!['.env', '.gitignore', '.env.example', '.env.local'].includes(entry.name)) {
|
||||
continue;
|
||||
}
|
||||
// Skip ignored directories
|
||||
if (entry.isDirectory() && IGNORED_DIRS.has(entry.name)) continue;
|
||||
|
||||
|
||||
@@ -0,0 +1,548 @@
|
||||
/**
|
||||
* Unit tests for GitHub OAuth handlers
|
||||
* Tests device code parsing, shell.openExternal handling, and error recovery
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
// Mock child_process before importing
|
||||
const mockSpawn = vi.fn();
|
||||
const mockExecSync = vi.fn();
|
||||
const mockExecFileSync = vi.fn();
|
||||
|
||||
vi.mock('child_process', () => ({
|
||||
spawn: (...args: unknown[]) => mockSpawn(...args),
|
||||
execSync: (...args: unknown[]) => mockExecSync(...args),
|
||||
execFileSync: (...args: unknown[]) => mockExecFileSync(...args)
|
||||
}));
|
||||
|
||||
// Mock shell.openExternal
|
||||
const mockOpenExternal = vi.fn();
|
||||
|
||||
vi.mock('electron', () => {
|
||||
const mockIpcMain = new (class extends EventEmitter {
|
||||
private handlers: Map<string, Function> = new Map();
|
||||
|
||||
handle(channel: string, handler: Function): void {
|
||||
this.handlers.set(channel, handler);
|
||||
}
|
||||
|
||||
removeHandler(channel: string): void {
|
||||
this.handlers.delete(channel);
|
||||
}
|
||||
|
||||
async invokeHandler(channel: string, event: unknown, ...args: unknown[]): Promise<unknown> {
|
||||
const handler = this.handlers.get(channel);
|
||||
if (handler) {
|
||||
return handler(event, ...args);
|
||||
}
|
||||
throw new Error(`No handler for channel: ${channel}`);
|
||||
}
|
||||
|
||||
getHandler(channel: string): Function | undefined {
|
||||
return this.handlers.get(channel);
|
||||
}
|
||||
})();
|
||||
|
||||
return {
|
||||
ipcMain: mockIpcMain,
|
||||
shell: {
|
||||
openExternal: (...args: unknown[]) => mockOpenExternal(...args)
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
// Mock @electron-toolkit/utils
|
||||
vi.mock('@electron-toolkit/utils', () => ({
|
||||
is: {
|
||||
dev: true,
|
||||
windows: process.platform === 'win32',
|
||||
macos: process.platform === 'darwin',
|
||||
linux: process.platform === 'linux'
|
||||
}
|
||||
}));
|
||||
|
||||
// Create mock process for spawn
|
||||
function createMockProcess(): EventEmitter & {
|
||||
stdout: EventEmitter | null;
|
||||
stderr: EventEmitter | null;
|
||||
stdin: { write: ReturnType<typeof vi.fn>; end: ReturnType<typeof vi.fn> } | null;
|
||||
} {
|
||||
const proc = new EventEmitter() as EventEmitter & {
|
||||
stdout: EventEmitter | null;
|
||||
stderr: EventEmitter | null;
|
||||
stdin: { write: ReturnType<typeof vi.fn>; end: ReturnType<typeof vi.fn> } | null;
|
||||
};
|
||||
proc.stdout = new EventEmitter();
|
||||
proc.stderr = new EventEmitter();
|
||||
proc.stdin = { write: vi.fn(), end: vi.fn() };
|
||||
return proc;
|
||||
}
|
||||
|
||||
describe('GitHub OAuth Handlers', () => {
|
||||
let ipcMain: EventEmitter & {
|
||||
handlers: Map<string, Function>;
|
||||
invokeHandler: (channel: string, event: unknown, ...args: unknown[]) => Promise<unknown>;
|
||||
getHandler: (channel: string) => Function | undefined;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
vi.resetModules();
|
||||
|
||||
// Get mocked ipcMain
|
||||
const electron = await import('electron');
|
||||
ipcMain = electron.ipcMain as unknown as typeof ipcMain;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Device Code Parsing', () => {
|
||||
it('should parse device code from standard gh CLI output format', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
mockOpenExternal.mockResolvedValue(undefined);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
// Start the handler
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
// Simulate gh CLI output with device code
|
||||
mockProcess.stderr?.emit('data', '! First copy your one-time code: ABCD-1234\n');
|
||||
mockProcess.stderr?.emit('data', '- Press Enter to open github.com in your browser...\n');
|
||||
|
||||
// Complete the process
|
||||
mockProcess.emit('close', 0);
|
||||
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
expect(result).toHaveProperty('data');
|
||||
const data = (result as { data: { deviceCode: string } }).data;
|
||||
expect(data.deviceCode).toBe('ABCD-1234');
|
||||
});
|
||||
|
||||
it('should parse device code from alternate output format (lowercase "code")', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
mockOpenExternal.mockResolvedValue(undefined);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
// Alternate format: "code: XXXX-XXXX" without "one-time"
|
||||
mockProcess.stderr?.emit('data', 'Enter the code: EFGH-5678\n');
|
||||
mockProcess.emit('close', 0);
|
||||
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { deviceCode: string } }).data;
|
||||
expect(data.deviceCode).toBe('EFGH-5678');
|
||||
});
|
||||
|
||||
it('should parse device code from stdout (not just stderr)', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
mockOpenExternal.mockResolvedValue(undefined);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
// Device code in stdout instead of stderr
|
||||
mockProcess.stdout?.emit('data', '! First copy your one-time code: IJKL-9012\n');
|
||||
mockProcess.emit('close', 0);
|
||||
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { deviceCode: string } }).data;
|
||||
expect(data.deviceCode).toBe('IJKL-9012');
|
||||
});
|
||||
|
||||
it('should handle output without device code gracefully', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
// Output without device code
|
||||
mockProcess.stderr?.emit('data', 'Some other message\n');
|
||||
mockProcess.emit('close', 0);
|
||||
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { deviceCode?: string } }).data;
|
||||
expect(data.deviceCode).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should extract URL from output containing https://github.com/login/device', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
mockOpenExternal.mockResolvedValue(undefined);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
mockProcess.stderr?.emit('data', '! First copy your one-time code: MNOP-3456\n');
|
||||
mockProcess.stderr?.emit('data', 'Then visit https://github.com/login/device to authenticate\n');
|
||||
mockProcess.emit('close', 0);
|
||||
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { authUrl: string } }).data;
|
||||
expect(data.authUrl).toBe('https://github.com/login/device');
|
||||
});
|
||||
});
|
||||
|
||||
describe('shell.openExternal Handling', () => {
|
||||
it('should call shell.openExternal with extracted URL when device code found', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
mockOpenExternal.mockResolvedValue(undefined);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
mockProcess.stderr?.emit('data', '! First copy your one-time code: QRST-7890\n');
|
||||
|
||||
// Wait for next tick to allow async browser opening
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
mockProcess.emit('close', 0);
|
||||
await resultPromise;
|
||||
|
||||
expect(mockOpenExternal).toHaveBeenCalledWith('https://github.com/login/device');
|
||||
});
|
||||
|
||||
it('should set browserOpened to true when shell.openExternal succeeds', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
mockOpenExternal.mockResolvedValue(undefined);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
mockProcess.stderr?.emit('data', '! First copy your one-time code: UVWX-1234\n');
|
||||
|
||||
// Wait for async browser opening
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
mockProcess.emit('close', 0);
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { browserOpened: boolean } }).data;
|
||||
expect(data.browserOpened).toBe(true);
|
||||
});
|
||||
|
||||
it('should set browserOpened to false when shell.openExternal fails', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
mockOpenExternal.mockRejectedValue(new Error('Failed to open browser'));
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
mockProcess.stderr?.emit('data', '! First copy your one-time code: YZAB-5678\n');
|
||||
|
||||
// Wait for async browser opening to fail
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
mockProcess.emit('close', 0);
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { browserOpened: boolean } }).data;
|
||||
expect(data.browserOpened).toBe(false);
|
||||
});
|
||||
|
||||
it('should provide fallbackUrl when browser fails to open', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
mockOpenExternal.mockRejectedValue(new Error('Failed to open browser'));
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
mockProcess.stderr?.emit('data', '! First copy your one-time code: CDEF-9012\n');
|
||||
|
||||
// Wait for async browser opening to fail
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
mockProcess.emit('close', 0);
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { fallbackUrl?: string } }).data;
|
||||
expect(data.fallbackUrl).toBe('https://github.com/login/device');
|
||||
});
|
||||
|
||||
it('should not provide fallbackUrl when browser opens successfully', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
mockOpenExternal.mockResolvedValue(undefined);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
mockProcess.stderr?.emit('data', '! First copy your one-time code: GHIJ-3456\n');
|
||||
|
||||
// Wait for async browser opening
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
mockProcess.emit('close', 0);
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { fallbackUrl?: string } }).data;
|
||||
expect(data.fallbackUrl).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
it('should handle gh CLI process error', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
// Emit error event
|
||||
mockProcess.emit('error', new Error('spawn gh ENOENT'));
|
||||
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', false);
|
||||
expect(result).toHaveProperty('error', 'spawn gh ENOENT');
|
||||
const data = (result as { data: { fallbackUrl: string } }).data;
|
||||
expect(data.fallbackUrl).toBe('https://github.com/login/device');
|
||||
});
|
||||
|
||||
it('should handle non-zero exit code', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
mockProcess.stderr?.emit('data', 'error: some authentication error\n');
|
||||
mockProcess.emit('close', 1);
|
||||
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', false);
|
||||
const data = (result as { data: { fallbackUrl: string } }).data;
|
||||
expect(data.fallbackUrl).toBe('https://github.com/login/device');
|
||||
});
|
||||
|
||||
it('should include device code in error result if it was extracted before failure', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
mockOpenExternal.mockResolvedValue(undefined);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
// Device code output followed by failure
|
||||
mockProcess.stderr?.emit('data', '! First copy your one-time code: KLMN-7890\n');
|
||||
|
||||
// Wait for async browser opening
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
mockProcess.stderr?.emit('data', 'error: authentication failed\n');
|
||||
mockProcess.emit('close', 1);
|
||||
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', false);
|
||||
const data = (result as { data: { deviceCode: string; fallbackUrl: string } }).data;
|
||||
expect(data.deviceCode).toBe('KLMN-7890');
|
||||
expect(data.fallbackUrl).toBe('https://github.com/login/device');
|
||||
});
|
||||
|
||||
it('should provide user-friendly error message on process spawn failure', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
const resultPromise = ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
mockProcess.emit('error', new Error('spawn gh ENOENT'));
|
||||
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result).toHaveProperty('success', false);
|
||||
const data = (result as { data: { message: string } }).data;
|
||||
expect(data.message).toContain('Failed to start GitHub CLI');
|
||||
});
|
||||
});
|
||||
|
||||
describe('gh CLI Check Handler', () => {
|
||||
it('should return installed: true when gh CLI is found', async () => {
|
||||
mockExecSync.mockImplementation((cmd: string) => {
|
||||
if (cmd.includes('which gh') || cmd.includes('where gh')) {
|
||||
return '/usr/local/bin/gh\n';
|
||||
}
|
||||
if (cmd === 'gh --version') {
|
||||
return 'gh version 2.65.0 (2024-01-15)\n';
|
||||
}
|
||||
return '';
|
||||
});
|
||||
|
||||
const { registerCheckGhCli } = await import('../oauth-handlers');
|
||||
registerCheckGhCli();
|
||||
|
||||
const result = await ipcMain.invokeHandler('github:checkCli', {});
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { installed: boolean; version: string } }).data;
|
||||
expect(data.installed).toBe(true);
|
||||
expect(data.version).toContain('gh version');
|
||||
});
|
||||
|
||||
it('should return installed: false when gh CLI is not found', async () => {
|
||||
mockExecSync.mockImplementation(() => {
|
||||
throw new Error('Command not found');
|
||||
});
|
||||
|
||||
const { registerCheckGhCli } = await import('../oauth-handlers');
|
||||
registerCheckGhCli();
|
||||
|
||||
const result = await ipcMain.invokeHandler('github:checkCli', {});
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { installed: boolean } }).data;
|
||||
expect(data.installed).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('gh Auth Check Handler', () => {
|
||||
it('should return authenticated: true with username when logged in', async () => {
|
||||
mockExecSync.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'gh auth status') {
|
||||
return 'Logged in to github.com as testuser\n';
|
||||
}
|
||||
if (cmd === 'gh api user --jq .login') {
|
||||
return 'testuser\n';
|
||||
}
|
||||
return '';
|
||||
});
|
||||
|
||||
const { registerCheckGhAuth } = await import('../oauth-handlers');
|
||||
registerCheckGhAuth();
|
||||
|
||||
const result = await ipcMain.invokeHandler('github:checkAuth', {});
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { authenticated: boolean; username: string } }).data;
|
||||
expect(data.authenticated).toBe(true);
|
||||
expect(data.username).toBe('testuser');
|
||||
});
|
||||
|
||||
it('should return authenticated: false when not logged in', async () => {
|
||||
mockExecSync.mockImplementation(() => {
|
||||
throw new Error('You are not logged into any GitHub hosts');
|
||||
});
|
||||
|
||||
const { registerCheckGhAuth } = await import('../oauth-handlers');
|
||||
registerCheckGhAuth();
|
||||
|
||||
const result = await ipcMain.invokeHandler('github:checkAuth', {});
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: { authenticated: boolean } }).data;
|
||||
expect(data.authenticated).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Spawn Arguments', () => {
|
||||
it('should spawn gh with correct auth login arguments', async () => {
|
||||
const mockProcess = createMockProcess();
|
||||
mockSpawn.mockReturnValue(mockProcess);
|
||||
|
||||
const { registerStartGhAuth } = await import('../oauth-handlers');
|
||||
registerStartGhAuth();
|
||||
|
||||
ipcMain.invokeHandler('github:startAuth', {});
|
||||
|
||||
expect(mockSpawn).toHaveBeenCalledWith(
|
||||
'gh',
|
||||
['auth', 'login', '--web', '--scopes', 'repo'],
|
||||
expect.objectContaining({
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Repository Validation', () => {
|
||||
it('should reject invalid repository format', async () => {
|
||||
const { registerGetGitHubBranches } = await import('../oauth-handlers');
|
||||
registerGetGitHubBranches();
|
||||
|
||||
// Test with injection attempt
|
||||
const result = await ipcMain.invokeHandler(
|
||||
'github:getBranches',
|
||||
{},
|
||||
'owner/repo; rm -rf /',
|
||||
'token'
|
||||
);
|
||||
|
||||
expect(result).toHaveProperty('success', false);
|
||||
expect(result).toHaveProperty('error', 'Invalid repository format. Expected: owner/repo');
|
||||
});
|
||||
|
||||
it('should accept valid repository format', async () => {
|
||||
mockExecFileSync.mockReturnValue('main\nfeature-branch\n');
|
||||
|
||||
const { registerGetGitHubBranches } = await import('../oauth-handlers');
|
||||
registerGetGitHubBranches();
|
||||
|
||||
const result = await ipcMain.invokeHandler(
|
||||
'github:getBranches',
|
||||
{},
|
||||
'valid-owner/valid-repo',
|
||||
'token'
|
||||
);
|
||||
|
||||
expect(result).toHaveProperty('success', true);
|
||||
const data = (result as { data: string[] }).data;
|
||||
expect(data).toContain('main');
|
||||
expect(data).toContain('feature-branch');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -47,11 +47,12 @@ export function registerImportIssues(agentManager: AgentManager): void {
|
||||
};
|
||||
|
||||
// Build description with metadata
|
||||
const labels = issue.labels.map(l => l.name).join(', ');
|
||||
const labelNames = issue.labels.map(l => l.name);
|
||||
const labelsString = labelNames.join(', ');
|
||||
const description = `# ${issue.title}
|
||||
|
||||
**GitHub Issue:** [#${issue.number}](${issue.html_url})
|
||||
${labels ? `**Labels:** ${labels}` : ''}
|
||||
${labelsString ? `**Labels:** ${labelsString}` : ''}
|
||||
|
||||
## Description
|
||||
|
||||
@@ -64,7 +65,8 @@ ${issue.body || 'No description provided.'}
|
||||
issue.number,
|
||||
issue.title,
|
||||
description,
|
||||
issue.html_url
|
||||
issue.html_url,
|
||||
labelNames
|
||||
);
|
||||
|
||||
// Start spec creation with the existing spec directory
|
||||
|
||||
@@ -66,7 +66,7 @@ export function registerInvestigateIssue(
|
||||
): void {
|
||||
ipcMain.on(
|
||||
IPC_CHANNELS.GITHUB_INVESTIGATE_ISSUE,
|
||||
async (_, projectId: string, issueNumber: number) => {
|
||||
async (_, projectId: string, issueNumber: number, selectedCommentIds?: number[]) => {
|
||||
const mainWindow = getMainWindow();
|
||||
if (!mainWindow) return;
|
||||
|
||||
@@ -104,11 +104,16 @@ export function registerInvestigateIssue(
|
||||
};
|
||||
|
||||
// Fetch issue comments for more context
|
||||
const comments = await githubFetch(
|
||||
const allComments = await githubFetch(
|
||||
config.token,
|
||||
`/repos/${config.repo}/issues/${issueNumber}/comments`
|
||||
) as GitHubAPIComment[];
|
||||
|
||||
// Filter comments based on selection (if provided)
|
||||
const comments = selectedCommentIds && selectedCommentIds.length > 0
|
||||
? allComments.filter(c => selectedCommentIds.includes(c.id))
|
||||
: allComments;
|
||||
|
||||
// Build context for the AI investigation
|
||||
const labels = issue.labels.map(l => l.name);
|
||||
const issueContext = buildIssueContext(
|
||||
@@ -141,17 +146,13 @@ export function registerInvestigateIssue(
|
||||
issue.number,
|
||||
issue.title,
|
||||
taskDescription,
|
||||
issue.html_url
|
||||
issue.html_url,
|
||||
labels
|
||||
);
|
||||
|
||||
// Start spec creation with the existing spec directory
|
||||
agentManager.startSpecCreation(
|
||||
specData.specId,
|
||||
project.path,
|
||||
specData.taskDescription,
|
||||
specData.specDir,
|
||||
specData.metadata
|
||||
);
|
||||
// NOTE: We intentionally do NOT call agentManager.startSpecCreation() here
|
||||
// This allows the task to stay in "backlog" status until the user manually starts it
|
||||
// Previously, calling startSpecCreation would auto-start the task immediately
|
||||
|
||||
// Phase 3: Creating task
|
||||
sendProgress(mainWindow, projectId, {
|
||||
|
||||
@@ -6,8 +6,8 @@ import { ipcMain } from 'electron';
|
||||
import { IPC_CHANNELS } from '../../../shared/constants';
|
||||
import type { IPCResult, GitHubIssue } from '../../../shared/types';
|
||||
import { projectStore } from '../../project-store';
|
||||
import { getGitHubConfig, githubFetch } from './utils';
|
||||
import type { GitHubAPIIssue } from './types';
|
||||
import { getGitHubConfig, githubFetch, normalizeRepoReference } from './utils';
|
||||
import type { GitHubAPIIssue, GitHubAPIComment } from './types';
|
||||
|
||||
/**
|
||||
* Transform GitHub API issue to application format
|
||||
@@ -57,16 +57,32 @@ export function registerGetIssues(): void {
|
||||
}
|
||||
|
||||
try {
|
||||
const normalizedRepo = normalizeRepoReference(config.repo);
|
||||
if (!normalizedRepo) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Invalid repository format. Use owner/repo or GitHub URL.'
|
||||
};
|
||||
}
|
||||
|
||||
const issues = await githubFetch(
|
||||
config.token,
|
||||
`/repos/${config.repo}/issues?state=${state}&per_page=100&sort=updated`
|
||||
) as GitHubAPIIssue[];
|
||||
`/repos/${normalizedRepo}/issues?state=${state}&per_page=100&sort=updated`
|
||||
);
|
||||
|
||||
// Ensure issues is an array
|
||||
if (!Array.isArray(issues)) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Unexpected response format from GitHub API'
|
||||
};
|
||||
}
|
||||
|
||||
// Filter out pull requests
|
||||
const issuesOnly = issues.filter(issue => !issue.pull_request);
|
||||
const issuesOnly = issues.filter((issue: GitHubAPIIssue) => !issue.pull_request);
|
||||
|
||||
const result: GitHubIssue[] = issuesOnly.map(issue =>
|
||||
transformIssue(issue, config.repo)
|
||||
const result: GitHubIssue[] = issuesOnly.map((issue: GitHubAPIIssue) =>
|
||||
transformIssue(issue, normalizedRepo)
|
||||
);
|
||||
|
||||
return { success: true, data: result };
|
||||
@@ -98,12 +114,20 @@ export function registerGetIssue(): void {
|
||||
}
|
||||
|
||||
try {
|
||||
const normalizedRepo = normalizeRepoReference(config.repo);
|
||||
if (!normalizedRepo) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Invalid repository format. Use owner/repo or GitHub URL.'
|
||||
};
|
||||
}
|
||||
|
||||
const issue = await githubFetch(
|
||||
config.token,
|
||||
`/repos/${config.repo}/issues/${issueNumber}`
|
||||
`/repos/${normalizedRepo}/issues/${issueNumber}`
|
||||
) as GitHubAPIIssue;
|
||||
|
||||
const result = transformIssue(issue, config.repo);
|
||||
const result = transformIssue(issue, normalizedRepo);
|
||||
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
@@ -116,10 +140,53 @@ export function registerGetIssue(): void {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get comments for a specific issue
|
||||
*/
|
||||
export function registerGetIssueComments(): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITHUB_GET_ISSUE_COMMENTS,
|
||||
async (_, projectId: string, issueNumber: number): Promise<IPCResult<GitHubAPIComment[]>> => {
|
||||
const project = projectStore.getProject(projectId);
|
||||
if (!project) {
|
||||
return { success: false, error: 'Project not found' };
|
||||
}
|
||||
|
||||
const config = getGitHubConfig(project);
|
||||
if (!config) {
|
||||
return { success: false, error: 'No GitHub token or repository configured' };
|
||||
}
|
||||
|
||||
try {
|
||||
const normalizedRepo = normalizeRepoReference(config.repo);
|
||||
if (!normalizedRepo) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Invalid repository format. Use owner/repo or GitHub URL.'
|
||||
};
|
||||
}
|
||||
|
||||
const comments = await githubFetch(
|
||||
config.token,
|
||||
`/repos/${normalizedRepo}/issues/${issueNumber}/comments`
|
||||
) as GitHubAPIComment[];
|
||||
|
||||
return { success: true, data: comments };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to fetch issue comments'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register all issue-related handlers
|
||||
*/
|
||||
export function registerIssueHandlers(): void {
|
||||
registerGetIssues();
|
||||
registerGetIssue();
|
||||
registerGetIssueComments();
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
* Provides a simpler OAuth flow than manual PAT creation
|
||||
*/
|
||||
|
||||
import { ipcMain } from 'electron';
|
||||
import { execSync, spawn } from 'child_process';
|
||||
import { ipcMain, shell } from 'electron';
|
||||
import { execSync, execFileSync, spawn } from 'child_process';
|
||||
import { IPC_CHANNELS } from '../../../shared/constants';
|
||||
import type { IPCResult } from '../../../shared/types';
|
||||
|
||||
@@ -14,13 +14,90 @@ const DEBUG = process.env.DEBUG === 'true' || process.env.NODE_ENV === 'developm
|
||||
function debugLog(message: string, data?: unknown): void {
|
||||
if (DEBUG) {
|
||||
if (data !== undefined) {
|
||||
console.log(`[GitHub OAuth] ${message}`, data);
|
||||
console.warn(`[GitHub OAuth] ${message}`, data);
|
||||
} else {
|
||||
console.log(`[GitHub OAuth] ${message}`);
|
||||
console.warn(`[GitHub OAuth] ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Regex pattern to validate GitHub repository format (owner/repo)
|
||||
// Allows alphanumeric characters, hyphens, underscores, and periods
|
||||
const GITHUB_REPO_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
||||
|
||||
/**
|
||||
* Validate that a repository string matches the expected owner/repo format
|
||||
* Prevents command injection by rejecting strings with shell metacharacters
|
||||
*/
|
||||
function isValidGitHubRepo(repo: string): boolean {
|
||||
return GITHUB_REPO_PATTERN.test(repo);
|
||||
}
|
||||
|
||||
// Regex patterns for parsing device code from gh CLI output
|
||||
// Expected format: "! First copy your one-time code: XXXX-XXXX"
|
||||
// Pattern updated to handle different gh CLI versions - supports:
|
||||
// - "one-time code", "code", or "verification code" prefixes
|
||||
// - Hyphen or space separator in the code (XXXX-XXXX or XXXX XXXX)
|
||||
// Note: Separator is REQUIRED to avoid matching 8-char strings without separator
|
||||
const DEVICE_CODE_PATTERN = /(?:one-time code|verification code|code):\s*([A-Z0-9]{4}[-\s][A-Z0-9]{4})/i;
|
||||
|
||||
// GitHub device flow URL pattern
|
||||
const DEVICE_URL_PATTERN = /https:\/\/github\.com\/login\/device/i;
|
||||
|
||||
// Default GitHub device flow URL
|
||||
const GITHUB_DEVICE_URL = 'https://github.com/login/device';
|
||||
|
||||
/**
|
||||
* Parse device code from gh CLI stdout output
|
||||
* Returns the device code (format: XXXX-XXXX) if found, null otherwise
|
||||
* Normalizes space separator to hyphen (GitHub always expects XXXX-XXXX)
|
||||
*/
|
||||
function parseDeviceCode(output: string): string | null {
|
||||
const match = output.match(DEVICE_CODE_PATTERN);
|
||||
if (match && match[1]) {
|
||||
// Normalize: replace space with hyphen (GitHub expects XXXX-XXXX format)
|
||||
const normalizedCode = match[1].replace(' ', '-');
|
||||
debugLog('Device code extracted successfully (code redacted for security)');
|
||||
return normalizedCode;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse device URL from gh CLI output
|
||||
* Returns the URL if found, or the default GitHub device URL
|
||||
*/
|
||||
function parseDeviceUrl(output: string): string {
|
||||
const match = output.match(DEVICE_URL_PATTERN);
|
||||
if (match) {
|
||||
debugLog('Found device URL in output:', match[0]);
|
||||
return match[0];
|
||||
}
|
||||
// Default to standard GitHub device flow URL
|
||||
return GITHUB_DEVICE_URL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of parsing device flow output from gh CLI
|
||||
*/
|
||||
interface DeviceFlowInfo {
|
||||
deviceCode: string | null;
|
||||
authUrl: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse both device code and URL from combined gh CLI output
|
||||
* Searches through both stdout and stderr as gh may output to either
|
||||
*/
|
||||
function parseDeviceFlowOutput(stdout: string, stderr: string): DeviceFlowInfo {
|
||||
const combinedOutput = `${stdout}\n${stderr}`;
|
||||
|
||||
return {
|
||||
deviceCode: parseDeviceCode(combinedOutput),
|
||||
authUrl: parseDeviceUrl(combinedOutput)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if gh CLI is installed
|
||||
*/
|
||||
@@ -102,14 +179,31 @@ export function registerCheckGhAuth(): void {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Result type for GitHub auth start, including device flow information
|
||||
*/
|
||||
interface GitHubAuthStartResult {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
deviceCode?: string;
|
||||
authUrl?: string;
|
||||
browserOpened?: boolean;
|
||||
/**
|
||||
* Fallback URL provided when browser launch fails.
|
||||
* The frontend should display this URL so users can manually navigate to complete auth.
|
||||
*/
|
||||
fallbackUrl?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start GitHub OAuth flow using gh CLI
|
||||
* This will open the browser for device flow authentication
|
||||
* This will extract the device code from gh CLI output and open the browser
|
||||
* using Electron's shell.openExternal (bypasses macOS child process restrictions)
|
||||
*/
|
||||
export function registerStartGhAuth(): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITHUB_START_AUTH,
|
||||
async (): Promise<IPCResult<{ success: boolean; message?: string }>> => {
|
||||
async (): Promise<IPCResult<GitHubAuthStartResult>> => {
|
||||
debugLog('startGitHubAuth handler called');
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
@@ -123,17 +217,64 @@ export function registerStartGhAuth(): void {
|
||||
|
||||
let output = '';
|
||||
let errorOutput = '';
|
||||
let deviceCodeExtracted = false;
|
||||
let extractedDeviceCode: string | null = null;
|
||||
let extractedAuthUrl: string = GITHUB_DEVICE_URL;
|
||||
let browserOpenedSuccessfully = false;
|
||||
let extractionInProgress = false;
|
||||
|
||||
// Function to attempt device code extraction and browser opening
|
||||
// Uses mutex pattern to prevent race conditions from concurrent data handlers
|
||||
const tryExtractAndOpenBrowser = async () => {
|
||||
if (deviceCodeExtracted || extractionInProgress) return;
|
||||
extractionInProgress = true;
|
||||
|
||||
const deviceFlowInfo = parseDeviceFlowOutput(output, errorOutput);
|
||||
|
||||
if (deviceFlowInfo.deviceCode) {
|
||||
deviceCodeExtracted = true;
|
||||
extractedDeviceCode = deviceFlowInfo.deviceCode;
|
||||
extractedAuthUrl = deviceFlowInfo.authUrl;
|
||||
|
||||
debugLog('Device code extracted successfully (code redacted for security)');
|
||||
debugLog('Auth URL:', extractedAuthUrl);
|
||||
|
||||
// Open browser using Electron's shell.openExternal
|
||||
// This bypasses macOS child process restrictions that block gh CLI's browser launch
|
||||
try {
|
||||
await shell.openExternal(extractedAuthUrl);
|
||||
browserOpenedSuccessfully = true;
|
||||
debugLog('Browser opened successfully via shell.openExternal');
|
||||
} catch (browserError) {
|
||||
debugLog('Failed to open browser:', browserError instanceof Error ? browserError.message : browserError);
|
||||
browserOpenedSuccessfully = false;
|
||||
// Don't fail here - we'll return the device code so user can manually navigate
|
||||
}
|
||||
|
||||
// Extraction complete - mutex flag stays true to prevent re-extraction
|
||||
// The deviceCodeExtracted flag will prevent future attempts
|
||||
extractionInProgress = false;
|
||||
} else {
|
||||
// No device code found yet, allow next data chunk to try again
|
||||
extractionInProgress = false;
|
||||
}
|
||||
};
|
||||
|
||||
ghProcess.stdout?.on('data', (data) => {
|
||||
const chunk = data.toString();
|
||||
output += chunk;
|
||||
debugLog('gh stdout:', chunk);
|
||||
// Try to extract device code as data comes in
|
||||
// Use void to explicitly ignore promise
|
||||
void tryExtractAndOpenBrowser();
|
||||
});
|
||||
|
||||
ghProcess.stderr?.on('data', (data) => {
|
||||
const chunk = data.toString();
|
||||
errorOutput += chunk;
|
||||
debugLog('gh stderr:', chunk);
|
||||
// gh often outputs to stderr, so check there too
|
||||
void tryExtractAndOpenBrowser();
|
||||
});
|
||||
|
||||
ghProcess.on('close', (code) => {
|
||||
@@ -142,17 +283,39 @@ export function registerStartGhAuth(): void {
|
||||
debugLog('Full stderr:', errorOutput);
|
||||
|
||||
if (code === 0) {
|
||||
// Success case - include fallbackUrl if browser failed to open
|
||||
// so the user can manually navigate if needed
|
||||
resolve({
|
||||
success: true,
|
||||
data: {
|
||||
success: true,
|
||||
message: 'Successfully authenticated with GitHub'
|
||||
message: browserOpenedSuccessfully
|
||||
? 'Successfully authenticated with GitHub'
|
||||
: 'Authentication successful. Browser could not be opened automatically.',
|
||||
deviceCode: extractedDeviceCode || undefined,
|
||||
authUrl: extractedAuthUrl,
|
||||
browserOpened: browserOpenedSuccessfully,
|
||||
// Provide fallback URL when browser failed to open
|
||||
fallbackUrl: !browserOpenedSuccessfully ? extractedAuthUrl : undefined
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Even if auth failed, return device code info if we extracted it
|
||||
// This allows user to retry manually with the fallback URL
|
||||
const fallbackUrlForManualAuth = extractedDeviceCode ? extractedAuthUrl : GITHUB_DEVICE_URL;
|
||||
|
||||
resolve({
|
||||
success: false,
|
||||
error: errorOutput || `Authentication failed with exit code ${code}`
|
||||
error: errorOutput || `Authentication failed with exit code ${code}`,
|
||||
data: {
|
||||
success: false,
|
||||
deviceCode: extractedDeviceCode || undefined,
|
||||
authUrl: extractedAuthUrl,
|
||||
browserOpened: browserOpenedSuccessfully,
|
||||
// Always provide fallback URL on failure for manual recovery
|
||||
fallbackUrl: fallbackUrlForManualAuth,
|
||||
message: 'Authentication failed. Please visit the URL manually to complete authentication.'
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -161,14 +324,28 @@ export function registerStartGhAuth(): void {
|
||||
debugLog('gh process error:', error.message);
|
||||
resolve({
|
||||
success: false,
|
||||
error: error.message
|
||||
error: error.message,
|
||||
data: {
|
||||
success: false,
|
||||
browserOpened: false,
|
||||
// Provide fallback URL so user can attempt manual auth
|
||||
fallbackUrl: GITHUB_DEVICE_URL,
|
||||
message: 'Failed to start GitHub CLI. Please visit the URL manually to authenticate.'
|
||||
}
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
debugLog('Exception in startGitHubAuth:', error instanceof Error ? error.message : error);
|
||||
resolve({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
data: {
|
||||
success: false,
|
||||
browserOpened: false,
|
||||
// Provide fallback URL for manual authentication recovery
|
||||
fallbackUrl: GITHUB_DEVICE_URL,
|
||||
message: 'An unexpected error occurred. Please visit the URL manually to authenticate.'
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -296,6 +473,303 @@ export function registerListUserRepos(): void {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect GitHub repository from git remote origin
|
||||
*/
|
||||
export function registerDetectGitHubRepo(): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITHUB_DETECT_REPO,
|
||||
async (_event: Electron.IpcMainInvokeEvent, projectPath: string): Promise<IPCResult<string>> => {
|
||||
debugLog('detectGitHubRepo handler called', { projectPath });
|
||||
try {
|
||||
// Get the remote URL
|
||||
debugLog('Running: git remote get-url origin');
|
||||
const remoteUrl = execSync('git remote get-url origin', {
|
||||
encoding: 'utf-8',
|
||||
cwd: projectPath,
|
||||
stdio: 'pipe'
|
||||
}).trim();
|
||||
|
||||
debugLog('Remote URL:', remoteUrl);
|
||||
|
||||
// Parse GitHub repo from URL
|
||||
// Formats:
|
||||
// - https://github.com/owner/repo.git
|
||||
// - git@github.com:owner/repo.git
|
||||
// - https://github.com/owner/repo
|
||||
const match = remoteUrl.match(/github\.com[/:]([^/]+\/[^/]+?)(?:\.git)?$/);
|
||||
if (match) {
|
||||
const repo = match[1];
|
||||
debugLog('Detected repo:', repo);
|
||||
return {
|
||||
success: true,
|
||||
data: repo
|
||||
};
|
||||
}
|
||||
|
||||
debugLog('Could not parse GitHub repo from URL');
|
||||
return {
|
||||
success: false,
|
||||
error: 'Remote URL is not a GitHub repository'
|
||||
};
|
||||
} catch (error) {
|
||||
debugLog('Failed to detect repo:', error instanceof Error ? error.message : error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to detect GitHub repository'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get branches from GitHub repository
|
||||
*/
|
||||
export function registerGetGitHubBranches(): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITHUB_GET_BRANCHES,
|
||||
async (_event: Electron.IpcMainInvokeEvent, repo: string, _token: string): Promise<IPCResult<string[]>> => {
|
||||
debugLog('getGitHubBranches handler called', { repo });
|
||||
|
||||
// Validate repo format to prevent command injection
|
||||
if (!isValidGitHubRepo(repo)) {
|
||||
debugLog('Invalid repo format rejected:', repo);
|
||||
return {
|
||||
success: false,
|
||||
error: 'Invalid repository format. Expected: owner/repo'
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
// Use gh CLI to list branches (uses authenticated session)
|
||||
// Use execFileSync with separate arguments to avoid shell injection
|
||||
const apiEndpoint = `repos/${repo}/branches`;
|
||||
debugLog(`Running: gh api ${apiEndpoint} --paginate --jq '.[].name'`);
|
||||
const output = execFileSync(
|
||||
'gh',
|
||||
['api', apiEndpoint, '--paginate', '--jq', '.[].name'],
|
||||
{
|
||||
encoding: 'utf-8',
|
||||
stdio: 'pipe'
|
||||
}
|
||||
);
|
||||
|
||||
const branches = output.trim().split('\n').filter(b => b.length > 0);
|
||||
debugLog('Found branches:', branches.length);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: branches
|
||||
};
|
||||
} catch (error) {
|
||||
debugLog('Failed to get branches:', error instanceof Error ? error.message : error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to get branches'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new GitHub repository using gh CLI
|
||||
*/
|
||||
export function registerCreateGitHubRepo(): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITHUB_CREATE_REPO,
|
||||
async (
|
||||
_event: Electron.IpcMainInvokeEvent,
|
||||
repoName: string,
|
||||
options: { description?: string; isPrivate?: boolean; projectPath: string; owner?: string }
|
||||
): Promise<IPCResult<{ fullName: string; url: string }>> => {
|
||||
debugLog('createGitHubRepo handler called', { repoName, options });
|
||||
|
||||
// Validate repo name - only alphanumeric, hyphens, underscores
|
||||
if (!/^[A-Za-z0-9_.-]+$/.test(repoName)) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Invalid repository name. Use only letters, numbers, hyphens, underscores, and periods.'
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
// Get the authenticated username
|
||||
const username = execSync('gh api user --jq .login', {
|
||||
encoding: 'utf-8',
|
||||
stdio: 'pipe'
|
||||
}).trim();
|
||||
|
||||
// Determine the owner (personal account or organization)
|
||||
const owner = options.owner || username;
|
||||
const isOrgRepo = owner !== username;
|
||||
|
||||
// Build the full repo name (owner/repo format for orgs)
|
||||
const repoFullName = isOrgRepo ? `${owner}/${repoName}` : repoName;
|
||||
|
||||
// Build gh repo create command arguments
|
||||
const args = ['repo', 'create', repoFullName, '--source', options.projectPath];
|
||||
|
||||
if (options.isPrivate) {
|
||||
args.push('--private');
|
||||
} else {
|
||||
args.push('--public');
|
||||
}
|
||||
|
||||
if (options.description) {
|
||||
args.push('--description', options.description);
|
||||
}
|
||||
|
||||
// Push to remote after creation
|
||||
args.push('--push');
|
||||
|
||||
debugLog('Running: gh', args);
|
||||
const output = execFileSync('gh', args, {
|
||||
encoding: 'utf-8',
|
||||
cwd: options.projectPath,
|
||||
stdio: 'pipe'
|
||||
});
|
||||
|
||||
debugLog('gh repo create output:', output);
|
||||
|
||||
const fullName = `${owner}/${repoName}`;
|
||||
const url = `https://github.com/${fullName}`;
|
||||
|
||||
debugLog('Created repo:', { fullName, url });
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { fullName, url }
|
||||
};
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to create repository';
|
||||
debugLog('Failed to create repo:', errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: errorMessage
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a remote origin to a local git repository
|
||||
*/
|
||||
export function registerAddGitRemote(): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITHUB_ADD_REMOTE,
|
||||
async (
|
||||
_event: Electron.IpcMainInvokeEvent,
|
||||
projectPath: string,
|
||||
repoFullName: string
|
||||
): Promise<IPCResult<{ remoteUrl: string }>> => {
|
||||
debugLog('addGitRemote handler called', { projectPath, repoFullName });
|
||||
|
||||
// Validate repo format
|
||||
if (!isValidGitHubRepo(repoFullName)) {
|
||||
return {
|
||||
success: false,
|
||||
error: 'Invalid repository format. Expected: owner/repo'
|
||||
};
|
||||
}
|
||||
|
||||
const remoteUrl = `https://github.com/${repoFullName}.git`;
|
||||
|
||||
try {
|
||||
// Check if origin already exists
|
||||
try {
|
||||
execSync('git remote get-url origin', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: 'pipe'
|
||||
});
|
||||
// Origin exists, remove it first
|
||||
debugLog('Removing existing origin remote');
|
||||
execSync('git remote remove origin', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: 'pipe'
|
||||
});
|
||||
} catch {
|
||||
// No origin exists, which is fine
|
||||
}
|
||||
|
||||
// Add the remote
|
||||
debugLog('Adding remote origin:', remoteUrl);
|
||||
execFileSync('git', ['remote', 'add', 'origin', remoteUrl], {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8',
|
||||
stdio: 'pipe'
|
||||
});
|
||||
|
||||
debugLog('Remote added successfully');
|
||||
return {
|
||||
success: true,
|
||||
data: { remoteUrl }
|
||||
};
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to add remote';
|
||||
debugLog('Failed to add remote:', errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: errorMessage
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* List user's GitHub organizations
|
||||
*/
|
||||
export function registerListGitHubOrgs(): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITHUB_LIST_ORGS,
|
||||
async (): Promise<IPCResult<{ orgs: Array<{ login: string; avatarUrl?: string }> }>> => {
|
||||
debugLog('listGitHubOrgs handler called');
|
||||
|
||||
try {
|
||||
// Get user's organizations
|
||||
const output = execSync('gh api user/orgs --jq \'.[] | {login: .login, avatarUrl: .avatar_url}\'', {
|
||||
encoding: 'utf-8',
|
||||
stdio: 'pipe'
|
||||
});
|
||||
|
||||
// Parse the JSON lines output
|
||||
const orgs: Array<{ login: string; avatarUrl?: string }> = [];
|
||||
const lines = output.trim().split('\n').filter(line => line.trim());
|
||||
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const org = JSON.parse(line);
|
||||
orgs.push({
|
||||
login: org.login,
|
||||
avatarUrl: org.avatarUrl
|
||||
});
|
||||
} catch {
|
||||
// Skip invalid JSON lines
|
||||
}
|
||||
}
|
||||
|
||||
debugLog('Found organizations:', orgs.length);
|
||||
return {
|
||||
success: true,
|
||||
data: { orgs }
|
||||
};
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to list organizations';
|
||||
debugLog('Failed to list orgs:', errorMessage);
|
||||
return {
|
||||
success: true, // Return success with empty array - user might not have any orgs
|
||||
data: { orgs: [] }
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register all GitHub OAuth handlers
|
||||
*/
|
||||
@@ -307,5 +781,10 @@ export function registerGithubOAuthHandlers(): void {
|
||||
registerGetGhToken();
|
||||
registerGetGhUser();
|
||||
registerListUserRepos();
|
||||
registerDetectGitHubRepo();
|
||||
registerGetGitHubBranches();
|
||||
registerCreateGitHubRepo();
|
||||
registerAddGitRemote();
|
||||
registerListGitHubOrgs();
|
||||
debugLog('GitHub OAuth handlers registered');
|
||||
}
|
||||
|
||||
@@ -4,9 +4,12 @@
|
||||
|
||||
import { ipcMain } from 'electron';
|
||||
import { execSync } from 'child_process';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { IPC_CHANNELS } from '../../../shared/constants';
|
||||
import type { IPCResult } from '../../../shared/types';
|
||||
import type { IPCResult, GitCommit, VersionSuggestion } from '../../../shared/types';
|
||||
import { projectStore } from '../../project-store';
|
||||
import { changelogService } from '../../changelog-service';
|
||||
import type { ReleaseOptions } from './types';
|
||||
|
||||
/**
|
||||
@@ -118,9 +121,146 @@ export function registerCreateRelease(): void {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the latest git tag in the repository
|
||||
*/
|
||||
function getLatestTag(projectPath: string): string | null {
|
||||
try {
|
||||
const tag = execSync('git describe --tags --abbrev=0 2>/dev/null || echo ""', {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8'
|
||||
}).trim();
|
||||
return tag || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get commits since a specific tag (or all commits if no tag)
|
||||
*/
|
||||
function getCommitsSinceTag(projectPath: string, tag: string | null): GitCommit[] {
|
||||
try {
|
||||
const range = tag ? `${tag}..HEAD` : 'HEAD';
|
||||
const format = '%H|%s|%an|%ae|%aI';
|
||||
const output = execSync(`git log ${range} --pretty=format:"${format}"`, {
|
||||
cwd: projectPath,
|
||||
encoding: 'utf-8'
|
||||
}).trim();
|
||||
|
||||
if (!output) return [];
|
||||
|
||||
return output.split('\n').map(line => {
|
||||
const [fullHash, subject, authorName, authorEmail, date] = line.split('|');
|
||||
return {
|
||||
hash: fullHash.substring(0, 7),
|
||||
fullHash,
|
||||
subject,
|
||||
author: authorName,
|
||||
authorEmail,
|
||||
date
|
||||
};
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current version from package.json
|
||||
*/
|
||||
function getCurrentVersion(projectPath: string): string {
|
||||
try {
|
||||
const pkgPath = path.join(projectPath, 'package.json');
|
||||
if (!existsSync(pkgPath)) {
|
||||
return '0.0.0';
|
||||
}
|
||||
const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
|
||||
return pkg.version || '0.0.0';
|
||||
} catch {
|
||||
return '0.0.0';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggest version for release using AI analysis of commits
|
||||
*/
|
||||
export function registerSuggestVersion(): void {
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.RELEASE_SUGGEST_VERSION,
|
||||
async (_, projectId: string): Promise<IPCResult<VersionSuggestion>> => {
|
||||
const project = projectStore.getProject(projectId);
|
||||
if (!project) {
|
||||
return { success: false, error: 'Project not found' };
|
||||
}
|
||||
|
||||
try {
|
||||
// Get current version from package.json
|
||||
const currentVersion = getCurrentVersion(project.path);
|
||||
|
||||
// Get latest tag
|
||||
const latestTag = getLatestTag(project.path);
|
||||
|
||||
// Get commits since last tag
|
||||
const commits = getCommitsSinceTag(project.path, latestTag);
|
||||
|
||||
if (commits.length === 0) {
|
||||
// No commits since last release, suggest patch bump
|
||||
const [major, minor, patch] = currentVersion.split('.').map(Number);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
suggestedVersion: `${major}.${minor}.${patch + 1}`,
|
||||
currentVersion,
|
||||
bumpType: 'patch',
|
||||
reason: 'No new commits since last release',
|
||||
commitCount: 0
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Use AI to analyze commits and suggest version
|
||||
const suggestion = await changelogService.suggestVersionFromCommits(
|
||||
project.path,
|
||||
commits,
|
||||
currentVersion
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
suggestedVersion: suggestion.version,
|
||||
currentVersion,
|
||||
bumpType: suggestion.reason.includes('breaking') ? 'major' :
|
||||
suggestion.reason.includes('feature') || suggestion.reason.includes('minor') ? 'minor' : 'patch',
|
||||
reason: suggestion.reason,
|
||||
commitCount: commits.length
|
||||
}
|
||||
};
|
||||
} catch (_error) {
|
||||
// Fallback to patch bump on error
|
||||
const currentVersion = getCurrentVersion(project.path);
|
||||
const [major, minor, patch] = currentVersion.split('.').map(Number);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
suggestedVersion: `${major}.${minor}.${patch + 1}`,
|
||||
currentVersion,
|
||||
bumpType: 'patch',
|
||||
reason: 'Fallback suggestion (AI analysis unavailable)',
|
||||
commitCount: 0
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register all release-related handlers
|
||||
*/
|
||||
export function registerReleaseHandlers(): void {
|
||||
registerCreateRelease();
|
||||
registerSuggestVersion();
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { ipcMain } from 'electron';
|
||||
import { IPC_CHANNELS } from '../../../shared/constants';
|
||||
import type { IPCResult, GitHubRepository, GitHubSyncStatus } from '../../../shared/types';
|
||||
import { projectStore } from '../../project-store';
|
||||
import { getGitHubConfig, githubFetch } from './utils';
|
||||
import { getGitHubConfig, githubFetch, normalizeRepoReference } from './utils';
|
||||
import type { GitHubAPIRepository } from './types';
|
||||
|
||||
/**
|
||||
@@ -33,16 +33,28 @@ export function registerCheckConnection(): void {
|
||||
}
|
||||
|
||||
try {
|
||||
// Normalize repo reference (handles full URLs, git URLs, etc.)
|
||||
const normalizedRepo = normalizeRepoReference(config.repo);
|
||||
if (!normalizedRepo) {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
connected: false,
|
||||
error: 'Invalid repository format. Use owner/repo or GitHub URL.'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Fetch repo info
|
||||
const repoData = await githubFetch(
|
||||
config.token,
|
||||
`/repos/${config.repo}`
|
||||
`/repos/${normalizedRepo}`
|
||||
) as { full_name: string; description?: string };
|
||||
|
||||
// Count open issues
|
||||
const issuesData = await githubFetch(
|
||||
config.token,
|
||||
`/repos/${config.repo}/issues?state=open&per_page=1`
|
||||
`/repos/${normalizedRepo}/issues?state=open&per_page=1`
|
||||
) as unknown[];
|
||||
|
||||
const openCount = Array.isArray(issuesData) ? issuesData.length : 0;
|
||||
@@ -71,7 +83,7 @@ export function registerCheckConnection(): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of GitHub repositories
|
||||
* Get list of GitHub repositories (personal + organization)
|
||||
*/
|
||||
export function registerGetRepositories(): void {
|
||||
ipcMain.handle(
|
||||
@@ -88,9 +100,11 @@ export function registerGetRepositories(): void {
|
||||
}
|
||||
|
||||
try {
|
||||
// Fetch user's personal + organization repos
|
||||
// affiliation parameter includes: owner, collaborator, organization_member
|
||||
const repos = await githubFetch(
|
||||
config.token,
|
||||
'/user/repos?per_page=100&sort=updated'
|
||||
'/user/repos?per_page=100&sort=updated&affiliation=owner,collaborator,organization_member'
|
||||
) as GitHubAPIRepository[];
|
||||
|
||||
const result: GitHubRepository[] = repos.map(repo => ({
|
||||
|
||||
@@ -51,6 +51,58 @@ function slugifyTitle(title: string): string {
|
||||
.substring(0, 50);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine task category based on GitHub issue labels
|
||||
* Maps to TaskCategory type from shared/types/task.ts
|
||||
*/
|
||||
function determineCategoryFromLabels(labels: string[]): 'feature' | 'bug_fix' | 'refactoring' | 'documentation' | 'security' | 'performance' | 'ui_ux' | 'infrastructure' | 'testing' {
|
||||
const lowerLabels = labels.map(l => l.toLowerCase());
|
||||
|
||||
// Check for bug labels
|
||||
if (lowerLabels.some(l => l.includes('bug') || l.includes('defect') || l.includes('error') || l.includes('fix'))) {
|
||||
return 'bug_fix';
|
||||
}
|
||||
|
||||
// Check for security labels
|
||||
if (lowerLabels.some(l => l.includes('security') || l.includes('vulnerability') || l.includes('cve'))) {
|
||||
return 'security';
|
||||
}
|
||||
|
||||
// Check for performance labels
|
||||
if (lowerLabels.some(l => l.includes('performance') || l.includes('optimization') || l.includes('speed'))) {
|
||||
return 'performance';
|
||||
}
|
||||
|
||||
// Check for UI/UX labels
|
||||
if (lowerLabels.some(l => l.includes('ui') || l.includes('ux') || l.includes('design') || l.includes('styling'))) {
|
||||
return 'ui_ux';
|
||||
}
|
||||
|
||||
// Check for infrastructure labels
|
||||
if (lowerLabels.some(l => l.includes('infrastructure') || l.includes('devops') || l.includes('deployment') || l.includes('ci') || l.includes('cd'))) {
|
||||
return 'infrastructure';
|
||||
}
|
||||
|
||||
// Check for testing labels
|
||||
if (lowerLabels.some(l => l.includes('test') || l.includes('testing') || l.includes('qa'))) {
|
||||
return 'testing';
|
||||
}
|
||||
|
||||
// Check for refactoring labels
|
||||
if (lowerLabels.some(l => l.includes('refactor') || l.includes('cleanup') || l.includes('maintenance') || l.includes('chore') || l.includes('tech-debt') || l.includes('technical debt'))) {
|
||||
return 'refactoring';
|
||||
}
|
||||
|
||||
// Check for documentation labels
|
||||
if (lowerLabels.some(l => l.includes('documentation') || l.includes('docs'))) {
|
||||
return 'documentation';
|
||||
}
|
||||
|
||||
// Check for enhancement/feature labels (default)
|
||||
// This catches 'enhancement', 'feature', 'improvement', or any unlabeled issues
|
||||
return 'feature';
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new spec directory and initial files
|
||||
*/
|
||||
@@ -59,7 +111,8 @@ export function createSpecForIssue(
|
||||
issueNumber: number,
|
||||
issueTitle: string,
|
||||
taskDescription: string,
|
||||
githubUrl: string
|
||||
githubUrl: string,
|
||||
labels: string[] = []
|
||||
): SpecCreationData {
|
||||
const specsBaseDir = getSpecsDir(project.autoBuildPath);
|
||||
const specsDir = path.join(project.path, specsBaseDir);
|
||||
@@ -104,12 +157,15 @@ export function createSpecForIssue(
|
||||
JSON.stringify(requirements, null, 2)
|
||||
);
|
||||
|
||||
// Determine category from GitHub issue labels
|
||||
const category = determineCategoryFromLabels(labels);
|
||||
|
||||
// task_metadata.json
|
||||
const metadata: TaskMetadata = {
|
||||
sourceType: 'github',
|
||||
githubIssueNumber: issueNumber,
|
||||
githubUrl,
|
||||
category: 'feature'
|
||||
category
|
||||
};
|
||||
writeFileSync(
|
||||
path.join(specDir, 'task_metadata.json'),
|
||||
|
||||
@@ -38,8 +38,11 @@ export interface GitHubAPIRepository {
|
||||
}
|
||||
|
||||
export interface GitHubAPIComment {
|
||||
id: number;
|
||||
body: string;
|
||||
user: { login: string };
|
||||
user: { login: string; avatar_url?: string };
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface ReleaseOptions {
|
||||
|
||||
@@ -54,6 +54,32 @@ export function getGitHubConfig(project: Project): GitHubConfig | null {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a GitHub repository reference to owner/repo format
|
||||
* Handles:
|
||||
* - owner/repo (already normalized)
|
||||
* - https://github.com/owner/repo
|
||||
* - https://github.com/owner/repo.git
|
||||
* - git@github.com:owner/repo.git
|
||||
*/
|
||||
export function normalizeRepoReference(repo: string): string {
|
||||
if (!repo) return '';
|
||||
|
||||
// Remove trailing .git if present
|
||||
let normalized = repo.replace(/\.git$/, '');
|
||||
|
||||
// Handle full GitHub URLs
|
||||
if (normalized.startsWith('https://github.com/')) {
|
||||
normalized = normalized.replace('https://github.com/', '');
|
||||
} else if (normalized.startsWith('http://github.com/')) {
|
||||
normalized = normalized.replace('http://github.com/', '');
|
||||
} else if (normalized.startsWith('git@github.com:')) {
|
||||
normalized = normalized.replace('git@github.com:', '');
|
||||
}
|
||||
|
||||
return normalized.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a request to the GitHub API
|
||||
*/
|
||||
@@ -69,7 +95,7 @@ export async function githubFetch(
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'User-Agent': 'Auto-Claude-UI',
|
||||
...options.headers
|
||||
|
||||
@@ -3,10 +3,45 @@
|
||||
*/
|
||||
|
||||
import type { IpcMainEvent, IpcMainInvokeEvent, BrowserWindow } from 'electron';
|
||||
import { IPC_CHANNELS } from '../../../shared/constants';
|
||||
import type { IPCResult, IdeationConfig, IdeationGenerationStatus } from '../../../shared/types';
|
||||
import { app } from 'electron';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { IPC_CHANNELS, DEFAULT_APP_SETTINGS, DEFAULT_FEATURE_MODELS, DEFAULT_FEATURE_THINKING } from '../../../shared/constants';
|
||||
import type { IPCResult, IdeationConfig, IdeationGenerationStatus, AppSettings } from '../../../shared/types';
|
||||
import { projectStore } from '../../project-store';
|
||||
import type { AgentManager } from '../../agent';
|
||||
import { debugLog, debugError } from '../../../shared/utils/debug-logger';
|
||||
|
||||
/**
|
||||
* Read ideation feature settings from the settings file
|
||||
*/
|
||||
function getIdeationFeatureSettings(): { model?: string; thinkingLevel?: string } {
|
||||
const settingsPath = path.join(app.getPath('userData'), 'settings.json');
|
||||
|
||||
try {
|
||||
if (existsSync(settingsPath)) {
|
||||
const content = readFileSync(settingsPath, 'utf-8');
|
||||
const settings: AppSettings = { ...DEFAULT_APP_SETTINGS, ...JSON.parse(content) };
|
||||
|
||||
// Get ideation-specific settings
|
||||
const featureModels = settings.featureModels || DEFAULT_FEATURE_MODELS;
|
||||
const featureThinking = settings.featureThinking || DEFAULT_FEATURE_THINKING;
|
||||
|
||||
return {
|
||||
model: featureModels.ideation,
|
||||
thinkingLevel: featureThinking.ideation
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
debugError('[Ideation Handler] Failed to read feature settings:', error);
|
||||
}
|
||||
|
||||
// Return defaults if settings file doesn't exist or fails to parse
|
||||
return {
|
||||
model: DEFAULT_FEATURE_MODELS.ideation,
|
||||
thinkingLevel: DEFAULT_FEATURE_THINKING.ideation
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Start ideation generation for a project
|
||||
@@ -18,10 +53,27 @@ export function startIdeationGeneration(
|
||||
agentManager: AgentManager,
|
||||
mainWindow: BrowserWindow | null
|
||||
): void {
|
||||
// Get feature settings and merge with config
|
||||
const featureSettings = getIdeationFeatureSettings();
|
||||
const configWithSettings: IdeationConfig = {
|
||||
...config,
|
||||
model: config.model || featureSettings.model,
|
||||
thinkingLevel: config.thinkingLevel || featureSettings.thinkingLevel
|
||||
};
|
||||
|
||||
debugLog('[Ideation Handler] Start generation request:', {
|
||||
projectId,
|
||||
enabledTypes: configWithSettings.enabledTypes,
|
||||
maxIdeasPerType: configWithSettings.maxIdeasPerType,
|
||||
model: configWithSettings.model,
|
||||
thinkingLevel: configWithSettings.thinkingLevel
|
||||
});
|
||||
|
||||
if (!mainWindow) return;
|
||||
|
||||
const project = projectStore.getProject(projectId);
|
||||
if (!project) {
|
||||
debugLog('[Ideation Handler] Project not found:', projectId);
|
||||
mainWindow.webContents.send(
|
||||
IPC_CHANNELS.IDEATION_ERROR,
|
||||
projectId,
|
||||
@@ -30,8 +82,15 @@ export function startIdeationGeneration(
|
||||
return;
|
||||
}
|
||||
|
||||
debugLog('[Ideation Handler] Starting agent manager generation:', {
|
||||
projectId,
|
||||
projectPath: project.path,
|
||||
model: configWithSettings.model,
|
||||
thinkingLevel: configWithSettings.thinkingLevel
|
||||
});
|
||||
|
||||
// Start ideation generation via agent manager
|
||||
agentManager.startIdeationGeneration(projectId, project.path, config, false);
|
||||
agentManager.startIdeationGeneration(projectId, project.path, configWithSettings, false);
|
||||
|
||||
// Send initial progress
|
||||
mainWindow.webContents.send(
|
||||
@@ -55,6 +114,20 @@ export function refreshIdeationSession(
|
||||
agentManager: AgentManager,
|
||||
mainWindow: BrowserWindow | null
|
||||
): void {
|
||||
// Get feature settings and merge with config
|
||||
const featureSettings = getIdeationFeatureSettings();
|
||||
const configWithSettings: IdeationConfig = {
|
||||
...config,
|
||||
model: config.model || featureSettings.model,
|
||||
thinkingLevel: config.thinkingLevel || featureSettings.thinkingLevel
|
||||
};
|
||||
|
||||
debugLog('[Ideation Handler] Refresh session request:', {
|
||||
projectId,
|
||||
model: configWithSettings.model,
|
||||
thinkingLevel: configWithSettings.thinkingLevel
|
||||
});
|
||||
|
||||
if (!mainWindow) return;
|
||||
|
||||
const project = projectStore.getProject(projectId);
|
||||
@@ -68,7 +141,7 @@ export function refreshIdeationSession(
|
||||
}
|
||||
|
||||
// Start ideation regeneration with refresh flag
|
||||
agentManager.startIdeationGeneration(projectId, project.path, config, true);
|
||||
agentManager.startIdeationGeneration(projectId, project.path, configWithSettings, true);
|
||||
|
||||
// Send initial progress
|
||||
mainWindow.webContents.send(
|
||||
@@ -91,9 +164,14 @@ export async function stopIdeationGeneration(
|
||||
agentManager: AgentManager,
|
||||
mainWindow: BrowserWindow | null
|
||||
): Promise<IPCResult> {
|
||||
debugLog('[Ideation Handler] Stop generation request:', { projectId });
|
||||
|
||||
const wasStopped = agentManager.stopIdeation(projectId);
|
||||
|
||||
debugLog('[Ideation Handler] Stop result:', { projectId, wasStopped });
|
||||
|
||||
if (wasStopped && mainWindow) {
|
||||
debugLog('[Ideation Handler] Sending stopped event to renderer');
|
||||
mainWindow.webContents.send(IPC_CHANNELS.IDEATION_STOPPED, projectId);
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ export async function getIdeationSession(
|
||||
|
||||
try {
|
||||
// Transform snake_case to camelCase for frontend
|
||||
const enabledTypes = (rawIdeation.config?.enabled_types || rawIdeation.config?.enabledTypes || []) as any[];
|
||||
const enabledTypes = (rawIdeation.config?.enabled_types || rawIdeation.config?.enabledTypes || []) as unknown[];
|
||||
|
||||
const session: IdeationSession = {
|
||||
id: rawIdeation.id || `ideation-${Date.now()}`,
|
||||
|
||||
@@ -160,7 +160,7 @@ function buildTaskMetadata(idea: RawIdea): TaskMetadata {
|
||||
function createSpecFiles(
|
||||
specDir: string,
|
||||
idea: RawIdea,
|
||||
taskDescription: string
|
||||
_taskDescription: string
|
||||
): void {
|
||||
// Create the spec directory
|
||||
mkdirSync(specDir, { recursive: true });
|
||||
|
||||
@@ -27,6 +27,7 @@ import { registerIdeationHandlers } from './ideation-handlers';
|
||||
import { registerChangelogHandlers } from './changelog-handlers';
|
||||
import { registerInsightsHandlers } from './insights-handlers';
|
||||
import { registerDockerHandlers } from './docker-handlers';
|
||||
import { registerAppUpdateHandlers } from './app-update-handlers';
|
||||
import { notificationService } from '../notification-service';
|
||||
|
||||
/**
|
||||
@@ -91,10 +92,13 @@ export function setupIpcHandlers(
|
||||
// Insights handlers
|
||||
registerInsightsHandlers(getMainWindow);
|
||||
|
||||
// Docker & infrastructure handlers (for Graphiti/FalkorDB)
|
||||
// Memory & infrastructure handlers (for Graphiti/LadybugDB)
|
||||
registerDockerHandlers();
|
||||
|
||||
console.log('[IPC] All handler modules registered successfully');
|
||||
// App auto-update handlers
|
||||
registerAppUpdateHandlers();
|
||||
|
||||
console.warn('[IPC] All handler modules registered successfully');
|
||||
}
|
||||
|
||||
// Re-export all individual registration functions for potential custom usage
|
||||
@@ -114,5 +118,6 @@ export {
|
||||
registerIdeationHandlers,
|
||||
registerChangelogHandlers,
|
||||
registerInsightsHandlers,
|
||||
registerDockerHandlers
|
||||
registerDockerHandlers,
|
||||
registerAppUpdateHandlers
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { BrowserWindow } from 'electron';
|
||||
import path from 'path';
|
||||
import { existsSync, readdirSync, mkdirSync, writeFileSync } from 'fs';
|
||||
import { IPC_CHANNELS, getSpecsDir, AUTO_BUILD_PATHS } from '../../shared/constants';
|
||||
import type { IPCResult, InsightsSession, InsightsSessionSummary, Task, TaskMetadata } from '../../shared/types';
|
||||
import type { IPCResult, InsightsSession, InsightsSessionSummary, InsightsModelConfig, Task, TaskMetadata } from '../../shared/types';
|
||||
import { projectStore } from '../project-store';
|
||||
import { insightsService } from '../insights-service';
|
||||
|
||||
@@ -32,7 +32,7 @@ export function registerInsightsHandlers(
|
||||
|
||||
ipcMain.on(
|
||||
IPC_CHANNELS.INSIGHTS_SEND_MESSAGE,
|
||||
async (_, projectId: string, message: string) => {
|
||||
async (_, projectId: string, message: string, modelConfig?: InsightsModelConfig) => {
|
||||
const project = projectStore.getProject(projectId);
|
||||
if (!project) {
|
||||
const mainWindow = getMainWindow();
|
||||
@@ -44,7 +44,7 @@ export function registerInsightsHandlers(
|
||||
|
||||
// Note: Python environment initialization should be handled by insightsService
|
||||
// or added here with proper dependency injection if needed
|
||||
insightsService.sendMessage(projectId, project.path, message);
|
||||
insightsService.sendMessage(projectId, project.path, message, modelConfig);
|
||||
}
|
||||
);
|
||||
|
||||
@@ -241,4 +241,57 @@ export function registerInsightsHandlers(
|
||||
}
|
||||
);
|
||||
|
||||
// Update model configuration for a session
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.INSIGHTS_UPDATE_MODEL_CONFIG,
|
||||
async (_, projectId: string, sessionId: string, modelConfig: InsightsModelConfig): Promise<IPCResult> => {
|
||||
const project = projectStore.getProject(projectId);
|
||||
if (!project) {
|
||||
return { success: false, error: 'Project not found' };
|
||||
}
|
||||
|
||||
const success = insightsService.updateSessionModelConfig(project.path, sessionId, modelConfig);
|
||||
if (success) {
|
||||
return { success: true };
|
||||
}
|
||||
return { success: false, error: 'Failed to update model configuration' };
|
||||
}
|
||||
);
|
||||
|
||||
// ============================================
|
||||
// Insights Event Forwarding (Service -> Renderer)
|
||||
// ============================================
|
||||
|
||||
// Forward streaming chunks to renderer
|
||||
insightsService.on('stream-chunk', (projectId: string, chunk: unknown) => {
|
||||
const mainWindow = getMainWindow();
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.INSIGHTS_STREAM_CHUNK, projectId, chunk);
|
||||
}
|
||||
});
|
||||
|
||||
// Forward status updates to renderer
|
||||
insightsService.on('status', (projectId: string, status: unknown) => {
|
||||
const mainWindow = getMainWindow();
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.INSIGHTS_STATUS, projectId, status);
|
||||
}
|
||||
});
|
||||
|
||||
// Forward errors to renderer
|
||||
insightsService.on('error', (projectId: string, error: string) => {
|
||||
const mainWindow = getMainWindow();
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.INSIGHTS_ERROR, projectId, error);
|
||||
}
|
||||
});
|
||||
|
||||
// Forward SDK rate limit events to renderer
|
||||
insightsService.on('sdk-rate-limit', (rateLimitInfo: unknown) => {
|
||||
const mainWindow = getMainWindow();
|
||||
if (mainWindow) {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.CLAUDE_SDK_RATE_LIMIT, rateLimitInfo);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { ipcMain } from 'electron';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import { IPC_CHANNELS, getSpecsDir, AUTO_BUILD_PATHS } from '../../shared/constants';
|
||||
import type { IPCResult, LinearIssue, LinearTeam, LinearProject, LinearImportResult, LinearSyncStatus, Project, Task, TaskMetadata } from '../../shared/types';
|
||||
import type { IPCResult, LinearIssue, LinearTeam, LinearProject, LinearImportResult, LinearSyncStatus, Project, TaskMetadata } from '../../shared/types';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync } from 'fs';
|
||||
import { spawn } from 'child_process';
|
||||
import { projectStore } from '../project-store';
|
||||
import { parseEnvFile } from './utils';
|
||||
|
||||
@@ -16,7 +15,7 @@ import { AgentManager } from '../agent';
|
||||
*/
|
||||
export function registerLinearHandlers(
|
||||
agentManager: AgentManager,
|
||||
getMainWindow: () => BrowserWindow | null
|
||||
_getMainWindow: () => BrowserWindow | null
|
||||
): void {
|
||||
// ============================================
|
||||
// Linear Integration Operations
|
||||
@@ -51,7 +50,7 @@ export function registerLinearHandlers(
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': apiKey
|
||||
'Authorization': `Bearer ${apiKey}`
|
||||
},
|
||||
body: JSON.stringify({ query, variables })
|
||||
});
|
||||
@@ -115,7 +114,8 @@ export function registerLinearHandlers(
|
||||
|
||||
if (data.teams.nodes.length > 0) {
|
||||
teamName = data.teams.nodes[0].name;
|
||||
const countQuery = `
|
||||
// Note: These queries are kept as documentation for future API reference
|
||||
const _countQuery = `
|
||||
query($teamId: String!) {
|
||||
team(id: $teamId) {
|
||||
issues {
|
||||
@@ -125,7 +125,7 @@ export function registerLinearHandlers(
|
||||
}
|
||||
`;
|
||||
// Get approximate count
|
||||
const issuesQuery = `
|
||||
const _issuesQuery = `
|
||||
query($teamId: String!) {
|
||||
issues(filter: { team: { id: { eq: $teamId } } }, first: 0) {
|
||||
pageInfo {
|
||||
@@ -134,6 +134,8 @@ export function registerLinearHandlers(
|
||||
}
|
||||
}
|
||||
`;
|
||||
void _countQuery;
|
||||
void _issuesQuery;
|
||||
|
||||
// Simple count estimation - get first 250 issues
|
||||
const countData = await linearGraphQL(apiKey, `
|
||||
|
||||
@@ -0,0 +1,532 @@
|
||||
/**
|
||||
* Memory Infrastructure IPC Handlers
|
||||
*
|
||||
* Provides memory database status and validation for the Graphiti integration.
|
||||
* Uses LadybugDB (embedded Kuzu-based database) - no Docker required.
|
||||
*/
|
||||
|
||||
import { ipcMain } from 'electron';
|
||||
import { spawn } from 'child_process';
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import type {
|
||||
IPCResult,
|
||||
InfrastructureStatus,
|
||||
GraphitiValidationResult,
|
||||
GraphitiConnectionTestResult,
|
||||
} from '../../shared/types';
|
||||
import {
|
||||
getMemoryServiceStatus,
|
||||
getMemoryService,
|
||||
getDefaultDbPath,
|
||||
isKuzuAvailable,
|
||||
} from '../memory-service';
|
||||
import { validateOpenAIApiKey } from '../api-validation-service';
|
||||
import { findPythonCommand, parsePythonCommand } from '../python-detector';
|
||||
|
||||
// Ollama types
|
||||
interface OllamaStatus {
|
||||
running: boolean;
|
||||
url: string;
|
||||
version?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
interface OllamaModel {
|
||||
name: string;
|
||||
size_bytes: number;
|
||||
size_gb: number;
|
||||
modified_at: string;
|
||||
is_embedding: boolean;
|
||||
embedding_dim?: number | null;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface OllamaEmbeddingModel {
|
||||
name: string;
|
||||
embedding_dim: number | null;
|
||||
description: string;
|
||||
size_bytes: number;
|
||||
size_gb: number;
|
||||
}
|
||||
|
||||
interface OllamaRecommendedModel {
|
||||
name: string;
|
||||
description: string;
|
||||
size_estimate: string;
|
||||
dim: number;
|
||||
installed: boolean;
|
||||
}
|
||||
|
||||
interface OllamaPullResult {
|
||||
model: string;
|
||||
status: 'completed' | 'failed';
|
||||
output: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the ollama_model_detector.py script
|
||||
*/
|
||||
async function executeOllamaDetector(
|
||||
command: string,
|
||||
baseUrl?: string
|
||||
): Promise<{ success: boolean; data?: unknown; error?: string }> {
|
||||
const pythonCmd = findPythonCommand();
|
||||
if (!pythonCmd) {
|
||||
return { success: false, error: 'Python not found' };
|
||||
}
|
||||
|
||||
// Find the ollama_model_detector.py script
|
||||
const possiblePaths = [
|
||||
path.resolve(__dirname, '..', '..', '..', 'auto-claude', 'ollama_model_detector.py'),
|
||||
path.resolve(process.cwd(), 'auto-claude', 'ollama_model_detector.py'),
|
||||
path.resolve(process.cwd(), '..', 'auto-claude', 'ollama_model_detector.py'),
|
||||
];
|
||||
|
||||
let scriptPath: string | null = null;
|
||||
for (const p of possiblePaths) {
|
||||
if (fs.existsSync(p)) {
|
||||
scriptPath = p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!scriptPath) {
|
||||
return { success: false, error: 'ollama_model_detector.py script not found' };
|
||||
}
|
||||
|
||||
const [pythonExe, baseArgs] = parsePythonCommand(pythonCmd);
|
||||
const args = [...baseArgs, scriptPath, command];
|
||||
if (baseUrl) {
|
||||
args.push('--base-url', baseUrl);
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let resolved = false;
|
||||
const proc = spawn(pythonExe, args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
proc.stdout.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
proc.stderr.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
// Single timeout mechanism to avoid race condition
|
||||
const timeoutId = setTimeout(() => {
|
||||
if (!resolved) {
|
||||
resolved = true;
|
||||
proc.kill();
|
||||
resolve({ success: false, error: 'Timeout' });
|
||||
}
|
||||
}, 10000);
|
||||
|
||||
proc.on('close', (code) => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
clearTimeout(timeoutId);
|
||||
if (code === 0 && stdout) {
|
||||
try {
|
||||
resolve(JSON.parse(stdout));
|
||||
} catch {
|
||||
resolve({ success: false, error: `Invalid JSON: ${stdout}` });
|
||||
}
|
||||
} else {
|
||||
resolve({ success: false, error: stderr || `Exit code ${code}` });
|
||||
}
|
||||
});
|
||||
|
||||
proc.on('error', (err) => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
clearTimeout(timeoutId);
|
||||
resolve({ success: false, error: err.message });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Register all memory-related IPC handlers
|
||||
*/
|
||||
export function registerMemoryHandlers(): void {
|
||||
// Get memory infrastructure status
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.MEMORY_STATUS,
|
||||
async (_): Promise<IPCResult<InfrastructureStatus>> => {
|
||||
try {
|
||||
const status = getMemoryServiceStatus();
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
memory: status,
|
||||
ready: status.kuzuInstalled && status.databaseExists,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to check memory status',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// List available databases
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.MEMORY_LIST_DATABASES,
|
||||
async (_, dbPath?: string): Promise<IPCResult<string[]>> => {
|
||||
try {
|
||||
const status = getMemoryServiceStatus(dbPath);
|
||||
return { success: true, data: status.databases };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to list databases',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Test memory database connection
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.MEMORY_TEST_CONNECTION,
|
||||
async (_, dbPath?: string, database?: string): Promise<IPCResult<GraphitiValidationResult>> => {
|
||||
try {
|
||||
if (!isKuzuAvailable()) {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
success: false,
|
||||
message: 'kuzu-node is not installed. Memory features require Python 3.12+ with LadybugDB.',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const service = getMemoryService({
|
||||
dbPath: dbPath || getDefaultDbPath(),
|
||||
database: database || 'auto_claude_memory',
|
||||
});
|
||||
|
||||
const result = await service.testConnection();
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to test connection',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// ============================================
|
||||
// Graphiti Validation Handlers
|
||||
// ============================================
|
||||
|
||||
// Validate LLM provider API key (OpenAI, Anthropic, etc.)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GRAPHITI_VALIDATE_LLM,
|
||||
async (_, provider: string, apiKey: string): Promise<IPCResult<GraphitiValidationResult>> => {
|
||||
try {
|
||||
// For now, we only validate OpenAI - other providers can be added later
|
||||
if (provider === 'openai') {
|
||||
const result = await validateOpenAIApiKey(apiKey);
|
||||
return { success: true, data: result };
|
||||
}
|
||||
|
||||
// For other providers, do basic validation
|
||||
if (!apiKey || !apiKey.trim()) {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
success: false,
|
||||
message: 'API key is required',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
success: true,
|
||||
message: `${provider} API key format appears valid`,
|
||||
details: { provider },
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to validate API key',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Test full Graphiti connection (Database + LLM provider)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GRAPHITI_TEST_CONNECTION,
|
||||
async (
|
||||
_,
|
||||
config: {
|
||||
dbPath?: string;
|
||||
database?: string;
|
||||
llmProvider: string;
|
||||
apiKey: string;
|
||||
}
|
||||
): Promise<IPCResult<GraphitiConnectionTestResult>> => {
|
||||
try {
|
||||
// Test database connection
|
||||
let databaseResult: GraphitiValidationResult;
|
||||
|
||||
if (!isKuzuAvailable()) {
|
||||
databaseResult = {
|
||||
success: false,
|
||||
message: 'kuzu-node is not installed. Memory features require Python 3.12+ with LadybugDB.',
|
||||
};
|
||||
} else {
|
||||
const service = getMemoryService({
|
||||
dbPath: config.dbPath || getDefaultDbPath(),
|
||||
database: config.database || 'auto_claude_memory',
|
||||
});
|
||||
databaseResult = await service.testConnection();
|
||||
}
|
||||
|
||||
// Test LLM provider
|
||||
let llmResult: GraphitiValidationResult;
|
||||
|
||||
if (config.llmProvider === 'openai') {
|
||||
llmResult = await validateOpenAIApiKey(config.apiKey);
|
||||
} else if (config.llmProvider === 'ollama') {
|
||||
// Ollama doesn't need API key validation
|
||||
llmResult = {
|
||||
success: true,
|
||||
message: 'Ollama (local) does not require API key validation',
|
||||
details: { provider: 'ollama' },
|
||||
};
|
||||
} else {
|
||||
// Basic validation for other providers
|
||||
llmResult = config.apiKey && config.apiKey.trim()
|
||||
? {
|
||||
success: true,
|
||||
message: `${config.llmProvider} API key format appears valid`,
|
||||
details: { provider: config.llmProvider },
|
||||
}
|
||||
: {
|
||||
success: false,
|
||||
message: 'API key is required',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
database: databaseResult,
|
||||
llmProvider: llmResult,
|
||||
ready: databaseResult.success && llmResult.success,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to test Graphiti connection',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// ============================================
|
||||
// Ollama Model Detection Handlers
|
||||
// ============================================
|
||||
|
||||
// Check if Ollama is running
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.OLLAMA_CHECK_STATUS,
|
||||
async (_, baseUrl?: string): Promise<IPCResult<OllamaStatus>> => {
|
||||
try {
|
||||
const result = await executeOllamaDetector('check-status', baseUrl);
|
||||
|
||||
if (!result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.error || 'Failed to check Ollama status',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: result.data as OllamaStatus,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to check Ollama status',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// List all Ollama models
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.OLLAMA_LIST_MODELS,
|
||||
async (_, baseUrl?: string): Promise<IPCResult<{ models: OllamaModel[]; count: number }>> => {
|
||||
try {
|
||||
const result = await executeOllamaDetector('list-models', baseUrl);
|
||||
|
||||
if (!result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.error || 'Failed to list Ollama models',
|
||||
};
|
||||
}
|
||||
|
||||
const data = result.data as { models: OllamaModel[]; count: number; url: string };
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
models: data.models,
|
||||
count: data.count,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to list Ollama models',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// List only embedding models from Ollama
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.OLLAMA_LIST_EMBEDDING_MODELS,
|
||||
async (
|
||||
_,
|
||||
baseUrl?: string
|
||||
): Promise<IPCResult<{ embedding_models: OllamaEmbeddingModel[]; count: number }>> => {
|
||||
try {
|
||||
const result = await executeOllamaDetector('list-embedding-models', baseUrl);
|
||||
|
||||
if (!result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.error || 'Failed to list Ollama embedding models',
|
||||
};
|
||||
}
|
||||
|
||||
const data = result.data as {
|
||||
embedding_models: OllamaEmbeddingModel[];
|
||||
count: number;
|
||||
url: string;
|
||||
};
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
embedding_models: data.embedding_models,
|
||||
count: data.count,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to list embedding models',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Pull (download) an Ollama model
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.OLLAMA_PULL_MODEL,
|
||||
async (
|
||||
_,
|
||||
modelName: string,
|
||||
baseUrl?: string
|
||||
): Promise<IPCResult<OllamaPullResult>> => {
|
||||
try {
|
||||
const pythonCmd = findPythonCommand();
|
||||
if (!pythonCmd) {
|
||||
return { success: false, error: 'Python not found' };
|
||||
}
|
||||
|
||||
// Find the ollama_model_detector.py script
|
||||
const possiblePaths = [
|
||||
path.resolve(__dirname, '..', '..', '..', 'auto-claude', 'ollama_model_detector.py'),
|
||||
path.resolve(process.cwd(), 'auto-claude', 'ollama_model_detector.py'),
|
||||
path.resolve(process.cwd(), '..', 'auto-claude', 'ollama_model_detector.py'),
|
||||
];
|
||||
|
||||
let scriptPath: string | null = null;
|
||||
for (const p of possiblePaths) {
|
||||
if (fs.existsSync(p)) {
|
||||
scriptPath = p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!scriptPath) {
|
||||
return { success: false, error: 'ollama_model_detector.py script not found' };
|
||||
}
|
||||
|
||||
const [pythonExe, baseArgs] = parsePythonCommand(pythonCmd);
|
||||
const args = [...baseArgs, scriptPath, 'pull-model', modelName];
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const proc = spawn(pythonExe, args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
timeout: 600000, // 10 minute timeout for large models
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
proc.stdout.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
proc.stderr.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
// Could emit progress events here in the future
|
||||
});
|
||||
|
||||
proc.on('close', (code) => {
|
||||
if (code === 0 && stdout) {
|
||||
try {
|
||||
const result = JSON.parse(stdout);
|
||||
if (result.success) {
|
||||
resolve({
|
||||
success: true,
|
||||
data: result.data as OllamaPullResult,
|
||||
});
|
||||
} else {
|
||||
resolve({
|
||||
success: false,
|
||||
error: result.error || 'Failed to pull model',
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
resolve({ success: false, error: `Invalid JSON: ${stdout}` });
|
||||
}
|
||||
} else {
|
||||
resolve({ success: false, error: stderr || `Exit code ${code}` });
|
||||
}
|
||||
});
|
||||
|
||||
proc.on('error', (err) => {
|
||||
resolve({ success: false, error: err.message });
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to pull model',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -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';
|
||||
@@ -22,6 +26,7 @@ import { changelogService } from '../changelog-service';
|
||||
import { insightsService } from '../insights-service';
|
||||
import { titleGenerator } from '../title-generator';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import { getEffectiveSourcePath } from '../updater/path-resolver';
|
||||
|
||||
// ============================================
|
||||
// Git Helper Functions
|
||||
@@ -98,54 +103,6 @@ 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
|
||||
*/
|
||||
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')
|
||||
];
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
if (existsSync(p) && existsSync(path.join(p, 'VERSION'))) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the configured auto-claude source path from settings, or auto-detect
|
||||
*/
|
||||
const getAutoBuildSourcePath = (): string | null => {
|
||||
// First check if manually configured
|
||||
if (existsSync(settingsPath)) {
|
||||
try {
|
||||
const content = readFileSync(settingsPath, 'utf-8');
|
||||
const settings = JSON.parse(content);
|
||||
if (settings.autoBuildPath && existsSync(settings.autoBuildPath)) {
|
||||
return settings.autoBuildPath;
|
||||
}
|
||||
} catch {
|
||||
// Fall through to auto-detect
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-detect from app location
|
||||
return detectAutoBuildSourcePath();
|
||||
};
|
||||
|
||||
/**
|
||||
* Configure all Python-dependent services with the managed Python path
|
||||
*/
|
||||
@@ -154,7 +111,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);
|
||||
@@ -168,9 +125,9 @@ const initializePythonEnvironment = async (
|
||||
pythonEnvManager: PythonEnvManager,
|
||||
agentManager: AgentManager
|
||||
): Promise<PythonEnvStatus> => {
|
||||
const autoBuildSource = getAutoBuildSourcePath();
|
||||
const autoBuildSource = getEffectiveSourcePath();
|
||||
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 +137,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 +194,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 };
|
||||
}
|
||||
);
|
||||
@@ -261,6 +218,31 @@ export function registerProjectHandlers(
|
||||
}
|
||||
);
|
||||
|
||||
// ============================================
|
||||
// Tab State Operations (persisted in main process)
|
||||
// ============================================
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.TAB_STATE_GET,
|
||||
async (): Promise<IPCResult<{ openProjectIds: string[]; activeProjectId: string | null; tabOrder: string[] }>> => {
|
||||
const tabState = projectStore.getTabState();
|
||||
console.log('[IPC] TAB_STATE_GET returning:', tabState);
|
||||
return { success: true, data: tabState };
|
||||
}
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.TAB_STATE_SAVE,
|
||||
async (
|
||||
_,
|
||||
tabState: { openProjectIds: string[]; activeProjectId: string | null; tabOrder: string[] }
|
||||
): Promise<IPCResult> => {
|
||||
console.log('[IPC] TAB_STATE_SAVE called with:', tabState);
|
||||
projectStore.saveTabState(tabState);
|
||||
return { success: true };
|
||||
}
|
||||
);
|
||||
|
||||
// ============================================
|
||||
// Project Initialization Operations
|
||||
// ============================================
|
||||
@@ -289,7 +271,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 +447,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'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,44 @@
|
||||
import { ipcMain } from 'electron';
|
||||
import { ipcMain, app } from 'electron';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import { IPC_CHANNELS, AUTO_BUILD_PATHS, getSpecsDir } from '../../shared/constants';
|
||||
import type { IPCResult, Roadmap, RoadmapFeature, RoadmapFeatureStatus, RoadmapGenerationStatus, Task, TaskMetadata, CompetitorAnalysis } from '../../shared/types';
|
||||
import { IPC_CHANNELS, AUTO_BUILD_PATHS, getSpecsDir, DEFAULT_APP_SETTINGS, DEFAULT_FEATURE_MODELS, DEFAULT_FEATURE_THINKING } from '../../shared/constants';
|
||||
import type { IPCResult, Roadmap, RoadmapFeature, RoadmapFeatureStatus, RoadmapGenerationStatus, Task, TaskMetadata, CompetitorAnalysis, AppSettings } from '../../shared/types';
|
||||
import type { RoadmapConfig } from '../agent/types';
|
||||
import path from 'path';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'fs';
|
||||
import { projectStore } from '../project-store';
|
||||
import { fileWatcher } from '../file-watcher';
|
||||
import { AgentManager } from '../agent';
|
||||
import { debugLog, debugError } from '../../shared/utils/debug-logger';
|
||||
|
||||
/**
|
||||
* Read feature settings from the settings file
|
||||
*/
|
||||
function getFeatureSettings(): { model?: string; thinkingLevel?: string } {
|
||||
const settingsPath = path.join(app.getPath('userData'), 'settings.json');
|
||||
|
||||
try {
|
||||
if (existsSync(settingsPath)) {
|
||||
const content = readFileSync(settingsPath, 'utf-8');
|
||||
const settings: AppSettings = { ...DEFAULT_APP_SETTINGS, ...JSON.parse(content) };
|
||||
|
||||
// Get roadmap-specific settings
|
||||
const featureModels = settings.featureModels || DEFAULT_FEATURE_MODELS;
|
||||
const featureThinking = settings.featureThinking || DEFAULT_FEATURE_THINKING;
|
||||
|
||||
return {
|
||||
model: featureModels.roadmap,
|
||||
thinkingLevel: featureThinking.roadmap
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
debugError('[Roadmap Handler] Failed to read feature settings:', error);
|
||||
}
|
||||
|
||||
// Return defaults if settings file doesn't exist or fails to parse
|
||||
return {
|
||||
model: DEFAULT_FEATURE_MODELS.roadmap,
|
||||
thinkingLevel: DEFAULT_FEATURE_THINKING.roadmap
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
@@ -138,7 +170,7 @@ export function registerRoadmapHandlers(
|
||||
impact: feature.impact || 'medium',
|
||||
phaseId: feature.phase_id,
|
||||
dependencies: feature.dependencies || [],
|
||||
status: feature.status || 'idea',
|
||||
status: feature.status || 'under_review',
|
||||
acceptanceCriteria: feature.acceptance_criteria || [],
|
||||
userStories: feature.user_stories || [],
|
||||
linkedSpecId: feature.linked_spec_id,
|
||||
@@ -160,14 +192,39 @@ export function registerRoadmapHandlers(
|
||||
}
|
||||
);
|
||||
|
||||
// Get roadmap generation status - allows frontend to query if generation is running
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.ROADMAP_GET_STATUS,
|
||||
async (_, projectId: string): Promise<IPCResult<{ isRunning: boolean }>> => {
|
||||
const isRunning = agentManager.isRoadmapRunning(projectId);
|
||||
debugLog('[Roadmap Handler] Get status:', { projectId, isRunning });
|
||||
return { success: true, data: { isRunning } };
|
||||
}
|
||||
);
|
||||
|
||||
ipcMain.on(
|
||||
IPC_CHANNELS.ROADMAP_GENERATE,
|
||||
(_, projectId: string, enableCompetitorAnalysis?: boolean) => {
|
||||
(_, projectId: string, enableCompetitorAnalysis?: boolean, refreshCompetitorAnalysis?: boolean) => {
|
||||
// Get feature settings for roadmap
|
||||
const featureSettings = getFeatureSettings();
|
||||
const config: RoadmapConfig = {
|
||||
model: featureSettings.model,
|
||||
thinkingLevel: featureSettings.thinkingLevel
|
||||
};
|
||||
|
||||
debugLog('[Roadmap Handler] Generate request:', {
|
||||
projectId,
|
||||
enableCompetitorAnalysis,
|
||||
refreshCompetitorAnalysis,
|
||||
config
|
||||
});
|
||||
|
||||
const mainWindow = getMainWindow();
|
||||
if (!mainWindow) return;
|
||||
|
||||
const project = projectStore.getProject(projectId);
|
||||
if (!project) {
|
||||
debugError('[Roadmap Handler] Project not found:', projectId);
|
||||
mainWindow.webContents.send(
|
||||
IPC_CHANNELS.ROADMAP_ERROR,
|
||||
projectId,
|
||||
@@ -176,8 +233,21 @@ export function registerRoadmapHandlers(
|
||||
return;
|
||||
}
|
||||
|
||||
debugLog('[Roadmap Handler] Starting agent manager generation:', {
|
||||
projectId,
|
||||
projectPath: project.path,
|
||||
config
|
||||
});
|
||||
|
||||
// Start roadmap generation via agent manager
|
||||
agentManager.startRoadmapGeneration(projectId, project.path, false, enableCompetitorAnalysis ?? false);
|
||||
agentManager.startRoadmapGeneration(
|
||||
projectId,
|
||||
project.path,
|
||||
false, // refresh (not a refresh operation)
|
||||
enableCompetitorAnalysis ?? false,
|
||||
refreshCompetitorAnalysis ?? false,
|
||||
config
|
||||
);
|
||||
|
||||
// Send initial progress
|
||||
mainWindow.webContents.send(
|
||||
@@ -194,7 +264,21 @@ export function registerRoadmapHandlers(
|
||||
|
||||
ipcMain.on(
|
||||
IPC_CHANNELS.ROADMAP_REFRESH,
|
||||
(_, projectId: string, enableCompetitorAnalysis?: boolean) => {
|
||||
(_, projectId: string, enableCompetitorAnalysis?: boolean, refreshCompetitorAnalysis?: boolean) => {
|
||||
// Get feature settings for roadmap
|
||||
const featureSettings = getFeatureSettings();
|
||||
const config: RoadmapConfig = {
|
||||
model: featureSettings.model,
|
||||
thinkingLevel: featureSettings.thinkingLevel
|
||||
};
|
||||
|
||||
debugLog('[Roadmap Handler] Refresh request:', {
|
||||
projectId,
|
||||
enableCompetitorAnalysis,
|
||||
refreshCompetitorAnalysis,
|
||||
config
|
||||
});
|
||||
|
||||
const mainWindow = getMainWindow();
|
||||
if (!mainWindow) return;
|
||||
|
||||
@@ -209,7 +293,14 @@ export function registerRoadmapHandlers(
|
||||
}
|
||||
|
||||
// Start roadmap regeneration with refresh flag
|
||||
agentManager.startRoadmapGeneration(projectId, project.path, true, enableCompetitorAnalysis ?? false);
|
||||
agentManager.startRoadmapGeneration(
|
||||
projectId,
|
||||
project.path,
|
||||
true, // refresh (this is a refresh operation)
|
||||
enableCompetitorAnalysis ?? false,
|
||||
refreshCompetitorAnalysis ?? false,
|
||||
config
|
||||
);
|
||||
|
||||
// Send initial progress
|
||||
mainWindow.webContents.send(
|
||||
@@ -224,6 +315,27 @@ export function registerRoadmapHandlers(
|
||||
}
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.ROADMAP_STOP,
|
||||
async (_, projectId: string): Promise<IPCResult> => {
|
||||
debugLog('[Roadmap Handler] Stop generation request:', { projectId });
|
||||
|
||||
const mainWindow = getMainWindow();
|
||||
|
||||
// Stop roadmap generation for this project
|
||||
const wasStopped = agentManager.stopRoadmap(projectId);
|
||||
|
||||
debugLog('[Roadmap Handler] Stop result:', { projectId, wasStopped });
|
||||
|
||||
if (wasStopped && mainWindow) {
|
||||
debugLog('[Roadmap Handler] Sending stopped event to renderer');
|
||||
mainWindow.webContents.send(IPC_CHANNELS.ROADMAP_STOPPED, projectId);
|
||||
}
|
||||
|
||||
return { success: wasStopped };
|
||||
}
|
||||
);
|
||||
|
||||
// ============================================
|
||||
// Roadmap Save (full state persistence for drag-and-drop)
|
||||
// ============================================
|
||||
@@ -233,7 +345,7 @@ export function registerRoadmapHandlers(
|
||||
async (
|
||||
_,
|
||||
projectId: string,
|
||||
features: RoadmapFeature[]
|
||||
roadmapData: Roadmap
|
||||
): Promise<IPCResult> => {
|
||||
const project = projectStore.getProject(projectId);
|
||||
if (!project) {
|
||||
@@ -252,10 +364,10 @@ export function registerRoadmapHandlers(
|
||||
|
||||
try {
|
||||
const content = readFileSync(roadmapPath, 'utf-8');
|
||||
const roadmap = JSON.parse(content);
|
||||
const existingRoadmap = JSON.parse(content);
|
||||
|
||||
// Transform camelCase features back to snake_case for JSON file
|
||||
roadmap.features = features.map((feature) => ({
|
||||
existingRoadmap.features = roadmapData.features.map((feature) => ({
|
||||
id: feature.id,
|
||||
title: feature.title,
|
||||
description: feature.description,
|
||||
@@ -273,10 +385,10 @@ export function registerRoadmapHandlers(
|
||||
}));
|
||||
|
||||
// Update metadata timestamp
|
||||
roadmap.metadata = roadmap.metadata || {};
|
||||
roadmap.metadata.updated_at = new Date().toISOString();
|
||||
existingRoadmap.metadata = existingRoadmap.metadata || {};
|
||||
existingRoadmap.metadata.updated_at = new Date().toISOString();
|
||||
|
||||
writeFileSync(roadmapPath, JSON.stringify(roadmap, null, 2));
|
||||
writeFileSync(roadmapPath, JSON.stringify(existingRoadmap, null, 2));
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
|
||||
@@ -874,4 +874,3 @@ ${(feature.acceptance_criteria || []).map((c: string) => `- [ ] ${c}`).join('\n'
|
||||
return { success: true, data: memories };
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -1172,4 +1172,3 @@ ${idea.rationale}
|
||||
return { success: false, error: 'Failed to rename session' };
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user