Compare commits
46 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 |
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
|
||||
@@ -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 }}
|
||||
+1
-1
@@ -86,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
|
||||
|
||||
+320
-2
@@ -1,3 +1,321 @@
|
||||
## 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
|
||||
@@ -303,7 +621,7 @@
|
||||
|
||||
- Restructured SortableFeatureCard badge layout for improved visual presentation
|
||||
|
||||
Bug Fixes:
|
||||
Bug Fixes:
|
||||
- Fixed spec runner path configuration for more reliable task execution
|
||||
|
||||
---
|
||||
@@ -606,4 +924,4 @@ Bug Fixes:
|
||||
- **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
|
||||
|
||||
@@ -189,12 +189,18 @@ 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):
|
||||
- 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`.
|
||||
|
||||
## Project Structure
|
||||
|
||||
+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
|
||||
@@ -24,114 +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.10+** - [Download Python](https://www.python.org/downloads/)
|
||||
3. **Docker Desktop** - Required for the Memory Layer
|
||||
4. **Claude Code CLI** - `npm install -g @anthropic-ai/claude-code`
|
||||
5. **Claude Subscription** - Requires [Claude Pro or Max](https://claude.ai/upgrade) for Claude Code access
|
||||
6. **Git Repository** - Your project must be initialized as a git repository
|
||||
Before using Auto Claude, you need:
|
||||
|
||||
### Git Initialization
|
||||
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`
|
||||
|
||||
**Auto Claude requires a git repository** to create isolated worktrees for safe parallel development. If your project isn't a git repo yet:
|
||||
### Install and Run
|
||||
|
||||
```bash
|
||||
cd your-project
|
||||
git init
|
||||
git add .
|
||||
git commit -m "Initial commit"
|
||||
```
|
||||
|
||||
> **Why git?** Auto Claude uses git branches and worktrees to isolate each task in its own workspace, keeping your main branch clean until you're ready to merge. This allows you to work on multiple features simultaneously without conflicts.
|
||||
|
||||
---
|
||||
|
||||
### Installing Docker Desktop
|
||||
|
||||
Docker runs the FalkorDB database that powers Auto Claude's cross-session memory.
|
||||
|
||||
| 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/) |
|
||||
|
||||
> **Not sure which Mac?** Click the Apple menu (🍎) → "About This Mac". Look for "Chip" - M1/M2/M3/M4 = Apple Silicon, otherwise Intel.
|
||||
|
||||
**After installing:** Open Docker Desktop and wait for the whale icon (🐳) to appear in your menu bar/system tray.
|
||||
|
||||
> **Using the Desktop UI?** It automatically detects Docker status and offers one-click FalkorDB setup. No terminal commands needed!
|
||||
|
||||
📚 **For detailed installation steps, troubleshooting, and advanced configuration, see [guides/DOCKER-SETUP.md](guides/DOCKER-SETUP.md)**
|
||||
|
||||
---
|
||||
|
||||
### 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
|
||||
```
|
||||
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!
|
||||
|
||||
<details>
|
||||
<summary><b>Windows users:</b> If installation fails with node-gyp errors, click here</summary>
|
||||
<summary><b>Windows users:</b> Security warning when installing</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:
|
||||
The Windows installer is not yet code-signed, so you may see a "Windows protected your PC" warning from Microsoft Defender SmartScreen.
|
||||
|
||||
1. Download [Visual Studio Build Tools 2022](https://visualstudio.microsoft.com/visual-cpp-build-tools/)
|
||||
2. Select "Desktop development with C++" workload
|
||||
3. In "Individual Components", add "MSVC v143 - VS 2022 C++ x64/x86 Spectre-mitigated libs"
|
||||
4. Restart terminal and run `npm install` again
|
||||
**To proceed:**
|
||||
1. Click "More info"
|
||||
2. Click "Run anyway"
|
||||
|
||||
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).
|
||||
|
||||
We're working on obtaining a code signing certificate for future releases.
|
||||
|
||||
</details>
|
||||
|
||||
### 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.
|
||||
|
||||
---
|
||||
|
||||
@@ -241,23 +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, Google AI, or Ollama (local/offline)
|
||||
|
||||
| Setup | LLM | Embeddings | Notes |
|
||||
|-------|-----|------------|-------|
|
||||
| **OpenAI** | OpenAI | OpenAI | Simplest - single API key |
|
||||
| **Anthropic + Voyage** | Anthropic | Voyage AI | High quality |
|
||||
| **Google AI** | Gemini | Google | Single API key, fast inference |
|
||||
| **Ollama** | Ollama | Ollama | Fully offline |
|
||||
| **Azure** | Azure OpenAI | Azure OpenAI | Enterprise |
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
@@ -273,9 +199,8 @@ 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
|
||||
@@ -309,13 +234,6 @@ The `.auto-claude/` directory is gitignored and project-specific - you'll have o
|
||||
|----------|----------|-------------|
|
||||
| `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, google |
|
||||
| `GRAPHITI_EMBEDDER_PROVIDER` | For Memory | Embedder: openai, voyage, azure_openai, ollama, google |
|
||||
| `OPENAI_API_KEY` | For OpenAI | Required for OpenAI provider |
|
||||
| `ANTHROPIC_API_KEY` | For Anthropic | Required for Anthropic LLM |
|
||||
| `VOYAGE_API_KEY` | For Voyage | Required for Voyage embeddings |
|
||||
| `GOOGLE_API_KEY` | For Google | Required for Google AI (Gemini) provider |
|
||||
|
||||
See `auto-claude/.env.example` for complete configuration options.
|
||||
|
||||
|
||||
+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/>.
|
||||
|
||||
@@ -5,23 +5,20 @@
|
||||
# DEBUG SETTINGS
|
||||
# ============================================
|
||||
|
||||
# Enable general debug logging for ideation and roadmap features
|
||||
# Enable debug logging across the entire application
|
||||
# When enabled, you'll see detailed console logs for:
|
||||
# - Ideation generation and stop functionality
|
||||
# - Roadmap generation and stop functionality
|
||||
# - 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
|
||||
# Enable debug logging for the auto-updater only
|
||||
# Shows detailed information about app update checks and downloads
|
||||
# DEBUG_UPDATER=true
|
||||
|
||||
# Enable debug logging for Auto Claude features
|
||||
# Affects changelog generation, project initialization, and other core features
|
||||
# AUTO_CLAUDE_DEBUG=true
|
||||
|
||||
# ============================================
|
||||
# HOW TO USE
|
||||
# ============================================
|
||||
@@ -31,7 +28,6 @@
|
||||
#
|
||||
# Option 2: Export in your shell profile (~/.bashrc, ~/.zshrc, etc.)
|
||||
# export DEBUG=true
|
||||
# export AUTO_CLAUDE_DEBUG=true
|
||||
#
|
||||
# Option 3: Create a .env file in this directory (auto-claude-ui/)
|
||||
# Copy this file: cp .env.example .env
|
||||
|
||||
+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 @@ export default defineConfig({
|
||||
exclude: [
|
||||
'uuid',
|
||||
'chokidar',
|
||||
'ioredis',
|
||||
'kuzu',
|
||||
'electron-updater',
|
||||
'@electron-toolkit/utils'
|
||||
]
|
||||
|
||||
Generated
+345
-168
File diff suppressed because it is too large
Load Diff
@@ -1,22 +1,32 @@
|
||||
{
|
||||
"name": "auto-claude-ui",
|
||||
"version": "2.6.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": "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",
|
||||
@@ -57,7 +67,6 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"electron-updater": "^6.6.2",
|
||||
"ioredis": "^5.8.2",
|
||||
"lucide-react": "^0.560.0",
|
||||
"motion": "^12.23.26",
|
||||
"react": "^19.2.3",
|
||||
@@ -77,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",
|
||||
@@ -108,6 +116,7 @@
|
||||
"node-pty": "npm:@lydell/node-pty@^1.1.0"
|
||||
},
|
||||
"onlyBuiltDependencies": [
|
||||
"@lydell/node-pty",
|
||||
"electron",
|
||||
"electron-winstaller",
|
||||
"esbuild"
|
||||
@@ -115,7 +124,8 @@
|
||||
},
|
||||
"build": {
|
||||
"appId": "com.autoclaude.ui",
|
||||
"productName": "Auto Claude",
|
||||
"productName": "Auto-Claude",
|
||||
"artifactName": "${productName}-${version}-${platform}-${arch}.${ext}",
|
||||
"publish": [
|
||||
{
|
||||
"provider": "github",
|
||||
@@ -149,13 +159,23 @@
|
||||
"!**/*.pyc",
|
||||
"!**/specs",
|
||||
"!**/.venv",
|
||||
"!**/.env"
|
||||
"!**/.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"
|
||||
|
||||
Generated
-77
@@ -103,9 +103,6 @@ importers:
|
||||
electron-updater:
|
||||
specifier: ^6.6.2
|
||||
version: 6.6.2
|
||||
ioredis:
|
||||
specifier: ^5.8.2
|
||||
version: 5.8.2
|
||||
lucide-react:
|
||||
specifier: ^0.560.0
|
||||
version: 0.560.0(react@19.2.3)
|
||||
@@ -158,9 +155,6 @@ importers:
|
||||
'@testing-library/react':
|
||||
specifier: ^16.1.0
|
||||
version: 16.3.1(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3(@types/react@19.2.7))(@types/react@19.2.7)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
'@types/ioredis':
|
||||
specifier: ^4.28.10
|
||||
version: 4.28.10
|
||||
'@types/node':
|
||||
specifier: ^25.0.0
|
||||
version: 25.0.3
|
||||
@@ -833,9 +827,6 @@ packages:
|
||||
resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==}
|
||||
engines: {node: '>=18.18'}
|
||||
|
||||
'@ioredis/commands@1.4.0':
|
||||
resolution: {integrity: sha512-aFT2yemJJo+TZCmieA7qnYGQooOS7QfNmYrzGtsYd3g9j5iDP8AimYYAesf79ohjbLG12XxC4nG5DyEnC88AsQ==}
|
||||
|
||||
'@isaacs/balanced-match@4.0.1':
|
||||
resolution: {integrity: sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==}
|
||||
engines: {node: 20 || >=22}
|
||||
@@ -1705,9 +1696,6 @@ packages:
|
||||
'@types/http-cache-semantics@4.0.4':
|
||||
resolution: {integrity: sha512-1m0bIFVc7eJWyve9S0RnuRgcQqF/Xd5QsUZAZeQFr1Q3/p9JWoQQEqmVy+DPTNpGXwhgIetAoYF8JSc33q29QA==}
|
||||
|
||||
'@types/ioredis@4.28.10':
|
||||
resolution: {integrity: sha512-69LyhUgrXdgcNDv7ogs1qXZomnfOEnSmrmMFqKgt1XMJxmoOSG/u3wYy13yACIfKuMJ8IhKgHafDO3sx19zVQQ==}
|
||||
|
||||
'@types/json-schema@7.0.15':
|
||||
resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
|
||||
|
||||
@@ -2195,10 +2183,6 @@ packages:
|
||||
resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
cluster-key-slot@1.1.2:
|
||||
resolution: {integrity: sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
color-convert@2.0.1:
|
||||
resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}
|
||||
engines: {node: '>=7.0.0'}
|
||||
@@ -2323,10 +2307,6 @@ packages:
|
||||
resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}
|
||||
engines: {node: '>=0.4.0'}
|
||||
|
||||
denque@2.1.0:
|
||||
resolution: {integrity: sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==}
|
||||
engines: {node: '>=0.10'}
|
||||
|
||||
dequal@2.0.3:
|
||||
resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}
|
||||
engines: {node: '>=6'}
|
||||
@@ -2925,10 +2905,6 @@ packages:
|
||||
resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
ioredis@5.8.2:
|
||||
resolution: {integrity: sha512-C6uC+kleiIMmjViJINWk80sOQw5lEzse1ZmvD+S/s8p8CWapftSaC+kocGTx6xrbrJ4WmYQGC08ffHLr6ToR6Q==}
|
||||
engines: {node: '>=12.22.0'}
|
||||
|
||||
ip-address@10.1.0:
|
||||
resolution: {integrity: sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==}
|
||||
engines: {node: '>= 12'}
|
||||
@@ -3246,15 +3222,9 @@ packages:
|
||||
resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
lodash.defaults@4.2.0:
|
||||
resolution: {integrity: sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==}
|
||||
|
||||
lodash.escaperegexp@4.1.2:
|
||||
resolution: {integrity: sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==}
|
||||
|
||||
lodash.isarguments@3.1.0:
|
||||
resolution: {integrity: sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==}
|
||||
|
||||
lodash.isequal@4.5.0:
|
||||
resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==}
|
||||
deprecated: This package is deprecated. Use require('node:util').isDeepStrictEqual instead.
|
||||
@@ -3894,14 +3864,6 @@ packages:
|
||||
resolution: {integrity: sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==}
|
||||
engines: {node: '>= 20.19.0'}
|
||||
|
||||
redis-errors@1.2.0:
|
||||
resolution: {integrity: sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==}
|
||||
engines: {node: '>=4'}
|
||||
|
||||
redis-parser@3.0.0:
|
||||
resolution: {integrity: sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==}
|
||||
engines: {node: '>=4'}
|
||||
|
||||
reflect.getprototypeof@1.0.10:
|
||||
resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -4126,9 +4088,6 @@ packages:
|
||||
stackback@0.0.2:
|
||||
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
|
||||
|
||||
standard-as-callback@2.1.0:
|
||||
resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==}
|
||||
|
||||
stat-mode@1.0.0:
|
||||
resolution: {integrity: sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg==}
|
||||
engines: {node: '>= 6'}
|
||||
@@ -5211,8 +5170,6 @@ snapshots:
|
||||
|
||||
'@humanwhocodes/retry@0.4.3': {}
|
||||
|
||||
'@ioredis/commands@1.4.0': {}
|
||||
|
||||
'@isaacs/balanced-match@4.0.1': {}
|
||||
|
||||
'@isaacs/brace-expansion@5.0.0':
|
||||
@@ -6043,10 +6000,6 @@ snapshots:
|
||||
|
||||
'@types/http-cache-semantics@4.0.4': {}
|
||||
|
||||
'@types/ioredis@4.28.10':
|
||||
dependencies:
|
||||
'@types/node': 25.0.3
|
||||
|
||||
'@types/json-schema@7.0.15': {}
|
||||
|
||||
'@types/keyv@3.1.4':
|
||||
@@ -6658,8 +6611,6 @@ snapshots:
|
||||
|
||||
clsx@2.1.1: {}
|
||||
|
||||
cluster-key-slot@1.1.2: {}
|
||||
|
||||
color-convert@2.0.1:
|
||||
dependencies:
|
||||
color-name: 1.1.4
|
||||
@@ -6777,8 +6728,6 @@ snapshots:
|
||||
|
||||
delayed-stream@1.0.0: {}
|
||||
|
||||
denque@2.1.0: {}
|
||||
|
||||
dequal@2.0.3: {}
|
||||
|
||||
detect-libc@2.1.2: {}
|
||||
@@ -7634,20 +7583,6 @@ snapshots:
|
||||
hasown: 2.0.2
|
||||
side-channel: 1.1.0
|
||||
|
||||
ioredis@5.8.2:
|
||||
dependencies:
|
||||
'@ioredis/commands': 1.4.0
|
||||
cluster-key-slot: 1.1.2
|
||||
debug: 4.4.3
|
||||
denque: 2.1.0
|
||||
lodash.defaults: 4.2.0
|
||||
lodash.isarguments: 3.1.0
|
||||
redis-errors: 1.2.0
|
||||
redis-parser: 3.0.0
|
||||
standard-as-callback: 2.1.0
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
ip-address@10.1.0: {}
|
||||
|
||||
is-alphabetical@2.0.1: {}
|
||||
@@ -7966,12 +7901,8 @@ snapshots:
|
||||
dependencies:
|
||||
p-locate: 5.0.0
|
||||
|
||||
lodash.defaults@4.2.0: {}
|
||||
|
||||
lodash.escaperegexp@4.1.2: {}
|
||||
|
||||
lodash.isarguments@3.1.0: {}
|
||||
|
||||
lodash.isequal@4.5.0: {}
|
||||
|
||||
lodash.merge@4.6.2: {}
|
||||
@@ -8808,12 +8739,6 @@ snapshots:
|
||||
|
||||
readdirp@5.0.0: {}
|
||||
|
||||
redis-errors@1.2.0: {}
|
||||
|
||||
redis-parser@3.0.0:
|
||||
dependencies:
|
||||
redis-errors: 1.2.0
|
||||
|
||||
reflect.getprototypeof@1.0.10:
|
||||
dependencies:
|
||||
call-bind: 1.0.8
|
||||
@@ -9112,8 +9037,6 @@ snapshots:
|
||||
|
||||
stackback@0.0.2: {}
|
||||
|
||||
standard-as-callback@2.1.0: {}
|
||||
|
||||
stat-mode@1.0.0: {}
|
||||
|
||||
std-env@3.10.0: {}
|
||||
|
||||
@@ -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>
|
||||
@@ -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();
|
||||
@@ -99,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'
|
||||
@@ -123,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
|
||||
})
|
||||
@@ -140,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',
|
||||
@@ -167,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,11 +5,37 @@ 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);
|
||||
@@ -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 })
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,14 @@ vi.mock('@electron-toolkit/utils', () => ({
|
||||
}
|
||||
}));
|
||||
|
||||
// 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 {
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -9,8 +9,9 @@ import { getClaudeProfileManager } from '../claude-profile-manager';
|
||||
import {
|
||||
SpecCreationMetadata,
|
||||
TaskExecutionOptions,
|
||||
IdeationConfig
|
||||
RoadmapConfig
|
||||
} from './types';
|
||||
import type { IdeationConfig } from '../../shared/types';
|
||||
|
||||
/**
|
||||
* Main AgentManager - orchestrates agent process lifecycle
|
||||
@@ -42,8 +43,10 @@ export class AgentManager extends EventEmitter {
|
||||
this.queueManager = new AgentQueueManager(this.state, this.events, this.processManager, this);
|
||||
|
||||
// Listen for auto-swap restart events
|
||||
this.on('auto-swap-restart-task', (taskId: string, _newProfileId: string) => {
|
||||
this.restartTask(taskId);
|
||||
this.on('auto-swap-restart-task', (taskId: string, newProfileId: string) => {
|
||||
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)
|
||||
@@ -243,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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -347,28 +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] 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,
|
||||
@@ -377,6 +410,7 @@ export class AgentManager extends EventEmitter {
|
||||
context.metadata
|
||||
);
|
||||
} else {
|
||||
console.log('[AgentManager] Restarting as task execution');
|
||||
this.startTaskExecution(
|
||||
taskId,
|
||||
context.projectPath,
|
||||
|
||||
@@ -273,22 +273,45 @@ export class AgentProcessManager {
|
||||
|
||||
// Check for rate limit if process failed
|
||||
if (code !== 0) {
|
||||
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();
|
||||
|
||||
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);
|
||||
|
||||
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
|
||||
});
|
||||
@@ -298,30 +321,42 @@ 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');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ 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';
|
||||
@@ -33,18 +35,26 @@ 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
|
||||
enableCompetitorAnalysis,
|
||||
refreshCompetitorAnalysis,
|
||||
config
|
||||
});
|
||||
|
||||
const autoBuildSource = this.processManager.getAutoBuildSourcePath();
|
||||
@@ -74,6 +84,20 @@ 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
|
||||
@@ -141,6 +165,15 @@ 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
|
||||
@@ -318,6 +351,15 @@ export class AgentQueueManager {
|
||||
childProcess.on('exit', (code: number | null) => {
|
||||
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);
|
||||
const storedProjectPath = processInfo?.projectPath;
|
||||
@@ -517,6 +559,15 @@ export class AgentQueueManager {
|
||||
childProcess.on('exit', (code: number | null) => {
|
||||
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);
|
||||
const storedProjectPath = processInfo?.projectPath;
|
||||
|
||||
@@ -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,4 +1,5 @@
|
||||
import { ChildProcess } from 'child_process';
|
||||
import type { IdeationConfig } from '../../shared/types';
|
||||
|
||||
/**
|
||||
* Agent-specific types for process and state management
|
||||
@@ -32,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 {
|
||||
|
||||
@@ -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}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -23,8 +23,8 @@ import type { BrowserWindow } from 'electron';
|
||||
import { IPC_CHANNELS } from '../shared/constants';
|
||||
import type { AppUpdateInfo } from '../shared/types';
|
||||
|
||||
// Debug mode - set via environment variable
|
||||
const DEBUG_UPDATER = process.env.DEBUG_UPDATER === 'true' || process.env.DEBUG === 'true';
|
||||
// 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
|
||||
|
||||
@@ -91,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
|
||||
@@ -103,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;
|
||||
@@ -117,7 +117,7 @@ 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()) {
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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: { 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',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
@@ -141,16 +141,9 @@ app.whenReady().then(() => {
|
||||
|
||||
// Log debug mode status
|
||||
const isDebugMode = process.env.DEBUG === 'true';
|
||||
const isAutoClaudeDebug = process.env.AUTO_CLAUDE_DEBUG === 'true';
|
||||
if (isDebugMode || isAutoClaudeDebug) {
|
||||
if (isDebugMode) {
|
||||
console.warn('[main] ========================================');
|
||||
console.warn('[main] DEBUG MODE ENABLED');
|
||||
if (isDebugMode) {
|
||||
console.warn('[main] - DEBUG=true (Ideation/Roadmap debug logging)');
|
||||
}
|
||||
if (isAutoClaudeDebug) {
|
||||
console.warn('[main] - AUTO_CLAUDE_DEBUG=true (Core features debug logging)');
|
||||
}
|
||||
console.warn('[main] DEBUG MODE ENABLED (DEBUG=true)');
|
||||
console.warn('[main] ========================================');
|
||||
}
|
||||
|
||||
|
||||
@@ -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,7 +1,7 @@
|
||||
import { ipcMain } from 'electron';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import path from 'path';
|
||||
import { existsSync, mkdirSync, writeFileSync } from 'fs';
|
||||
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs';
|
||||
import { IPC_CHANNELS, getSpecsDir } from '../../shared/constants';
|
||||
import type {
|
||||
IPCResult,
|
||||
@@ -375,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';
|
||||
|
||||
/**
|
||||
@@ -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
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -11,10 +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
|
||||
getGraphitiDatabaseDetails
|
||||
} from './utils';
|
||||
import { getEffectiveSourcePath } from '../../updater/path-resolver';
|
||||
import {
|
||||
loadGraphitiStateFromSpecs,
|
||||
buildMemoryStatus
|
||||
@@ -39,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);
|
||||
@@ -110,8 +111,8 @@ export function registerProjectContextHandlers(
|
||||
project.path,
|
||||
project.autoBuildPath,
|
||||
memoryStatus.available,
|
||||
memoryStatus.host,
|
||||
memoryStatus.port
|
||||
memoryStatus.dbPath,
|
||||
memoryStatus.database
|
||||
);
|
||||
|
||||
return {
|
||||
@@ -144,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();
|
||||
}
|
||||
|
||||
@@ -69,56 +69,42 @@ export function registerEnvHandlers(
|
||||
if (config.graphitiEnabled !== undefined) {
|
||||
existingVars['GRAPHITI_ENABLED'] = config.graphitiEnabled ? 'true' : 'false';
|
||||
}
|
||||
// Graphiti Provider Configuration
|
||||
// Memory Provider Configuration (embeddings only - LLM uses Claude SDK)
|
||||
if (config.graphitiProviderConfig) {
|
||||
const pc = config.graphitiProviderConfig;
|
||||
if (pc.llmProvider) existingVars['GRAPHITI_LLM_PROVIDER'] = pc.llmProvider;
|
||||
// Embedding provider only (LLM provider removed - Claude SDK handles RAG)
|
||||
if (pc.embeddingProvider) existingVars['GRAPHITI_EMBEDDER_PROVIDER'] = pc.embeddingProvider;
|
||||
// OpenAI
|
||||
// OpenAI Embeddings
|
||||
if (pc.openaiApiKey) existingVars['OPENAI_API_KEY'] = pc.openaiApiKey;
|
||||
if (pc.openaiModel) existingVars['OPENAI_MODEL'] = pc.openaiModel;
|
||||
if (pc.openaiEmbeddingModel) existingVars['OPENAI_EMBEDDING_MODEL'] = pc.openaiEmbeddingModel;
|
||||
// Anthropic
|
||||
if (pc.anthropicApiKey) existingVars['ANTHROPIC_API_KEY'] = pc.anthropicApiKey;
|
||||
if (pc.anthropicModel) existingVars['GRAPHITI_ANTHROPIC_MODEL'] = pc.anthropicModel;
|
||||
// Azure OpenAI
|
||||
// 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.azureOpenaiLlmDeployment) existingVars['AZURE_OPENAI_LLM_DEPLOYMENT'] = pc.azureOpenaiLlmDeployment;
|
||||
if (pc.azureOpenaiEmbeddingDeployment) existingVars['AZURE_OPENAI_EMBEDDING_DEPLOYMENT'] = pc.azureOpenaiEmbeddingDeployment;
|
||||
// Voyage
|
||||
// Voyage Embeddings
|
||||
if (pc.voyageApiKey) existingVars['VOYAGE_API_KEY'] = pc.voyageApiKey;
|
||||
if (pc.voyageEmbeddingModel) existingVars['VOYAGE_EMBEDDING_MODEL'] = pc.voyageEmbeddingModel;
|
||||
// Google
|
||||
// Google Embeddings
|
||||
if (pc.googleApiKey) existingVars['GOOGLE_API_KEY'] = pc.googleApiKey;
|
||||
if (pc.googleLlmModel) existingVars['GOOGLE_LLM_MODEL'] = pc.googleLlmModel;
|
||||
if (pc.googleEmbeddingModel) existingVars['GOOGLE_EMBEDDING_MODEL'] = pc.googleEmbeddingModel;
|
||||
// Ollama
|
||||
// Ollama Embeddings
|
||||
if (pc.ollamaBaseUrl) existingVars['OLLAMA_BASE_URL'] = pc.ollamaBaseUrl;
|
||||
if (pc.ollamaLlmModel) existingVars['OLLAMA_LLM_MODEL'] = pc.ollamaLlmModel;
|
||||
if (pc.ollamaEmbeddingModel) existingVars['OLLAMA_EMBEDDING_MODEL'] = pc.ollamaEmbeddingModel;
|
||||
if (pc.ollamaEmbeddingDim) existingVars['OLLAMA_EMBEDDING_DIM'] = String(pc.ollamaEmbeddingDim);
|
||||
// FalkorDB
|
||||
if (pc.falkorDbHost) existingVars['GRAPHITI_FALKORDB_HOST'] = pc.falkorDbHost;
|
||||
if (pc.falkorDbPort) existingVars['GRAPHITI_FALKORDB_PORT'] = String(pc.falkorDbPort);
|
||||
if (pc.falkorDbPassword) existingVars['GRAPHITI_FALKORDB_PASSWORD'] = pc.falkorDbPassword;
|
||||
// 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';
|
||||
}
|
||||
@@ -161,50 +147,39 @@ ${existingVars['DEFAULT_BRANCH'] ? `DEFAULT_BRANCH=${existingVars['DEFAULT_BRANC
|
||||
${existingVars['ENABLE_FANCY_UI'] !== undefined ? `ENABLE_FANCY_UI=${existingVars['ENABLE_FANCY_UI']}` : '# ENABLE_FANCY_UI=true'}
|
||||
|
||||
# =============================================================================
|
||||
# GRAPHITI MEMORY INTEGRATION (OPTIONAL)
|
||||
# Multi-provider support: OpenAI, Anthropic, Google AI, Azure OpenAI, Ollama, Voyage
|
||||
# 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'}
|
||||
|
||||
# Provider Selection
|
||||
${existingVars['GRAPHITI_LLM_PROVIDER'] ? `GRAPHITI_LLM_PROVIDER=${existingVars['GRAPHITI_LLM_PROVIDER']}` : '# GRAPHITI_LLM_PROVIDER=openai'}
|
||||
${existingVars['GRAPHITI_EMBEDDER_PROVIDER'] ? `GRAPHITI_EMBEDDER_PROVIDER=${existingVars['GRAPHITI_EMBEDDER_PROVIDER']}` : '# GRAPHITI_EMBEDDER_PROVIDER=openai'}
|
||||
# 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 Settings
|
||||
# OpenAI Embeddings
|
||||
${existingVars['OPENAI_API_KEY'] ? `OPENAI_API_KEY=${existingVars['OPENAI_API_KEY']}` : '# OPENAI_API_KEY='}
|
||||
${existingVars['OPENAI_MODEL'] ? `OPENAI_MODEL=${existingVars['OPENAI_MODEL']}` : '# OPENAI_MODEL=gpt-4o-mini'}
|
||||
${existingVars['OPENAI_EMBEDDING_MODEL'] ? `OPENAI_EMBEDDING_MODEL=${existingVars['OPENAI_EMBEDDING_MODEL']}` : '# OPENAI_EMBEDDING_MODEL=text-embedding-3-small'}
|
||||
|
||||
# Anthropic Settings (LLM only - use with Voyage or OpenAI for embeddings)
|
||||
${existingVars['ANTHROPIC_API_KEY'] ? `ANTHROPIC_API_KEY=${existingVars['ANTHROPIC_API_KEY']}` : '# ANTHROPIC_API_KEY='}
|
||||
${existingVars['GRAPHITI_ANTHROPIC_MODEL'] ? `GRAPHITI_ANTHROPIC_MODEL=${existingVars['GRAPHITI_ANTHROPIC_MODEL']}` : '# GRAPHITI_ANTHROPIC_MODEL=claude-sonnet-4-5-latest'}
|
||||
|
||||
# Azure OpenAI Settings
|
||||
# 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_LLM_DEPLOYMENT'] ? `AZURE_OPENAI_LLM_DEPLOYMENT=${existingVars['AZURE_OPENAI_LLM_DEPLOYMENT']}` : '# AZURE_OPENAI_LLM_DEPLOYMENT='}
|
||||
${existingVars['AZURE_OPENAI_EMBEDDING_DEPLOYMENT'] ? `AZURE_OPENAI_EMBEDDING_DEPLOYMENT=${existingVars['AZURE_OPENAI_EMBEDDING_DEPLOYMENT']}` : '# AZURE_OPENAI_EMBEDDING_DEPLOYMENT='}
|
||||
|
||||
# Voyage AI Settings (Embeddings only - great with Anthropic)
|
||||
# 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 Settings (LLM and Embeddings - Gemini)
|
||||
# Google AI Embeddings
|
||||
${existingVars['GOOGLE_API_KEY'] ? `GOOGLE_API_KEY=${existingVars['GOOGLE_API_KEY']}` : '# GOOGLE_API_KEY='}
|
||||
${existingVars['GOOGLE_LLM_MODEL'] ? `GOOGLE_LLM_MODEL=${existingVars['GOOGLE_LLM_MODEL']}` : '# GOOGLE_LLM_MODEL=gemini-2.0-flash'}
|
||||
${existingVars['GOOGLE_EMBEDDING_MODEL'] ? `GOOGLE_EMBEDDING_MODEL=${existingVars['GOOGLE_EMBEDDING_MODEL']}` : '# GOOGLE_EMBEDDING_MODEL=text-embedding-004'}
|
||||
|
||||
# Ollama Settings (Local - free)
|
||||
# Ollama Embeddings (Local - free)
|
||||
${existingVars['OLLAMA_BASE_URL'] ? `OLLAMA_BASE_URL=${existingVars['OLLAMA_BASE_URL']}` : '# OLLAMA_BASE_URL=http://localhost:11434'}
|
||||
${existingVars['OLLAMA_LLM_MODEL'] ? `OLLAMA_LLM_MODEL=${existingVars['OLLAMA_LLM_MODEL']}` : '# OLLAMA_LLM_MODEL='}
|
||||
${existingVars['OLLAMA_EMBEDDING_MODEL'] ? `OLLAMA_EMBEDDING_MODEL=${existingVars['OLLAMA_EMBEDDING_MODEL']}` : '# OLLAMA_EMBEDDING_MODEL='}
|
||||
${existingVars['OLLAMA_EMBEDDING_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'}
|
||||
|
||||
# FalkorDB Connection
|
||||
${existingVars['GRAPHITI_FALKORDB_HOST'] ? `GRAPHITI_FALKORDB_HOST=${existingVars['GRAPHITI_FALKORDB_HOST']}` : '# GRAPHITI_FALKORDB_HOST=localhost'}
|
||||
${existingVars['GRAPHITI_FALKORDB_PORT'] ? `GRAPHITI_FALKORDB_PORT=${existingVars['GRAPHITI_FALKORDB_PORT']}` : '# GRAPHITI_FALKORDB_PORT=6380'}
|
||||
${existingVars['GRAPHITI_FALKORDB_PASSWORD'] ? `GRAPHITI_FALKORDB_PASSWORD=${existingVars['GRAPHITI_FALKORDB_PASSWORD']}` : '# GRAPHITI_FALKORDB_PASSWORD='}
|
||||
# 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;
|
||||
@@ -316,59 +291,43 @@ ${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
|
||||
const llmProvider = vars['GRAPHITI_LLM_PROVIDER'];
|
||||
// Populate graphitiProviderConfig from .env file (embeddings only - no LLM provider)
|
||||
const embeddingProvider = vars['GRAPHITI_EMBEDDER_PROVIDER'];
|
||||
if (llmProvider || embeddingProvider || vars['ANTHROPIC_API_KEY'] || vars['AZURE_OPENAI_API_KEY'] ||
|
||||
if (embeddingProvider || vars['AZURE_OPENAI_API_KEY'] ||
|
||||
vars['VOYAGE_API_KEY'] || vars['GOOGLE_API_KEY'] || vars['OLLAMA_BASE_URL']) {
|
||||
config.graphitiProviderConfig = {
|
||||
llmProvider: (llmProvider as 'openai' | 'anthropic' | 'azure_openai' | 'ollama' | 'google' | 'groq') || 'openai',
|
||||
embeddingProvider: (embeddingProvider as 'openai' | 'voyage' | 'azure_openai' | 'ollama' | 'google' | 'huggingface') || 'openai',
|
||||
// OpenAI
|
||||
embeddingProvider: (embeddingProvider as 'openai' | 'voyage' | 'azure_openai' | 'ollama' | 'google') || 'ollama',
|
||||
// OpenAI Embeddings
|
||||
openaiApiKey: vars['OPENAI_API_KEY'],
|
||||
openaiModel: vars['OPENAI_MODEL'],
|
||||
openaiEmbeddingModel: vars['OPENAI_EMBEDDING_MODEL'],
|
||||
// Anthropic
|
||||
anthropicApiKey: vars['ANTHROPIC_API_KEY'],
|
||||
anthropicModel: vars['GRAPHITI_ANTHROPIC_MODEL'],
|
||||
// Azure OpenAI
|
||||
// Azure OpenAI Embeddings
|
||||
azureOpenaiApiKey: vars['AZURE_OPENAI_API_KEY'],
|
||||
azureOpenaiBaseUrl: vars['AZURE_OPENAI_BASE_URL'],
|
||||
azureOpenaiLlmDeployment: vars['AZURE_OPENAI_LLM_DEPLOYMENT'],
|
||||
azureOpenaiEmbeddingDeployment: vars['AZURE_OPENAI_EMBEDDING_DEPLOYMENT'],
|
||||
// Voyage
|
||||
// Voyage Embeddings
|
||||
voyageApiKey: vars['VOYAGE_API_KEY'],
|
||||
voyageEmbeddingModel: vars['VOYAGE_EMBEDDING_MODEL'],
|
||||
// Google
|
||||
// Google Embeddings
|
||||
googleApiKey: vars['GOOGLE_API_KEY'],
|
||||
googleLlmModel: vars['GOOGLE_LLM_MODEL'],
|
||||
googleEmbeddingModel: vars['GOOGLE_EMBEDDING_MODEL'],
|
||||
// Ollama
|
||||
// Ollama Embeddings
|
||||
ollamaBaseUrl: vars['OLLAMA_BASE_URL'],
|
||||
ollamaLlmModel: vars['OLLAMA_LLM_MODEL'],
|
||||
ollamaEmbeddingModel: vars['OLLAMA_EMBEDDING_MODEL'],
|
||||
ollamaEmbeddingDim: vars['OLLAMA_EMBEDDING_DIM'] ? parseInt(vars['OLLAMA_EMBEDDING_DIM'], 10) : undefined,
|
||||
// FalkorDB
|
||||
falkorDbHost: vars['GRAPHITI_FALKORDB_HOST'],
|
||||
falkorDbPort: vars['GRAPHITI_FALKORDB_PORT'] ? parseInt(vars['GRAPHITI_FALKORDB_PORT'], 10) : undefined,
|
||||
falkorDbPassword: vars['GRAPHITI_FALKORDB_PASSWORD'],
|
||||
// LadybugDB
|
||||
database: vars['GRAPHITI_DATABASE'],
|
||||
dbPath: vars['GRAPHITI_DB_PATH'],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,11 @@ function isValidGitHubRepo(repo: string): boolean {
|
||||
|
||||
// Regex patterns for parsing device code from gh CLI output
|
||||
// Expected format: "! First copy your one-time code: XXXX-XXXX"
|
||||
const DEVICE_CODE_PATTERN = /(?:one-time code|code):\s*([A-Z0-9]{4}-[A-Z0-9]{4})/i;
|
||||
// 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;
|
||||
@@ -46,12 +50,15 @@ 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]) {
|
||||
debugLog('Parsed device code:', match[1]);
|
||||
return 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;
|
||||
}
|
||||
@@ -229,7 +236,7 @@ export function registerStartGhAuth(): void {
|
||||
extractedDeviceCode = deviceFlowInfo.deviceCode;
|
||||
extractedAuthUrl = deviceFlowInfo.authUrl;
|
||||
|
||||
debugLog('Device code extracted:', extractedDeviceCode);
|
||||
debugLog('Device code extracted successfully (code redacted for security)');
|
||||
debugLog('Auth URL:', extractedAuthUrl);
|
||||
|
||||
// Open browser using Electron's shell.openExternal
|
||||
@@ -243,6 +250,10 @@ export function registerStartGhAuth(): void {
|
||||
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;
|
||||
@@ -520,7 +531,7 @@ export function registerGetGitHubBranches(): void {
|
||||
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);
|
||||
@@ -529,7 +540,7 @@ export function registerGetGitHubBranches(): void {
|
||||
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
|
||||
@@ -562,6 +573,203 @@ export function registerGetGitHubBranches(): void {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
@@ -575,5 +783,8 @@ export function registerGithubOAuthHandlers(): void {
|
||||
registerListUserRepos();
|
||||
registerDetectGitHubRepo();
|
||||
registerGetGitHubBranches();
|
||||
registerCreateGitHubRepo();
|
||||
registerAddGitRemote();
|
||||
registerListGitHubOrgs();
|
||||
debugLog('GitHub OAuth handlers registered');
|
||||
}
|
||||
|
||||
@@ -3,11 +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 } from '../../../shared/utils/debug-logger';
|
||||
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
|
||||
@@ -19,10 +53,20 @@ 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: config.enabledTypes,
|
||||
maxIdeasPerType: config.maxIdeasPerType
|
||||
enabledTypes: configWithSettings.enabledTypes,
|
||||
maxIdeasPerType: configWithSettings.maxIdeasPerType,
|
||||
model: configWithSettings.model,
|
||||
thinkingLevel: configWithSettings.thinkingLevel
|
||||
});
|
||||
|
||||
if (!mainWindow) return;
|
||||
@@ -40,11 +84,13 @@ export function startIdeationGeneration(
|
||||
|
||||
debugLog('[Ideation Handler] Starting agent manager generation:', {
|
||||
projectId,
|
||||
projectPath: project.path
|
||||
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(
|
||||
@@ -68,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);
|
||||
@@ -81,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(
|
||||
|
||||
@@ -92,7 +92,7 @@ export function setupIpcHandlers(
|
||||
// Insights handlers
|
||||
registerInsightsHandlers(getMainWindow);
|
||||
|
||||
// Docker & infrastructure handlers (for Graphiti/FalkorDB)
|
||||
// Memory & infrastructure handlers (for Graphiti/LadybugDB)
|
||||
registerDockerHandlers();
|
||||
|
||||
// App auto-update handlers
|
||||
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -26,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
|
||||
@@ -102,93 +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.
|
||||
* Works across platforms (macOS, Windows, Linux) in both dev and production modes.
|
||||
*/
|
||||
const detectAutoBuildSourcePath = (): string | null => {
|
||||
const possiblePaths: string[] = [];
|
||||
|
||||
// Development mode paths
|
||||
if (is.dev) {
|
||||
// In dev, __dirname is typically auto-claude-ui/out/main
|
||||
// We need to go up to the project root to find auto-claude/
|
||||
possiblePaths.push(
|
||||
path.resolve(__dirname, '..', '..', '..', 'auto-claude'), // From out/main up 3 levels
|
||||
path.resolve(__dirname, '..', '..', 'auto-claude'), // From out/main up 2 levels
|
||||
path.resolve(process.cwd(), 'auto-claude'), // From cwd (project root)
|
||||
path.resolve(process.cwd(), '..', 'auto-claude') // From cwd parent (if running from auto-claude-ui/)
|
||||
);
|
||||
} else {
|
||||
// Production mode paths (packaged app)
|
||||
// On Windows/Linux/macOS, the app might be installed anywhere
|
||||
// We check common locations relative to the app bundle
|
||||
const appPath = app.getAppPath();
|
||||
possiblePaths.push(
|
||||
path.resolve(appPath, '..', 'auto-claude'), // Sibling to app
|
||||
path.resolve(appPath, '..', '..', 'auto-claude'), // Up 2 from app
|
||||
path.resolve(appPath, '..', '..', '..', 'auto-claude'), // Up 3 from app
|
||||
path.resolve(process.resourcesPath, '..', 'auto-claude'), // Relative to resources
|
||||
path.resolve(process.resourcesPath, '..', '..', 'auto-claude')
|
||||
);
|
||||
}
|
||||
|
||||
// Add process.cwd() as last resort on all platforms
|
||||
possiblePaths.push(path.resolve(process.cwd(), 'auto-claude'));
|
||||
|
||||
// Enable debug logging with AUTO_CLAUDE_DEBUG=1
|
||||
const debug = process.env.AUTO_CLAUDE_DEBUG === '1' || process.env.AUTO_CLAUDE_DEBUG === 'true';
|
||||
|
||||
if (debug) {
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] Platform:', process.platform);
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] Is dev:', is.dev);
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] __dirname:', __dirname);
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] app.getAppPath():', app.getAppPath());
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] process.cwd():', process.cwd());
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] Checking paths:', possiblePaths);
|
||||
}
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
// Use requirements.txt as marker - it always exists in auto-claude source
|
||||
const markerPath = path.join(p, 'requirements.txt');
|
||||
const exists = existsSync(p) && existsSync(markerPath);
|
||||
|
||||
if (debug) {
|
||||
console.warn(`[project-handlers:detectAutoBuildSourcePath] Checking ${p}: ${exists ? '✓ FOUND' : '✗ not found'}`);
|
||||
}
|
||||
|
||||
if (exists) {
|
||||
console.warn(`[project-handlers:detectAutoBuildSourcePath] Auto-detected source path: ${p}`);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] Could not auto-detect Auto Claude source path.');
|
||||
console.warn('[project-handlers:detectAutoBuildSourcePath] Set AUTO_CLAUDE_DEBUG=1 environment variable for detailed path checking.');
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
@@ -211,7 +125,7 @@ const initializePythonEnvironment = async (
|
||||
pythonEnvManager: PythonEnvManager,
|
||||
agentManager: AgentManager
|
||||
): Promise<PythonEnvStatus> => {
|
||||
const autoBuildSource = getAutoBuildSourcePath();
|
||||
const autoBuildSource = getEffectiveSourcePath();
|
||||
if (!autoBuildSource) {
|
||||
console.warn('[IPC] Auto-build source not found, skipping Python env init');
|
||||
return {
|
||||
@@ -304,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
|
||||
// ============================================
|
||||
|
||||
@@ -1,13 +1,45 @@
|
||||
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 { 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
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Register all roadmap-related IPC handlers
|
||||
@@ -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,
|
||||
@@ -172,10 +204,19 @@ export function registerRoadmapHandlers(
|
||||
|
||||
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
|
||||
enableCompetitorAnalysis,
|
||||
refreshCompetitorAnalysis,
|
||||
config
|
||||
});
|
||||
|
||||
const mainWindow = getMainWindow();
|
||||
@@ -194,11 +235,19 @@ export function registerRoadmapHandlers(
|
||||
|
||||
debugLog('[Roadmap Handler] Starting agent manager generation:', {
|
||||
projectId,
|
||||
projectPath: project.path
|
||||
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(
|
||||
@@ -215,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;
|
||||
|
||||
@@ -230,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(
|
||||
|
||||
@@ -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' };
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -1650,4 +1650,3 @@ ${issue.body || 'No description provided.'}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -876,7 +876,7 @@
|
||||
try {
|
||||
// Set status to in_progress for the restart
|
||||
newStatus = 'in_progress';
|
||||
|
||||
|
||||
// Update plan status for restart
|
||||
if (plan) {
|
||||
plan.status = 'in_progress';
|
||||
@@ -897,7 +897,7 @@
|
||||
const specsBaseDir = getSpecsDir(project.autoBuildPath);
|
||||
const specDirForWatcher = path.join(project.path, specsBaseDir, task.specId);
|
||||
fileWatcher.watch(taskId, specDirForWatcher);
|
||||
|
||||
|
||||
agentManager.startTaskExecution(
|
||||
taskId,
|
||||
project.path,
|
||||
@@ -932,7 +932,7 @@
|
||||
taskId,
|
||||
recovered: true,
|
||||
newStatus,
|
||||
message: autoRestarted
|
||||
message: autoRestarted
|
||||
? 'Task recovered and restarted successfully'
|
||||
: `Task recovered successfully and moved to ${newStatus}`,
|
||||
autoRestarted
|
||||
@@ -1494,4 +1494,3 @@
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -876,7 +876,7 @@
|
||||
try {
|
||||
// Set status to in_progress for the restart
|
||||
newStatus = 'in_progress';
|
||||
|
||||
|
||||
// Update plan status for restart
|
||||
if (plan) {
|
||||
plan.status = 'in_progress';
|
||||
@@ -897,7 +897,7 @@
|
||||
const specsBaseDir = getSpecsDir(project.autoBuildPath);
|
||||
const specDirForWatcher = path.join(project.path, specsBaseDir, task.specId);
|
||||
fileWatcher.watch(taskId, specDirForWatcher);
|
||||
|
||||
|
||||
agentManager.startTaskExecution(
|
||||
taskId,
|
||||
project.path,
|
||||
@@ -932,7 +932,7 @@
|
||||
taskId,
|
||||
recovered: true,
|
||||
newStatus,
|
||||
message: autoRestarted
|
||||
message: autoRestarted
|
||||
? 'Task recovered and restarted successfully'
|
||||
: `Task recovered successfully and moved to ${newStatus}`,
|
||||
autoRestarted
|
||||
|
||||
@@ -218,12 +218,12 @@
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -218,12 +218,12 @@
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -484,4 +484,4 @@
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
);
|
||||
|
||||
@@ -48,8 +48,8 @@ const detectAutoBuildSourcePath = (): string | null => {
|
||||
// Add process.cwd() as last resort on all platforms
|
||||
possiblePaths.push(path.resolve(process.cwd(), 'auto-claude'));
|
||||
|
||||
// Enable debug logging with AUTO_CLAUDE_DEBUG=1
|
||||
const debug = process.env.AUTO_CLAUDE_DEBUG === '1' || process.env.AUTO_CLAUDE_DEBUG === 'true';
|
||||
// Enable debug logging with DEBUG=1
|
||||
const debug = process.env.DEBUG === '1' || process.env.DEBUG === 'true';
|
||||
|
||||
if (debug) {
|
||||
console.warn('[detectAutoBuildSourcePath] Platform:', process.platform);
|
||||
@@ -76,7 +76,7 @@ const detectAutoBuildSourcePath = (): string | null => {
|
||||
}
|
||||
|
||||
console.warn('[detectAutoBuildSourcePath] Could not auto-detect Auto Claude source path. Please configure manually in settings.');
|
||||
console.warn('[detectAutoBuildSourcePath] Set AUTO_CLAUDE_DEBUG=1 environment variable for detailed path checking.');
|
||||
console.warn('[detectAutoBuildSourcePath] Set DEBUG=1 environment variable for detailed path checking.');
|
||||
return null;
|
||||
};
|
||||
|
||||
|
||||
@@ -951,7 +951,7 @@ export function registerTaskHandlers(
|
||||
try {
|
||||
// Set status to in_progress for the restart
|
||||
newStatus = 'in_progress';
|
||||
|
||||
|
||||
// Update plan status for restart
|
||||
if (plan) {
|
||||
plan.status = 'in_progress';
|
||||
@@ -964,7 +964,7 @@ export function registerTaskHandlers(
|
||||
const specsBaseDir = getSpecsDir(project.autoBuildPath);
|
||||
const specDirForWatcher = path.join(project.path, specsBaseDir, task.specId);
|
||||
fileWatcher.watch(taskId, specDirForWatcher);
|
||||
|
||||
|
||||
// Note: Parallel execution is handled internally by the agent
|
||||
agentManager.startTaskExecution(
|
||||
taskId,
|
||||
@@ -1000,7 +1000,7 @@ export function registerTaskHandlers(
|
||||
taskId,
|
||||
recovered: true,
|
||||
newStatus,
|
||||
message: autoRestarted
|
||||
message: autoRestarted
|
||||
? 'Task recovered and restarted successfully'
|
||||
: `Task recovered successfully and moved to ${newStatus}`,
|
||||
autoRestarted
|
||||
|
||||
@@ -247,13 +247,14 @@ export function registerTaskExecutionHandlers(
|
||||
}
|
||||
|
||||
// Step 3: Clean untracked files that came from the merge
|
||||
const cleanResult = spawnSync('git', ['clean', '-fd'], {
|
||||
// IMPORTANT: Exclude .auto-claude and .worktrees directories to preserve specs and worktree data
|
||||
const cleanResult = spawnSync('git', ['clean', '-fd', '-e', '.auto-claude', '-e', '.worktrees'], {
|
||||
cwd: project.path,
|
||||
encoding: 'utf-8',
|
||||
stdio: 'pipe'
|
||||
});
|
||||
if (cleanResult.status === 0) {
|
||||
console.log('[TASK_REVIEW] Cleaned untracked files in main');
|
||||
console.log('[TASK_REVIEW] Cleaned untracked files in main (excluding .auto-claude and .worktrees)');
|
||||
}
|
||||
|
||||
console.log('[TASK_REVIEW] Main branch restored to pre-merge state');
|
||||
|
||||
@@ -2,7 +2,7 @@ import { ipcMain, BrowserWindow } from 'electron';
|
||||
import { IPC_CHANNELS, AUTO_BUILD_PATHS } from '../../../shared/constants';
|
||||
import type { IPCResult, WorktreeStatus, WorktreeDiff, WorktreeDiffFile, WorktreeMergeResult, WorktreeDiscardResult, WorktreeListResult, WorktreeListItem } from '../../../shared/types';
|
||||
import path from 'path';
|
||||
import { existsSync, readdirSync, statSync } from 'fs';
|
||||
import { existsSync, readdirSync, statSync, readFileSync } from 'fs';
|
||||
import { execSync, spawn, spawnSync } from 'child_process';
|
||||
import { projectStore } from '../../project-store';
|
||||
import { PythonEnvManager } from '../../python-env-manager';
|
||||
@@ -11,6 +11,26 @@ import { getProfileEnv } from '../../rate-limit-detector';
|
||||
import { findTaskAndProject } from './shared';
|
||||
import { findPythonCommand, parsePythonCommand } from '../../python-detector';
|
||||
|
||||
/**
|
||||
* Read the stored base branch from task_metadata.json
|
||||
* This is the branch the task was created from (set by user during task creation)
|
||||
*/
|
||||
function getTaskBaseBranch(specDir: string): string | undefined {
|
||||
try {
|
||||
const metadataPath = path.join(specDir, 'task_metadata.json');
|
||||
if (existsSync(metadataPath)) {
|
||||
const metadata = JSON.parse(readFileSync(metadataPath, 'utf-8'));
|
||||
// Return baseBranch if explicitly set (not the __project_default__ marker)
|
||||
if (metadata.baseBranch && metadata.baseBranch !== '__project_default__') {
|
||||
return metadata.baseBranch;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[getTaskBaseBranch] Failed to read task metadata:', e);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register worktree management handlers
|
||||
*/
|
||||
@@ -61,12 +81,13 @@ export function registerWorktreeHandlers(
|
||||
baseBranch = 'main';
|
||||
}
|
||||
|
||||
// Get commit count
|
||||
// Get commit count (cross-platform - no shell syntax)
|
||||
let commitCount = 0;
|
||||
try {
|
||||
const countOutput = execSync(`git rev-list --count ${baseBranch}..HEAD 2>/dev/null || echo 0`, {
|
||||
const countOutput = execSync(`git rev-list --count ${baseBranch}..HEAD`, {
|
||||
cwd: worktreePath,
|
||||
encoding: 'utf-8'
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
}).trim();
|
||||
commitCount = parseInt(countOutput, 10) || 0;
|
||||
} catch {
|
||||
@@ -78,10 +99,12 @@ export function registerWorktreeHandlers(
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
|
||||
let diffStat = '';
|
||||
try {
|
||||
const diffStat = execSync(`git diff --stat ${baseBranch}...HEAD 2>/dev/null || echo ""`, {
|
||||
diffStat = execSync(`git diff --stat ${baseBranch}...HEAD`, {
|
||||
cwd: worktreePath,
|
||||
encoding: 'utf-8'
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
}).trim();
|
||||
|
||||
// Parse the summary line (e.g., "3 files changed, 50 insertions(+), 10 deletions(-)")
|
||||
@@ -159,17 +182,21 @@ export function registerWorktreeHandlers(
|
||||
// Get the diff with file stats
|
||||
const files: WorktreeDiffFile[] = [];
|
||||
|
||||
let numstat = '';
|
||||
let nameStatus = '';
|
||||
try {
|
||||
// Get numstat for additions/deletions per file
|
||||
const numstat = execSync(`git diff --numstat ${baseBranch}...HEAD 2>/dev/null || echo ""`, {
|
||||
// Get numstat for additions/deletions per file (cross-platform)
|
||||
numstat = execSync(`git diff --numstat ${baseBranch}...HEAD`, {
|
||||
cwd: worktreePath,
|
||||
encoding: 'utf-8'
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
}).trim();
|
||||
|
||||
// Get name-status for file status
|
||||
const nameStatus = execSync(`git diff --name-status ${baseBranch}...HEAD 2>/dev/null || echo ""`, {
|
||||
// Get name-status for file status (cross-platform)
|
||||
nameStatus = execSync(`git diff --name-status ${baseBranch}...HEAD`, {
|
||||
cwd: worktreePath,
|
||||
encoding: 'utf-8'
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
}).trim();
|
||||
|
||||
// Parse name-status to get file statuses
|
||||
@@ -320,6 +347,13 @@ export function registerWorktreeHandlers(
|
||||
args.push('--no-commit');
|
||||
}
|
||||
|
||||
// Add --base-branch if task was created with a specific base branch
|
||||
const taskBaseBranch = getTaskBaseBranch(specDir);
|
||||
if (taskBaseBranch) {
|
||||
args.push('--base-branch', taskBaseBranch);
|
||||
debug('Using stored base branch:', taskBaseBranch);
|
||||
}
|
||||
|
||||
const pythonPath = pythonEnvManager.getPythonPath() || findPythonCommand() || 'python';
|
||||
debug('Running command:', pythonPath, args.join(' '));
|
||||
debug('Working directory:', sourcePath);
|
||||
@@ -332,7 +366,7 @@ export function registerWorktreeHandlers(
|
||||
});
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const MERGE_TIMEOUT_MS = 120000; // 2 minutes timeout for merge operations
|
||||
const MERGE_TIMEOUT_MS = 600000; // 10 minutes timeout for AI merge operations with many files
|
||||
let timeoutId: NodeJS.Timeout | null = null;
|
||||
let resolved = false;
|
||||
|
||||
@@ -446,14 +480,17 @@ export function registerWorktreeHandlers(
|
||||
const specBranch = `auto-claude/${task.specId}`;
|
||||
try {
|
||||
// Check if current branch contains all commits from spec branch
|
||||
const mergeBaseResult = execSync(
|
||||
`git merge-base --is-ancestor ${specBranch} HEAD 2>/dev/null && echo "merged" || echo "not-merged"`,
|
||||
{ cwd: project.path, encoding: 'utf-8' }
|
||||
).trim();
|
||||
mergeAlreadyCommitted = mergeBaseResult === 'merged';
|
||||
// git merge-base --is-ancestor returns exit code 0 if true, 1 if false
|
||||
execSync(
|
||||
`git merge-base --is-ancestor ${specBranch} HEAD`,
|
||||
{ cwd: project.path, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }
|
||||
);
|
||||
// If we reach here, the command succeeded (exit code 0) - branch is merged
|
||||
mergeAlreadyCommitted = true;
|
||||
debug('Merge already committed check:', mergeAlreadyCommitted);
|
||||
} catch {
|
||||
// Branch may not exist or other error - assume not merged
|
||||
// Exit code 1 means not merged, or branch may not exist
|
||||
mergeAlreadyCommitted = false;
|
||||
debug('Could not check merge status, assuming not merged');
|
||||
}
|
||||
}
|
||||
@@ -659,6 +696,7 @@ export function registerWorktreeHandlers(
|
||||
}
|
||||
|
||||
const runScript = path.join(sourcePath, 'run.py');
|
||||
const specDir = path.join(project.path, project.autoBuildPath || '.auto-claude', 'specs', task.specId);
|
||||
const args = [
|
||||
runScript,
|
||||
'--spec', task.specId,
|
||||
@@ -666,6 +704,13 @@ export function registerWorktreeHandlers(
|
||||
'--merge-preview'
|
||||
];
|
||||
|
||||
// Add --base-branch if task was created with a specific base branch
|
||||
const taskBaseBranch = getTaskBaseBranch(specDir);
|
||||
if (taskBaseBranch) {
|
||||
args.push('--base-branch', taskBaseBranch);
|
||||
console.warn('[IPC] Using stored base branch for preview:', taskBaseBranch);
|
||||
}
|
||||
|
||||
const pythonPath = pythonEnvManager.getPythonPath() || findPythonCommand() || 'python';
|
||||
console.warn('[IPC] Running merge preview:', pythonPath, args.join(' '));
|
||||
|
||||
@@ -892,27 +937,30 @@ export function registerWorktreeHandlers(
|
||||
baseBranch = 'main';
|
||||
}
|
||||
|
||||
// Get commit count
|
||||
// Get commit count (cross-platform - no shell syntax)
|
||||
let commitCount = 0;
|
||||
try {
|
||||
const countOutput = execSync(`git rev-list --count ${baseBranch}..HEAD 2>/dev/null || echo 0`, {
|
||||
const countOutput = execSync(`git rev-list --count ${baseBranch}..HEAD`, {
|
||||
cwd: entryPath,
|
||||
encoding: 'utf-8'
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
}).trim();
|
||||
commitCount = parseInt(countOutput, 10) || 0;
|
||||
} catch {
|
||||
commitCount = 0;
|
||||
}
|
||||
|
||||
// Get diff stats
|
||||
// Get diff stats (cross-platform - no shell syntax)
|
||||
let filesChanged = 0;
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
let diffStat = '';
|
||||
|
||||
try {
|
||||
const diffStat = execSync(`git diff --shortstat ${baseBranch}...HEAD 2>/dev/null || echo ""`, {
|
||||
diffStat = execSync(`git diff --shortstat ${baseBranch}...HEAD`, {
|
||||
cwd: entryPath,
|
||||
encoding: 'utf-8'
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
}).trim();
|
||||
|
||||
const filesMatch = diffStat.match(/(\d+) files? changed/);
|
||||
|
||||
@@ -0,0 +1,631 @@
|
||||
/**
|
||||
* Memory Service
|
||||
*
|
||||
* Queries the LadybugDB graph database for memories stored by Graphiti.
|
||||
* Uses Python subprocess to communicate with the embedded database.
|
||||
*
|
||||
* LadybugDB stores data in Kuzu format at ~/.auto-claude/memories/<database>/
|
||||
*/
|
||||
|
||||
import { spawn } from 'child_process';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import * as fs from 'fs';
|
||||
import { app } from 'electron';
|
||||
import { findPythonCommand, parsePythonCommand } from './python-detector';
|
||||
import type { MemoryEpisode } from '../shared/types';
|
||||
|
||||
interface MemoryServiceConfig {
|
||||
dbPath: string;
|
||||
database: string;
|
||||
}
|
||||
|
||||
// Embedder configuration for semantic search
|
||||
export interface EmbedderConfig {
|
||||
provider: 'openai' | 'google' | 'ollama' | 'voyage' | 'azure_openai';
|
||||
// OpenAI
|
||||
openaiApiKey?: string;
|
||||
openaiEmbeddingModel?: string;
|
||||
// Google AI
|
||||
googleApiKey?: string;
|
||||
googleEmbeddingModel?: string;
|
||||
// Ollama
|
||||
ollamaBaseUrl?: string;
|
||||
ollamaEmbeddingModel?: string;
|
||||
ollamaEmbeddingDim?: number;
|
||||
// Voyage AI
|
||||
voyageApiKey?: string;
|
||||
voyageEmbeddingModel?: string;
|
||||
// Azure OpenAI
|
||||
azureOpenaiApiKey?: string;
|
||||
azureOpenaiBaseUrl?: string;
|
||||
azureOpenaiEmbeddingDeployment?: string;
|
||||
}
|
||||
|
||||
interface SemanticSearchResult extends MemoryQueryResult {
|
||||
search_type: 'semantic' | 'keyword';
|
||||
embedder?: string;
|
||||
}
|
||||
|
||||
interface QueryResult {
|
||||
success: boolean;
|
||||
data?: unknown;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface MemoryQueryResult {
|
||||
memories: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
type: string;
|
||||
timestamp: string;
|
||||
content: string;
|
||||
description?: string;
|
||||
group_id?: string;
|
||||
session_number?: number;
|
||||
score?: number;
|
||||
}>;
|
||||
count: number;
|
||||
query?: string;
|
||||
}
|
||||
|
||||
interface StatusResult {
|
||||
available: boolean;
|
||||
ladybugInstalled: boolean;
|
||||
databasePath: string;
|
||||
database: string;
|
||||
databaseExists: boolean;
|
||||
connected?: boolean;
|
||||
databases?: string[];
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the default database path
|
||||
*/
|
||||
export function getDefaultDbPath(): string {
|
||||
return path.join(os.homedir(), '.auto-claude', 'memories');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to the query_memory.py script
|
||||
*/
|
||||
function getQueryScriptPath(): string | null {
|
||||
// Look for the script in auto-claude directory (sibling to auto-claude-ui)
|
||||
const possiblePaths = [
|
||||
// Dev mode: from dist/main -> ../../auto-claude
|
||||
path.resolve(__dirname, '..', '..', '..', 'auto-claude', 'query_memory.py'),
|
||||
// Packaged app: from app.getAppPath() (handles asar and resources correctly)
|
||||
path.resolve(app.getAppPath(), '..', 'auto-claude', 'query_memory.py'),
|
||||
// Alternative: from app root
|
||||
path.resolve(process.cwd(), 'auto-claude', 'query_memory.py'),
|
||||
// If running from repo root
|
||||
path.resolve(process.cwd(), '..', 'auto-claude', 'query_memory.py'),
|
||||
];
|
||||
|
||||
for (const p of possiblePaths) {
|
||||
if (fs.existsSync(p)) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a Python memory query command
|
||||
*/
|
||||
async function executeQuery(
|
||||
command: string,
|
||||
args: string[],
|
||||
timeout: number = 10000
|
||||
): Promise<QueryResult> {
|
||||
const pythonCmd = findPythonCommand();
|
||||
if (!pythonCmd) {
|
||||
return { success: false, error: 'Python not found' };
|
||||
}
|
||||
|
||||
const scriptPath = getQueryScriptPath();
|
||||
if (!scriptPath) {
|
||||
return { success: false, error: 'query_memory.py script not found' };
|
||||
}
|
||||
|
||||
const [pythonExe, baseArgs] = parsePythonCommand(pythonCmd);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const fullArgs = [...baseArgs, scriptPath, command, ...args];
|
||||
const proc = spawn(pythonExe, fullArgs, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
timeout,
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
proc.stdout.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
proc.stderr.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
proc.on('close', (code) => {
|
||||
if (code === 0 && stdout) {
|
||||
try {
|
||||
const result = JSON.parse(stdout);
|
||||
resolve(result);
|
||||
} catch {
|
||||
resolve({ success: false, error: `Invalid JSON response: ${stdout}` });
|
||||
}
|
||||
} else {
|
||||
resolve({
|
||||
success: false,
|
||||
error: stderr || `Process exited with code ${code}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
proc.on('error', (err) => {
|
||||
resolve({ success: false, error: err.message });
|
||||
});
|
||||
|
||||
// Handle timeout
|
||||
setTimeout(() => {
|
||||
proc.kill();
|
||||
resolve({ success: false, error: 'Query timed out' });
|
||||
}, timeout);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute semantic search with embedder configuration passed via environment
|
||||
*/
|
||||
async function executeSemanticQuery(
|
||||
args: string[],
|
||||
embedderConfig: EmbedderConfig,
|
||||
timeout: number = 30000 // Longer timeout for embedding operations
|
||||
): Promise<QueryResult> {
|
||||
const pythonCmd = findPythonCommand();
|
||||
if (!pythonCmd) {
|
||||
return { success: false, error: 'Python not found' };
|
||||
}
|
||||
|
||||
const scriptPath = getQueryScriptPath();
|
||||
if (!scriptPath) {
|
||||
return { success: false, error: 'query_memory.py script not found' };
|
||||
}
|
||||
|
||||
const [pythonExe, baseArgs] = parsePythonCommand(pythonCmd);
|
||||
|
||||
// Build environment with embedder configuration
|
||||
const env: Record<string, string | undefined> = { ...process.env };
|
||||
|
||||
// Set the embedder provider
|
||||
env.GRAPHITI_EMBEDDER_PROVIDER = embedderConfig.provider;
|
||||
|
||||
// Provider-specific configuration
|
||||
switch (embedderConfig.provider) {
|
||||
case 'openai':
|
||||
if (embedderConfig.openaiApiKey) {
|
||||
env.OPENAI_API_KEY = embedderConfig.openaiApiKey;
|
||||
}
|
||||
if (embedderConfig.openaiEmbeddingModel) {
|
||||
env.OPENAI_EMBEDDING_MODEL = embedderConfig.openaiEmbeddingModel;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'google':
|
||||
if (embedderConfig.googleApiKey) {
|
||||
env.GOOGLE_API_KEY = embedderConfig.googleApiKey;
|
||||
}
|
||||
if (embedderConfig.googleEmbeddingModel) {
|
||||
env.GOOGLE_EMBEDDING_MODEL = embedderConfig.googleEmbeddingModel;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'ollama':
|
||||
if (embedderConfig.ollamaBaseUrl) {
|
||||
env.OLLAMA_BASE_URL = embedderConfig.ollamaBaseUrl;
|
||||
}
|
||||
if (embedderConfig.ollamaEmbeddingModel) {
|
||||
env.OLLAMA_EMBEDDING_MODEL = embedderConfig.ollamaEmbeddingModel;
|
||||
}
|
||||
if (embedderConfig.ollamaEmbeddingDim) {
|
||||
env.OLLAMA_EMBEDDING_DIM = String(embedderConfig.ollamaEmbeddingDim);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'voyage':
|
||||
if (embedderConfig.voyageApiKey) {
|
||||
env.VOYAGE_API_KEY = embedderConfig.voyageApiKey;
|
||||
}
|
||||
if (embedderConfig.voyageEmbeddingModel) {
|
||||
env.VOYAGE_EMBEDDING_MODEL = embedderConfig.voyageEmbeddingModel;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'azure_openai':
|
||||
if (embedderConfig.azureOpenaiApiKey) {
|
||||
env.AZURE_OPENAI_API_KEY = embedderConfig.azureOpenaiApiKey;
|
||||
}
|
||||
if (embedderConfig.azureOpenaiBaseUrl) {
|
||||
env.AZURE_OPENAI_BASE_URL = embedderConfig.azureOpenaiBaseUrl;
|
||||
}
|
||||
if (embedderConfig.azureOpenaiEmbeddingDeployment) {
|
||||
env.AZURE_OPENAI_EMBEDDING_DEPLOYMENT = embedderConfig.azureOpenaiEmbeddingDeployment;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const fullArgs = [...baseArgs, scriptPath, 'semantic-search', ...args];
|
||||
const proc = spawn(pythonExe, fullArgs, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env,
|
||||
timeout,
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
|
||||
proc.stdout.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
proc.stderr.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
proc.on('close', (code) => {
|
||||
if (code === 0 && stdout) {
|
||||
try {
|
||||
const result = JSON.parse(stdout);
|
||||
resolve(result);
|
||||
} catch {
|
||||
resolve({ success: false, error: `Invalid JSON response: ${stdout}` });
|
||||
}
|
||||
} else {
|
||||
resolve({
|
||||
success: false,
|
||||
error: stderr || `Process exited with code ${code}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
proc.on('error', (err) => {
|
||||
resolve({ success: false, error: err.message });
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
proc.kill();
|
||||
resolve({ success: false, error: 'Semantic search timed out' });
|
||||
}, timeout);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Memory Service for querying graph memories from LadybugDB
|
||||
*/
|
||||
export class MemoryService {
|
||||
private config: MemoryServiceConfig;
|
||||
|
||||
constructor(config: MemoryServiceConfig) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the full path to the database
|
||||
*/
|
||||
private getDbFullPath(): string {
|
||||
return path.join(this.config.dbPath, this.config.database);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the database exists
|
||||
*/
|
||||
databaseExists(): boolean {
|
||||
const dbPath = this.getDbFullPath();
|
||||
return fs.existsSync(dbPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* List all available databases
|
||||
*/
|
||||
listDatabases(): string[] {
|
||||
try {
|
||||
const basePath = this.config.dbPath;
|
||||
if (!fs.existsSync(basePath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return fs.readdirSync(basePath).filter((name) => {
|
||||
if (name.startsWith('.')) return false;
|
||||
return true; // Include both files and directories
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to list databases:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Query episodic memories from the database
|
||||
*/
|
||||
async getEpisodicMemories(limit: number = 20): Promise<MemoryEpisode[]> {
|
||||
const result = await executeQuery('get-memories', [
|
||||
this.config.dbPath,
|
||||
this.config.database,
|
||||
'--limit',
|
||||
String(limit),
|
||||
]);
|
||||
|
||||
if (!result.success || !result.data) {
|
||||
console.error('Failed to get memories:', result.error);
|
||||
return [];
|
||||
}
|
||||
|
||||
const data = result.data as MemoryQueryResult;
|
||||
return data.memories.map((m) => ({
|
||||
id: m.id,
|
||||
type: this.mapMemoryType(m.type),
|
||||
timestamp: m.timestamp,
|
||||
content: m.content,
|
||||
session_number: m.session_number,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Query entity memories (patterns, gotchas, etc.) from the database
|
||||
*/
|
||||
async getEntityMemories(limit: number = 20): Promise<MemoryEpisode[]> {
|
||||
const result = await executeQuery('get-entities', [
|
||||
this.config.dbPath,
|
||||
this.config.database,
|
||||
'--limit',
|
||||
String(limit),
|
||||
]);
|
||||
|
||||
if (!result.success || !result.data) {
|
||||
console.error('Failed to get entities:', result.error);
|
||||
return [];
|
||||
}
|
||||
|
||||
const data = result.data as { entities: MemoryQueryResult['memories']; count: number };
|
||||
return data.entities.map((e) => ({
|
||||
id: e.id,
|
||||
type: this.mapMemoryType(e.type),
|
||||
timestamp: e.timestamp,
|
||||
content: e.content,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all memories from the database
|
||||
*/
|
||||
async getAllMemories(limit: number = 20): Promise<MemoryEpisode[]> {
|
||||
const [episodic, entities] = await Promise.all([
|
||||
this.getEpisodicMemories(limit),
|
||||
this.getEntityMemories(limit),
|
||||
]);
|
||||
|
||||
const memories = [...episodic, ...entities];
|
||||
|
||||
// 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 in the database (keyword search)
|
||||
*/
|
||||
async searchMemories(searchQuery: string, limit: number = 20): Promise<MemoryEpisode[]> {
|
||||
const result = await executeQuery('search', [
|
||||
this.config.dbPath,
|
||||
this.config.database,
|
||||
searchQuery,
|
||||
'--limit',
|
||||
String(limit),
|
||||
]);
|
||||
|
||||
if (!result.success || !result.data) {
|
||||
console.error('Failed to search memories:', result.error);
|
||||
return [];
|
||||
}
|
||||
|
||||
const data = result.data as MemoryQueryResult;
|
||||
return data.memories.map((m) => ({
|
||||
id: m.id,
|
||||
type: this.mapMemoryType(m.type),
|
||||
timestamp: m.timestamp,
|
||||
content: m.content,
|
||||
session_number: m.session_number,
|
||||
score: m.score,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Semantic search using embeddings
|
||||
*
|
||||
* Uses the configured embedder to create vector embeddings and perform
|
||||
* similarity search. Falls back to keyword search if embedder fails.
|
||||
*
|
||||
* @param searchQuery The search query
|
||||
* @param embedderConfig Configuration for the embedding provider
|
||||
* @param limit Maximum number of results
|
||||
* @returns Memories with relevance scores
|
||||
*/
|
||||
async searchMemoriesSemantic(
|
||||
searchQuery: string,
|
||||
embedderConfig: EmbedderConfig,
|
||||
limit: number = 20
|
||||
): Promise<{ memories: MemoryEpisode[]; searchType: 'semantic' | 'keyword' }> {
|
||||
const result = await executeSemanticQuery(
|
||||
[this.config.dbPath, this.config.database, searchQuery, '--limit', String(limit)],
|
||||
embedderConfig
|
||||
);
|
||||
|
||||
if (!result.success || !result.data) {
|
||||
console.error('Semantic search failed, falling back to keyword:', result.error);
|
||||
// Fall back to keyword search
|
||||
const memories = await this.searchMemories(searchQuery, limit);
|
||||
return { memories, searchType: 'keyword' };
|
||||
}
|
||||
|
||||
const data = result.data as SemanticSearchResult;
|
||||
const memories = data.memories.map((m) => ({
|
||||
id: m.id,
|
||||
type: this.mapMemoryType(m.type),
|
||||
timestamp: m.timestamp,
|
||||
content: m.content,
|
||||
session_number: m.session_number,
|
||||
score: m.score,
|
||||
}));
|
||||
|
||||
return {
|
||||
memories,
|
||||
searchType: data.search_type || 'semantic',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Test connection to the database
|
||||
*/
|
||||
async testConnection(): Promise<{ success: boolean; message: string }> {
|
||||
const result = await executeQuery('get-status', [this.config.dbPath, this.config.database]);
|
||||
|
||||
if (!result.success) {
|
||||
return {
|
||||
success: false,
|
||||
message: result.error || 'Failed to check database status',
|
||||
};
|
||||
}
|
||||
|
||||
const data = result.data as StatusResult;
|
||||
|
||||
if (!data.available) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'LadybugDB (real_ladybug) not installed. Requires Python 3.12+',
|
||||
};
|
||||
}
|
||||
|
||||
if (!data.databaseExists) {
|
||||
return {
|
||||
success: false,
|
||||
message: `Database not found at ${data.databasePath}/${data.database}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (!data.connected) {
|
||||
return {
|
||||
success: false,
|
||||
message: data.error || 'Failed to connect to database',
|
||||
};
|
||||
}
|
||||
|
||||
const dbCount = data.databases?.length || 0;
|
||||
return {
|
||||
success: true,
|
||||
message: `Connected to LadybugDB with ${dbCount} databases`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the database connection (no-op for subprocess model)
|
||||
*/
|
||||
async close(): Promise<void> {
|
||||
// No persistent connection to close with subprocess model
|
||||
}
|
||||
|
||||
/**
|
||||
* Map string type to MemoryEpisode type
|
||||
*/
|
||||
private mapMemoryType(type: string): MemoryEpisode['type'] {
|
||||
switch (type) {
|
||||
case 'session_insight':
|
||||
return 'session_insight';
|
||||
case 'pattern':
|
||||
return 'pattern';
|
||||
case 'gotcha':
|
||||
return 'gotcha';
|
||||
case 'codebase_discovery':
|
||||
return 'codebase_discovery';
|
||||
case 'task_outcome':
|
||||
return 'task_outcome';
|
||||
default:
|
||||
return 'session_insight';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Singleton instance for reuse
|
||||
let serviceInstance: MemoryService | null = null;
|
||||
|
||||
/**
|
||||
* Get or create a Memory service instance
|
||||
*/
|
||||
export function getMemoryService(config: MemoryServiceConfig): MemoryService {
|
||||
if (
|
||||
!serviceInstance ||
|
||||
serviceInstance['config'].dbPath !== config.dbPath ||
|
||||
serviceInstance['config'].database !== config.database
|
||||
) {
|
||||
serviceInstance = new MemoryService(config);
|
||||
}
|
||||
return serviceInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the singleton service instance
|
||||
*/
|
||||
export async function closeMemoryService(): Promise<void> {
|
||||
if (serviceInstance) {
|
||||
await serviceInstance.close();
|
||||
serviceInstance = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if Python with LadybugDB is available
|
||||
*/
|
||||
export function isKuzuAvailable(): boolean {
|
||||
// Check if Python is available
|
||||
const pythonCmd = findPythonCommand();
|
||||
if (!pythonCmd) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if query script exists
|
||||
const scriptPath = getQueryScriptPath();
|
||||
return scriptPath !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get memory service status
|
||||
*/
|
||||
export interface MemoryServiceStatus {
|
||||
kuzuInstalled: boolean;
|
||||
databasePath: string;
|
||||
databaseExists: boolean;
|
||||
databases: string[];
|
||||
}
|
||||
|
||||
export function getMemoryServiceStatus(dbPath?: string): MemoryServiceStatus {
|
||||
const basePath = dbPath || getDefaultDbPath();
|
||||
|
||||
const databases = fs.existsSync(basePath)
|
||||
? fs.readdirSync(basePath).filter((name) => !name.startsWith('.'))
|
||||
: [];
|
||||
|
||||
// Check if Python and script are available
|
||||
const pythonAvailable = findPythonCommand() !== null;
|
||||
const scriptAvailable = getQueryScriptPath() !== null;
|
||||
|
||||
return {
|
||||
kuzuInstalled: pythonAvailable && scriptAvailable,
|
||||
databasePath: basePath,
|
||||
databaseExists: databases.length > 0,
|
||||
databases,
|
||||
};
|
||||
}
|
||||
@@ -66,7 +66,7 @@ class NotificationService {
|
||||
private sendNotification(type: NotificationType, options: NotificationOptions): void {
|
||||
// Get notification settings
|
||||
const settings = this.getNotificationSettings(options.projectId);
|
||||
|
||||
|
||||
// Check if this notification type is enabled
|
||||
if (!this.isNotificationEnabled(type, settings)) {
|
||||
return;
|
||||
@@ -162,4 +162,3 @@ class NotificationService {
|
||||
|
||||
// Export singleton instance
|
||||
export const notificationService = new NotificationService();
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ import path from 'path';
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
/**
|
||||
* Debug logging - only logs when AUTO_CLAUDE_DEBUG env var is set
|
||||
* Debug logging - only logs when DEBUG=true or in development mode
|
||||
*/
|
||||
const DEBUG = process.env.AUTO_CLAUDE_DEBUG === 'true' || process.env.AUTO_CLAUDE_DEBUG === '1';
|
||||
const DEBUG = process.env.DEBUG === 'true' || process.env.NODE_ENV === 'development';
|
||||
|
||||
function debug(message: string, data?: Record<string, unknown>): void {
|
||||
if (DEBUG) {
|
||||
|
||||
@@ -6,9 +6,16 @@ import type { Project, ProjectSettings, Task, TaskStatus, TaskMetadata, Implemen
|
||||
import { DEFAULT_PROJECT_SETTINGS, AUTO_BUILD_PATHS, getSpecsDir } from '../shared/constants';
|
||||
import { getAutoBuildPath, isInitialized } from './project-initializer';
|
||||
|
||||
interface TabState {
|
||||
openProjectIds: string[];
|
||||
activeProjectId: string | null;
|
||||
tabOrder: string[];
|
||||
}
|
||||
|
||||
interface StoreData {
|
||||
projects: Project[];
|
||||
settings: Record<string, unknown>;
|
||||
tabState?: TabState;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -68,6 +75,14 @@ export class ProjectStore {
|
||||
// Check if project already exists
|
||||
const existing = this.data.projects.find((p) => p.path === projectPath);
|
||||
if (existing) {
|
||||
// Validate that .auto-claude folder still exists for existing project
|
||||
// If manually deleted, reset autoBuildPath so UI prompts for reinitialization
|
||||
if (existing.autoBuildPath && !isInitialized(existing.path)) {
|
||||
console.warn(`[ProjectStore] .auto-claude folder was deleted for project "${existing.name}" - resetting autoBuildPath`);
|
||||
existing.autoBuildPath = '';
|
||||
existing.updatedAt = new Date();
|
||||
this.save();
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
|
||||
@@ -126,6 +141,34 @@ export class ProjectStore {
|
||||
return this.data.projects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get tab state
|
||||
*/
|
||||
getTabState(): TabState {
|
||||
return this.data.tabState || {
|
||||
openProjectIds: [],
|
||||
activeProjectId: null,
|
||||
tabOrder: []
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Save tab state
|
||||
*/
|
||||
saveTabState(tabState: TabState): void {
|
||||
// Filter out any project IDs that no longer exist
|
||||
const validProjectIds = this.data.projects.map(p => p.id);
|
||||
this.data.tabState = {
|
||||
openProjectIds: tabState.openProjectIds.filter(id => validProjectIds.includes(id)),
|
||||
activeProjectId: tabState.activeProjectId && validProjectIds.includes(tabState.activeProjectId)
|
||||
? tabState.activeProjectId
|
||||
: null,
|
||||
tabOrder: tabState.tabOrder.filter(id => validProjectIds.includes(id))
|
||||
};
|
||||
console.log('[ProjectStore] Saving tab state:', this.data.tabState);
|
||||
this.save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate all projects to ensure their .auto-claude folders still exist.
|
||||
* If a project has autoBuildPath set but the folder was deleted,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { spawn, execSync } from 'child_process';
|
||||
import { existsSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { EventEmitter } from 'events';
|
||||
import { app } from 'electron';
|
||||
|
||||
export interface PythonEnvStatus {
|
||||
ready: boolean;
|
||||
@@ -14,6 +15,9 @@ export interface PythonEnvStatus {
|
||||
/**
|
||||
* Manages the Python virtual environment for the auto-claude backend.
|
||||
* Automatically creates venv and installs dependencies if needed.
|
||||
*
|
||||
* On packaged apps (especially Linux AppImages), the bundled source is read-only,
|
||||
* so we create the venv in userData instead of inside the source directory.
|
||||
*/
|
||||
export class PythonEnvManager extends EventEmitter {
|
||||
private autoBuildSourcePath: string | null = null;
|
||||
@@ -21,16 +25,35 @@ export class PythonEnvManager extends EventEmitter {
|
||||
private isInitializing = false;
|
||||
private isReady = false;
|
||||
|
||||
/**
|
||||
* Get the path where the venv should be created.
|
||||
* For packaged apps, this is in userData to avoid read-only filesystem issues.
|
||||
* For development, this is inside the source directory.
|
||||
*/
|
||||
private getVenvBasePath(): string | null {
|
||||
if (!this.autoBuildSourcePath) return null;
|
||||
|
||||
// For packaged apps, put venv in userData (writable location)
|
||||
// This fixes Linux AppImage where resources are read-only
|
||||
if (app.isPackaged) {
|
||||
return path.join(app.getPath('userData'), 'python-venv');
|
||||
}
|
||||
|
||||
// Development mode - use source directory
|
||||
return path.join(this.autoBuildSourcePath, '.venv');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to the venv Python executable
|
||||
*/
|
||||
private getVenvPythonPath(): string | null {
|
||||
if (!this.autoBuildSourcePath) return null;
|
||||
const venvPath = this.getVenvBasePath();
|
||||
if (!venvPath) return null;
|
||||
|
||||
const venvPython =
|
||||
process.platform === 'win32'
|
||||
? path.join(this.autoBuildSourcePath, '.venv', 'Scripts', 'python.exe')
|
||||
: path.join(this.autoBuildSourcePath, '.venv', 'bin', 'python');
|
||||
? path.join(venvPath, 'Scripts', 'python.exe')
|
||||
: path.join(venvPath, 'bin', 'python');
|
||||
|
||||
return venvPython;
|
||||
}
|
||||
@@ -142,10 +165,10 @@ export class PythonEnvManager extends EventEmitter {
|
||||
}
|
||||
|
||||
this.emit('status', 'Creating Python virtual environment...');
|
||||
console.warn('[PythonEnvManager] Creating venv with:', systemPython);
|
||||
const venvPath = this.getVenvBasePath()!;
|
||||
console.warn('[PythonEnvManager] Creating venv at:', venvPath, 'with:', systemPython);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const venvPath = path.join(this.autoBuildSourcePath!, '.venv');
|
||||
const proc = spawn(systemPython, ['-m', 'venv', venvPath], {
|
||||
cwd: this.autoBuildSourcePath!,
|
||||
stdio: 'pipe'
|
||||
|
||||
@@ -4,12 +4,13 @@ import { spawn } from 'child_process';
|
||||
import { app } from 'electron';
|
||||
import { EventEmitter } from 'events';
|
||||
import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from './rate-limit-detector';
|
||||
import { findPythonCommand, parsePythonCommand } from './python-detector';
|
||||
import { parsePythonCommand } from './python-detector';
|
||||
import { pythonEnvManager } from './python-env-manager';
|
||||
|
||||
/**
|
||||
* Debug logging - only logs when AUTO_CLAUDE_DEBUG env var is set
|
||||
* Debug logging - only logs when DEBUG=true or in development mode
|
||||
*/
|
||||
const DEBUG = process.env.AUTO_CLAUDE_DEBUG === 'true' || process.env.AUTO_CLAUDE_DEBUG === '1';
|
||||
const DEBUG = process.env.DEBUG === 'true' || process.env.NODE_ENV === 'development';
|
||||
|
||||
function debug(...args: unknown[]): void {
|
||||
if (DEBUG) {
|
||||
@@ -21,8 +22,6 @@ function debug(...args: unknown[]): void {
|
||||
* Service for generating terminal names from commands using Claude AI
|
||||
*/
|
||||
export class TerminalNameGenerator extends EventEmitter {
|
||||
// Auto-detect Python command on initialization
|
||||
private pythonPath: string = findPythonCommand() || 'python';
|
||||
private autoBuildSourcePath: string = '';
|
||||
|
||||
constructor() {
|
||||
@@ -31,12 +30,9 @@ export class TerminalNameGenerator extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure paths for Python and auto-claude source
|
||||
* Configure the auto-claude source path
|
||||
*/
|
||||
configure(pythonPath?: string, autoBuildSourcePath?: string): void {
|
||||
if (pythonPath) {
|
||||
this.pythonPath = pythonPath;
|
||||
}
|
||||
configure(autoBuildSourcePath?: string): void {
|
||||
if (autoBuildSourcePath) {
|
||||
this.autoBuildSourcePath = autoBuildSourcePath;
|
||||
}
|
||||
@@ -118,6 +114,23 @@ export class TerminalNameGenerator extends EventEmitter {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if Python environment is ready (has claude_agent_sdk installed)
|
||||
if (!pythonEnvManager.isEnvReady()) {
|
||||
debug('Python environment not ready, initializing...');
|
||||
const status = await pythonEnvManager.initialize(autoBuildSource);
|
||||
if (!status.ready) {
|
||||
debug('Python environment initialization failed:', status.error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Get the venv Python path (where claude_agent_sdk is installed)
|
||||
const venvPythonPath = pythonEnvManager.getPythonPath();
|
||||
if (!venvPythonPath) {
|
||||
debug('Venv Python path not available');
|
||||
return null;
|
||||
}
|
||||
|
||||
const prompt = this.createNamePrompt(command, cwd);
|
||||
const script = this.createGenerationScript(prompt);
|
||||
|
||||
@@ -132,8 +145,8 @@ export class TerminalNameGenerator extends EventEmitter {
|
||||
const profileEnv = getProfileEnv();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
// Parse Python command to handle space-separated commands like "py -3"
|
||||
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(this.pythonPath);
|
||||
// Use the venv Python where claude_agent_sdk is installed
|
||||
const [pythonCommand, pythonBaseArgs] = parsePythonCommand(venvPythonPath);
|
||||
const childProcess = spawn(pythonCommand, [...pythonBaseArgs, '-c', script], {
|
||||
cwd: autoBuildSource,
|
||||
env: {
|
||||
|
||||
@@ -7,9 +7,9 @@ import { detectRateLimit, createSDKRateLimitInfo, getProfileEnv } from './rate-l
|
||||
import { findPythonCommand, parsePythonCommand } from './python-detector';
|
||||
|
||||
/**
|
||||
* Debug logging - only logs when AUTO_CLAUDE_DEBUG env var is set
|
||||
* Debug logging - only logs when DEBUG=true or in development mode
|
||||
*/
|
||||
const DEBUG = process.env.AUTO_CLAUDE_DEBUG === 'true' || process.env.AUTO_CLAUDE_DEBUG === '1';
|
||||
const DEBUG = process.env.DEBUG === 'true' || process.env.NODE_ENV === 'development';
|
||||
|
||||
function debug(...args: unknown[]): void {
|
||||
if (DEBUG) {
|
||||
|
||||
@@ -52,8 +52,9 @@ export async function downloadAndApplyUpdate(
|
||||
debugLog('[Update] Using cached release info');
|
||||
}
|
||||
|
||||
// Use the release tarball URL
|
||||
const tarballUrl = release.tarball_url;
|
||||
// Use explicit tag reference URL to avoid HTTP 300 when branch/tag names collide
|
||||
// See: https://github.com/AndyMik90/Auto-Claude/issues/78
|
||||
const tarballUrl = `https://api.github.com/repos/${GITHUB_CONFIG.owner}/${GITHUB_CONFIG.repo}/tarball/refs/tags/${release.tag_name}`;
|
||||
const releaseVersion = parseVersionFromTag(release.tag_name);
|
||||
debugLog('[Update] Release version:', releaseVersion);
|
||||
debugLog('[Update] Tarball URL:', tarballUrl);
|
||||
|
||||
@@ -48,6 +48,10 @@ export interface ChangelogAPI {
|
||||
imageData: string,
|
||||
filename: string
|
||||
) => Promise<IPCResult<{ relativePath: string; url: string }>>;
|
||||
readLocalImage: (
|
||||
projectPath: string,
|
||||
relativePath: string
|
||||
) => Promise<IPCResult<string>>;
|
||||
|
||||
// Event Listeners
|
||||
onChangelogGenerationProgress: (
|
||||
@@ -113,6 +117,12 @@ export const createChangelogAPI = (): ChangelogAPI => ({
|
||||
): Promise<IPCResult<{ relativePath: string; url: string }>> =>
|
||||
invokeIpc(IPC_CHANNELS.CHANGELOG_SAVE_IMAGE, projectId, imageData, filename),
|
||||
|
||||
readLocalImage: (
|
||||
projectPath: string,
|
||||
relativePath: string
|
||||
): Promise<IPCResult<string>> =>
|
||||
invokeIpc(IPC_CHANNELS.CHANGELOG_READ_LOCAL_IMAGE, projectPath, relativePath),
|
||||
|
||||
// Event Listeners
|
||||
onChangelogGenerationProgress: (
|
||||
callback: (projectId: string, progress: ChangelogGenerationProgress) => void
|
||||
|
||||
@@ -41,9 +41,18 @@ export interface GitHubAPI {
|
||||
getGitHubUser: () => Promise<IPCResult<{ username: string; name?: string }>>;
|
||||
listGitHubUserRepos: () => Promise<IPCResult<{ repos: Array<{ fullName: string; description: string | null; isPrivate: boolean }> }>>;
|
||||
|
||||
// Repository detection
|
||||
// Repository detection and management
|
||||
detectGitHubRepo: (projectPath: string) => Promise<IPCResult<string>>;
|
||||
getGitHubBranches: (repo: string, token: string) => Promise<IPCResult<string[]>>;
|
||||
createGitHubRepo: (
|
||||
repoName: string,
|
||||
options: { description?: string; isPrivate?: boolean; projectPath: string; owner?: string }
|
||||
) => Promise<IPCResult<{ fullName: string; url: string }>>;
|
||||
addGitRemote: (
|
||||
projectPath: string,
|
||||
repoFullName: string
|
||||
) => Promise<IPCResult<{ remoteUrl: string }>>;
|
||||
listGitHubOrgs: () => Promise<IPCResult<{ orgs: Array<{ login: string; avatarUrl?: string }> }>>;
|
||||
|
||||
// Event Listeners
|
||||
onGitHubInvestigationProgress: (
|
||||
@@ -113,13 +122,28 @@ export const createGitHubAPI = (): GitHubAPI => ({
|
||||
listGitHubUserRepos: (): Promise<IPCResult<{ repos: Array<{ fullName: string; description: string | null; isPrivate: boolean }> }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_LIST_USER_REPOS),
|
||||
|
||||
// Repository detection
|
||||
// Repository detection and management
|
||||
detectGitHubRepo: (projectPath: string): Promise<IPCResult<string>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_DETECT_REPO, projectPath),
|
||||
|
||||
getGitHubBranches: (repo: string, token: string): Promise<IPCResult<string[]>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_GET_BRANCHES, repo, token),
|
||||
|
||||
createGitHubRepo: (
|
||||
repoName: string,
|
||||
options: { description?: string; isPrivate?: boolean; projectPath: string; owner?: string }
|
||||
): Promise<IPCResult<{ fullName: string; url: string }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_CREATE_REPO, repoName, options),
|
||||
|
||||
addGitRemote: (
|
||||
projectPath: string,
|
||||
repoFullName: string
|
||||
): Promise<IPCResult<{ remoteUrl: string }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_ADD_REMOTE, projectPath, repoFullName),
|
||||
|
||||
listGitHubOrgs: (): Promise<IPCResult<{ orgs: Array<{ login: string; avatarUrl?: string }> }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_LIST_ORGS),
|
||||
|
||||
// Event Listeners
|
||||
onGitHubInvestigationProgress: (
|
||||
callback: (projectId: string, status: GitHubInvestigationStatus) => void
|
||||
|
||||
@@ -16,8 +16,8 @@ export interface RoadmapAPI {
|
||||
getRoadmap: (projectId: string) => Promise<IPCResult<Roadmap | null>>;
|
||||
getRoadmapStatus: (projectId: string) => Promise<IPCResult<{ isRunning: boolean }>>;
|
||||
saveRoadmap: (projectId: string, roadmap: Roadmap) => Promise<IPCResult>;
|
||||
generateRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean) => void;
|
||||
refreshRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean) => void;
|
||||
generateRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean, refreshCompetitorAnalysis?: boolean) => void;
|
||||
refreshRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean, refreshCompetitorAnalysis?: boolean) => void;
|
||||
stopRoadmap: (projectId: string) => Promise<IPCResult>;
|
||||
updateFeatureStatus: (
|
||||
projectId: string,
|
||||
@@ -58,11 +58,11 @@ export const createRoadmapAPI = (): RoadmapAPI => ({
|
||||
saveRoadmap: (projectId: string, roadmap: Roadmap): Promise<IPCResult> =>
|
||||
invokeIpc(IPC_CHANNELS.ROADMAP_SAVE, projectId, roadmap),
|
||||
|
||||
generateRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean): void =>
|
||||
sendIpc(IPC_CHANNELS.ROADMAP_GENERATE, projectId, enableCompetitorAnalysis),
|
||||
generateRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean, refreshCompetitorAnalysis?: boolean): void =>
|
||||
sendIpc(IPC_CHANNELS.ROADMAP_GENERATE, projectId, enableCompetitorAnalysis, refreshCompetitorAnalysis),
|
||||
|
||||
refreshRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean): void =>
|
||||
sendIpc(IPC_CHANNELS.ROADMAP_REFRESH, projectId, enableCompetitorAnalysis),
|
||||
refreshRoadmap: (projectId: string, enableCompetitorAnalysis?: boolean, refreshCompetitorAnalysis?: boolean): void =>
|
||||
sendIpc(IPC_CHANNELS.ROADMAP_REFRESH, projectId, enableCompetitorAnalysis, refreshCompetitorAnalysis),
|
||||
|
||||
stopRoadmap: (projectId: string): Promise<IPCResult> =>
|
||||
invokeIpc(IPC_CHANNELS.ROADMAP_STOP, projectId),
|
||||
|
||||
@@ -14,6 +14,13 @@ import type {
|
||||
GitStatus
|
||||
} from '../../shared/types';
|
||||
|
||||
// Tab state interface (persisted in main process)
|
||||
export interface TabState {
|
||||
openProjectIds: string[];
|
||||
activeProjectId: string | null;
|
||||
tabOrder: string[];
|
||||
}
|
||||
|
||||
export interface ProjectAPI {
|
||||
// Project Management
|
||||
addProject: (projectPath: string) => Promise<IPCResult<Project>>;
|
||||
@@ -27,6 +34,10 @@ export interface ProjectAPI {
|
||||
updateProjectAutoBuild: (projectId: string) => Promise<IPCResult<InitializationResult>>;
|
||||
checkProjectVersion: (projectId: string) => Promise<IPCResult<AutoBuildVersionInfo>>;
|
||||
|
||||
// Tab State (persisted in main process for reliability)
|
||||
getTabState: () => Promise<IPCResult<TabState>>;
|
||||
saveTabState: (tabState: TabState) => Promise<IPCResult>;
|
||||
|
||||
// Context Operations
|
||||
getProjectContext: (projectId: string) => Promise<IPCResult<unknown>>;
|
||||
refreshProjectIndex: (projectId: string) => Promise<IPCResult<unknown>>;
|
||||
@@ -49,20 +60,19 @@ export interface ProjectAPI {
|
||||
) => Promise<IPCResult<import('../../shared/types').CreateProjectFolderResult>>;
|
||||
getDefaultProjectLocation: () => Promise<string | null>;
|
||||
|
||||
// Docker & Infrastructure Operations (for Graphiti/FalkorDB)
|
||||
getInfrastructureStatus: (port?: number) => Promise<IPCResult<InfrastructureStatus>>;
|
||||
startFalkorDB: (port?: number) => Promise<IPCResult<{ success: boolean; error?: string }>>;
|
||||
stopFalkorDB: () => Promise<IPCResult<{ success: boolean; error?: string }>>;
|
||||
openDockerDesktop: () => Promise<IPCResult<{ success: boolean; error?: string }>>;
|
||||
getDockerDownloadUrl: () => Promise<string>;
|
||||
// Memory Infrastructure Operations (LadybugDB - no Docker required)
|
||||
getMemoryInfrastructureStatus: (dbPath?: string) => Promise<IPCResult<InfrastructureStatus>>;
|
||||
listMemoryDatabases: (dbPath?: string) => Promise<IPCResult<string[]>>;
|
||||
testMemoryConnection: (dbPath?: string, database?: string) => Promise<IPCResult<GraphitiValidationResult>>;
|
||||
|
||||
// Graphiti Validation Operations
|
||||
validateFalkorDBConnection: (uri: string) => Promise<IPCResult<GraphitiValidationResult>>;
|
||||
validateOpenAIApiKey: (apiKey: string) => Promise<IPCResult<GraphitiValidationResult>>;
|
||||
testGraphitiConnection: (
|
||||
falkorDbUri: string,
|
||||
openAiApiKey: string
|
||||
) => Promise<IPCResult<GraphitiConnectionTestResult>>;
|
||||
validateLLMApiKey: (provider: string, apiKey: string) => Promise<IPCResult<GraphitiValidationResult>>;
|
||||
testGraphitiConnection: (config: {
|
||||
dbPath?: string;
|
||||
database?: string;
|
||||
llmProvider: string;
|
||||
apiKey: string;
|
||||
}) => Promise<IPCResult<GraphitiConnectionTestResult>>;
|
||||
|
||||
// Git Operations
|
||||
getGitBranches: (projectPath: string) => Promise<IPCResult<string[]>>;
|
||||
@@ -70,6 +80,41 @@ export interface ProjectAPI {
|
||||
detectMainBranch: (projectPath: string) => Promise<IPCResult<string | null>>;
|
||||
checkGitStatus: (projectPath: string) => Promise<IPCResult<GitStatus>>;
|
||||
initializeGit: (projectPath: string) => Promise<IPCResult<InitializationResult>>;
|
||||
|
||||
// Ollama Model Detection
|
||||
checkOllamaStatus: (baseUrl?: string) => Promise<IPCResult<{
|
||||
running: boolean;
|
||||
url: string;
|
||||
version?: string;
|
||||
message?: string;
|
||||
}>>;
|
||||
listOllamaModels: (baseUrl?: string) => Promise<IPCResult<{
|
||||
models: Array<{
|
||||
name: string;
|
||||
size_bytes: number;
|
||||
size_gb: number;
|
||||
modified_at: string;
|
||||
is_embedding: boolean;
|
||||
embedding_dim?: number | null;
|
||||
description?: string;
|
||||
}>;
|
||||
count: number;
|
||||
}>>;
|
||||
listOllamaEmbeddingModels: (baseUrl?: string) => Promise<IPCResult<{
|
||||
embedding_models: Array<{
|
||||
name: string;
|
||||
embedding_dim: number | null;
|
||||
description: string;
|
||||
size_bytes: number;
|
||||
size_gb: number;
|
||||
}>;
|
||||
count: number;
|
||||
}>>;
|
||||
pullOllamaModel: (modelName: string, baseUrl?: string) => Promise<IPCResult<{
|
||||
model: string;
|
||||
status: 'completed' | 'failed';
|
||||
output: string[];
|
||||
}>>;
|
||||
}
|
||||
|
||||
export const createProjectAPI = (): ProjectAPI => ({
|
||||
@@ -98,6 +143,13 @@ export const createProjectAPI = (): ProjectAPI => ({
|
||||
checkProjectVersion: (projectId: string): Promise<IPCResult<AutoBuildVersionInfo>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.PROJECT_CHECK_VERSION, projectId),
|
||||
|
||||
// Tab State (persisted in main process for reliability)
|
||||
getTabState: (): Promise<IPCResult<TabState>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.TAB_STATE_GET),
|
||||
|
||||
saveTabState: (tabState: TabState): Promise<IPCResult> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.TAB_STATE_SAVE, tabState),
|
||||
|
||||
// Context Operations
|
||||
getProjectContext: (projectId: string) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.CONTEXT_GET, projectId),
|
||||
@@ -141,34 +193,27 @@ export const createProjectAPI = (): ProjectAPI => ({
|
||||
getDefaultProjectLocation: (): Promise<string | null> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.DIALOG_GET_DEFAULT_PROJECT_LOCATION),
|
||||
|
||||
// Docker & Infrastructure Operations
|
||||
getInfrastructureStatus: (port?: number): Promise<IPCResult<InfrastructureStatus>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.DOCKER_STATUS, port),
|
||||
// Memory Infrastructure Operations (LadybugDB - no Docker required)
|
||||
getMemoryInfrastructureStatus: (dbPath?: string): Promise<IPCResult<InfrastructureStatus>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.MEMORY_STATUS, dbPath),
|
||||
|
||||
startFalkorDB: (port?: number): Promise<IPCResult<{ success: boolean; error?: string }>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.DOCKER_START_FALKORDB, port),
|
||||
listMemoryDatabases: (dbPath?: string): Promise<IPCResult<string[]>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.MEMORY_LIST_DATABASES, dbPath),
|
||||
|
||||
stopFalkorDB: (): Promise<IPCResult<{ success: boolean; error?: string }>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.DOCKER_STOP_FALKORDB),
|
||||
|
||||
openDockerDesktop: (): Promise<IPCResult<{ success: boolean; error?: string }>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.DOCKER_OPEN_DESKTOP),
|
||||
|
||||
getDockerDownloadUrl: (): Promise<string> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.DOCKER_GET_DOWNLOAD_URL),
|
||||
testMemoryConnection: (dbPath?: string, database?: string): Promise<IPCResult<GraphitiValidationResult>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.MEMORY_TEST_CONNECTION, dbPath, database),
|
||||
|
||||
// Graphiti Validation Operations
|
||||
validateFalkorDBConnection: (uri: string): Promise<IPCResult<GraphitiValidationResult>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GRAPHITI_VALIDATE_FALKORDB, uri),
|
||||
validateLLMApiKey: (provider: string, apiKey: string): Promise<IPCResult<GraphitiValidationResult>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GRAPHITI_VALIDATE_LLM, provider, apiKey),
|
||||
|
||||
validateOpenAIApiKey: (apiKey: string): Promise<IPCResult<GraphitiValidationResult>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GRAPHITI_VALIDATE_OPENAI, apiKey),
|
||||
|
||||
testGraphitiConnection: (
|
||||
falkorDbUri: string,
|
||||
openAiApiKey: string
|
||||
): Promise<IPCResult<GraphitiConnectionTestResult>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GRAPHITI_TEST_CONNECTION, falkorDbUri, openAiApiKey),
|
||||
testGraphitiConnection: (config: {
|
||||
dbPath?: string;
|
||||
database?: string;
|
||||
llmProvider: string;
|
||||
apiKey: string;
|
||||
}): Promise<IPCResult<GraphitiConnectionTestResult>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GRAPHITI_TEST_CONNECTION, config),
|
||||
|
||||
// Git Operations
|
||||
getGitBranches: (projectPath: string): Promise<IPCResult<string[]>> =>
|
||||
@@ -184,5 +229,18 @@ export const createProjectAPI = (): ProjectAPI => ({
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_CHECK_STATUS, projectPath),
|
||||
|
||||
initializeGit: (projectPath: string): Promise<IPCResult<InitializationResult>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_INITIALIZE, projectPath)
|
||||
ipcRenderer.invoke(IPC_CHANNELS.GIT_INITIALIZE, projectPath),
|
||||
|
||||
// Ollama Model Detection
|
||||
checkOllamaStatus: (baseUrl?: string) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.OLLAMA_CHECK_STATUS, baseUrl),
|
||||
|
||||
listOllamaModels: (baseUrl?: string) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.OLLAMA_LIST_MODELS, baseUrl),
|
||||
|
||||
listOllamaEmbeddingModels: (baseUrl?: string) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.OLLAMA_LIST_EMBEDDING_MODELS, baseUrl),
|
||||
|
||||
pullOllamaModel: (modelName: string, baseUrl?: string) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.OLLAMA_PULL_MODEL, modelName, baseUrl)
|
||||
});
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Settings2, Download, RefreshCw, AlertCircle } from 'lucide-react';
|
||||
import {
|
||||
DndContext,
|
||||
DragOverlay,
|
||||
closestCenter,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type DragEndEvent
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
SortableContext,
|
||||
horizontalListSortingStrategy
|
||||
} from '@dnd-kit/sortable';
|
||||
import { TooltipProvider } from './components/ui/tooltip';
|
||||
import { Button } from './components/ui/button';
|
||||
import {
|
||||
@@ -44,6 +57,7 @@ import { useTerminalStore, restoreTerminalSessions } from './stores/terminal-sto
|
||||
import { useIpcListeners } from './hooks/useIpc';
|
||||
import { COLOR_THEMES } from '../shared/constants';
|
||||
import type { Task, Project, ColorTheme } from '../shared/types';
|
||||
import { ProjectTabBar } from './components/ProjectTabBar';
|
||||
|
||||
export function App() {
|
||||
// Load IPC listeners for real-time updates
|
||||
@@ -52,6 +66,13 @@ export function App() {
|
||||
// Stores
|
||||
const projects = useProjectStore((state) => state.projects);
|
||||
const selectedProjectId = useProjectStore((state) => state.selectedProjectId);
|
||||
const activeProjectId = useProjectStore((state) => state.activeProjectId);
|
||||
const getProjectTabs = useProjectStore((state) => state.getProjectTabs);
|
||||
const openProjectIds = useProjectStore((state) => state.openProjectIds);
|
||||
const openProjectTab = useProjectStore((state) => state.openProjectTab);
|
||||
const closeProjectTab = useProjectStore((state) => state.closeProjectTab);
|
||||
const setActiveProject = useProjectStore((state) => state.setActiveProject);
|
||||
const reorderTabs = useProjectStore((state) => state.reorderTabs);
|
||||
const tasks = useTaskStore((state) => state.tasks);
|
||||
const settings = useSettingsStore((state) => state.settings);
|
||||
const settingsLoading = useSettingsStore((state) => state.isLoading);
|
||||
@@ -77,8 +98,21 @@ export function App() {
|
||||
const [showGitHubSetup, setShowGitHubSetup] = useState(false);
|
||||
const [gitHubSetupProject, setGitHubSetupProject] = useState<Project | null>(null);
|
||||
|
||||
// Get selected project
|
||||
const selectedProject = projects.find((p) => p.id === selectedProjectId);
|
||||
// Setup drag sensors
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, {
|
||||
activationConstraint: {
|
||||
distance: 8, // 8px movement required before drag starts
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
// Track dragging state for overlay
|
||||
const [activeDragProject, setActiveDragProject] = useState<Project | null>(null);
|
||||
|
||||
// Get tabs and selected project
|
||||
const projectTabs = getProjectTabs();
|
||||
const selectedProject = projects.find((p) => p.id === (activeProjectId || selectedProjectId));
|
||||
|
||||
// Initial load
|
||||
useEffect(() => {
|
||||
@@ -86,6 +120,53 @@ export function App() {
|
||||
loadSettings();
|
||||
}, []);
|
||||
|
||||
// Restore tab state and open tabs for loaded projects
|
||||
useEffect(() => {
|
||||
console.log('[App] Tab restore useEffect triggered:', {
|
||||
projectsCount: projects.length,
|
||||
openProjectIds,
|
||||
activeProjectId,
|
||||
selectedProjectId,
|
||||
projectTabsCount: projectTabs.length,
|
||||
projectTabIds: projectTabs.map(p => p.id)
|
||||
});
|
||||
|
||||
if (projects.length > 0) {
|
||||
// Check openProjectIds (persisted state) instead of projectTabs (computed)
|
||||
// to avoid race condition where projectTabs is empty before projects load
|
||||
if (openProjectIds.length === 0) {
|
||||
// No tabs persisted at all, open the first available project
|
||||
const projectToOpen = activeProjectId || selectedProjectId || projects[0].id;
|
||||
console.log('[App] No tabs persisted, opening project:', projectToOpen);
|
||||
// Verify the project exists before opening
|
||||
if (projects.some(p => p.id === projectToOpen)) {
|
||||
openProjectTab(projectToOpen);
|
||||
setActiveProject(projectToOpen);
|
||||
} else {
|
||||
// Fallback to first project if stored IDs are invalid
|
||||
console.log('[App] Project not found, falling back to first project:', projects[0].id);
|
||||
openProjectTab(projects[0].id);
|
||||
setActiveProject(projects[0].id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
console.log('[App] Tabs already persisted, checking active project');
|
||||
// If there's an active project but no tabs open for it, open a tab
|
||||
if (activeProjectId && !projectTabs.some(tab => tab.id === activeProjectId)) {
|
||||
console.log('[App] Active project has no tab, opening:', activeProjectId);
|
||||
openProjectTab(activeProjectId);
|
||||
}
|
||||
// If there's a selected project but no active project, make it active
|
||||
else if (selectedProjectId && !activeProjectId) {
|
||||
console.log('[App] No active project, using selected:', selectedProjectId);
|
||||
setActiveProject(selectedProjectId);
|
||||
openProjectTab(selectedProjectId);
|
||||
} else {
|
||||
console.log('[App] Tab state is valid, no action needed');
|
||||
}
|
||||
}
|
||||
}, [projects, activeProjectId, selectedProjectId, openProjectIds, projectTabs, openProjectTab, setActiveProject]);
|
||||
|
||||
// Track if settings have been loaded at least once
|
||||
const [settingsHaveLoaded, setSettingsHaveLoaded] = useState(false);
|
||||
|
||||
@@ -135,11 +216,22 @@ export function App() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Reset init success flag when selected project changes
|
||||
// This allows the init dialog to show for new/different projects
|
||||
useEffect(() => {
|
||||
setInitSuccess(false);
|
||||
setInitError(null);
|
||||
}, [selectedProjectId]);
|
||||
|
||||
// Check if selected project needs initialization (e.g., .auto-claude folder was deleted)
|
||||
useEffect(() => {
|
||||
// Don't show dialog while initialization is in progress
|
||||
if (isInitializing) return;
|
||||
|
||||
// Don't reopen dialog after successful initialization
|
||||
// (project update with autoBuildPath may not have propagated yet)
|
||||
if (initSuccess) return;
|
||||
|
||||
if (selectedProject && !selectedProject.autoBuildPath && skippedInitProjectId !== selectedProject.id) {
|
||||
// Project exists but isn't initialized - show init dialog
|
||||
setPendingProject(selectedProject);
|
||||
@@ -147,12 +239,52 @@ export function App() {
|
||||
setInitSuccess(false); // Reset success flag
|
||||
setShowInitDialog(true);
|
||||
}
|
||||
}, [selectedProject, skippedInitProjectId, isInitializing]);
|
||||
}, [selectedProject, skippedInitProjectId, isInitializing, initSuccess]);
|
||||
|
||||
// Global keyboard shortcut: Cmd/Ctrl+T to add project (when not on terminals view)
|
||||
useEffect(() => {
|
||||
const handleKeyDown = async (e: KeyboardEvent) => {
|
||||
// Skip if in input fields
|
||||
if (
|
||||
e.target instanceof HTMLInputElement ||
|
||||
e.target instanceof HTMLTextAreaElement ||
|
||||
(e.target as HTMLElement)?.isContentEditable
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Cmd/Ctrl+T: Add new project (only when not on terminals view)
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 't' && activeView !== 'terminals') {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const path = await window.electronAPI.selectDirectory();
|
||||
if (path) {
|
||||
const project = await addProject(path);
|
||||
if (project) {
|
||||
openProjectTab(project.id);
|
||||
if (!project.autoBuildPath) {
|
||||
setPendingProject(project);
|
||||
setInitError(null);
|
||||
setInitSuccess(false);
|
||||
setShowInitDialog(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to add project:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [activeView, openProjectTab]);
|
||||
|
||||
// Load tasks when project changes
|
||||
useEffect(() => {
|
||||
if (selectedProjectId) {
|
||||
loadTasks(selectedProjectId);
|
||||
const currentProjectId = activeProjectId || selectedProjectId;
|
||||
if (currentProjectId) {
|
||||
loadTasks(currentProjectId);
|
||||
setSelectedTask(null); // Clear selection on project change
|
||||
} else {
|
||||
useTaskStore.getState().clearTasks();
|
||||
@@ -173,7 +305,7 @@ export function App() {
|
||||
console.error('[App] Failed to restore sessions:', err);
|
||||
});
|
||||
}
|
||||
}, [selectedProjectId, selectedProject?.path, selectedProject?.name]);
|
||||
}, [activeProjectId, selectedProjectId, selectedProject?.path, selectedProject?.name]);
|
||||
|
||||
// Apply theme on load
|
||||
useEffect(() => {
|
||||
@@ -250,12 +382,17 @@ export function App() {
|
||||
const path = await window.electronAPI.selectDirectory();
|
||||
if (path) {
|
||||
const project = await addProject(path);
|
||||
if (project && !project.autoBuildPath) {
|
||||
// Project doesn't have Auto Claude initialized, show init dialog
|
||||
setPendingProject(project);
|
||||
setInitError(null); // Clear any previous errors
|
||||
setInitSuccess(false); // Reset success flag
|
||||
setShowInitDialog(true);
|
||||
if (project) {
|
||||
// Open a tab for the new project
|
||||
openProjectTab(project.id);
|
||||
|
||||
if (!project.autoBuildPath) {
|
||||
// Project doesn't have Auto Claude initialized, show init dialog
|
||||
setPendingProject(project);
|
||||
setInitError(null); // Clear any previous errors
|
||||
setInitSuccess(false); // Reset success flag
|
||||
setShowInitDialog(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -263,6 +400,38 @@ export function App() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleProjectTabSelect = (projectId: string) => {
|
||||
setActiveProject(projectId);
|
||||
};
|
||||
|
||||
const handleProjectTabClose = (projectId: string) => {
|
||||
closeProjectTab(projectId);
|
||||
};
|
||||
|
||||
// Handle drag start - set the active dragged project
|
||||
const handleDragStart = (event: any) => {
|
||||
const { active } = event;
|
||||
const draggedProject = projectTabs.find(p => p.id === active.id);
|
||||
if (draggedProject) {
|
||||
setActiveDragProject(draggedProject);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle drag end - reorder tabs if dropped over another tab
|
||||
const handleDragEnd = (event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
setActiveDragProject(null);
|
||||
|
||||
if (!over) return;
|
||||
|
||||
const oldIndex = projectTabs.findIndex(p => p.id === active.id);
|
||||
const newIndex = projectTabs.findIndex(p => p.id === over.id);
|
||||
|
||||
if (oldIndex !== newIndex && oldIndex !== -1 && newIndex !== -1) {
|
||||
reorderTabs(oldIndex, newIndex);
|
||||
}
|
||||
};
|
||||
|
||||
const handleInitialize = async () => {
|
||||
if (!pendingProject) return;
|
||||
|
||||
@@ -386,6 +555,38 @@ export function App() {
|
||||
|
||||
{/* Main content */}
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
{/* Project Tabs */}
|
||||
{projectTabs.length > 0 && (
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragStart={handleDragStart}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<SortableContext items={projectTabs.map(p => p.id)} strategy={horizontalListSortingStrategy}>
|
||||
<ProjectTabBar
|
||||
projects={projectTabs}
|
||||
activeProjectId={activeProjectId}
|
||||
onProjectSelect={handleProjectTabSelect}
|
||||
onProjectClose={handleProjectTabClose}
|
||||
onAddProject={handleAddProject}
|
||||
/>
|
||||
</SortableContext>
|
||||
|
||||
{/* Drag overlay - shows what's being dragged */}
|
||||
<DragOverlay>
|
||||
{activeDragProject && (
|
||||
<div className="flex items-center gap-2 bg-card border border-border rounded-md px-4 py-2.5 shadow-lg max-w-[200px]">
|
||||
<div className="w-1 h-4 bg-muted-foreground rounded-full" />
|
||||
<span className="truncate font-medium text-sm">
|
||||
{activeDragProject.name}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</DragOverlay>
|
||||
</DndContext>
|
||||
)}
|
||||
|
||||
{/* Header */}
|
||||
<header className="electron-drag flex h-14 items-center justify-between border-b border-border bg-card/50 backdrop-blur-sm px-6">
|
||||
<div className="electron-no-drag">
|
||||
@@ -432,21 +633,22 @@ export function App() {
|
||||
<TerminalGrid
|
||||
projectPath={selectedProject?.path}
|
||||
onNewTaskClick={() => setIsNewTaskDialogOpen(true)}
|
||||
isActive={activeView === 'terminals'}
|
||||
/>
|
||||
</div>
|
||||
{activeView === 'roadmap' && selectedProjectId && (
|
||||
<Roadmap projectId={selectedProjectId} onGoToTask={handleGoToTask} />
|
||||
{activeView === 'roadmap' && (activeProjectId || selectedProjectId) && (
|
||||
<Roadmap projectId={activeProjectId || selectedProjectId!} onGoToTask={handleGoToTask} />
|
||||
)}
|
||||
{activeView === 'context' && selectedProjectId && (
|
||||
<Context projectId={selectedProjectId} />
|
||||
{activeView === 'context' && (activeProjectId || selectedProjectId) && (
|
||||
<Context projectId={activeProjectId || selectedProjectId!} />
|
||||
)}
|
||||
{activeView === 'ideation' && selectedProjectId && (
|
||||
<Ideation projectId={selectedProjectId} onGoToTask={handleGoToTask} />
|
||||
{activeView === 'ideation' && (activeProjectId || selectedProjectId) && (
|
||||
<Ideation projectId={activeProjectId || selectedProjectId!} onGoToTask={handleGoToTask} />
|
||||
)}
|
||||
{activeView === 'insights' && selectedProjectId && (
|
||||
<Insights projectId={selectedProjectId} />
|
||||
{activeView === 'insights' && (activeProjectId || selectedProjectId) && (
|
||||
<Insights projectId={activeProjectId || selectedProjectId!} />
|
||||
)}
|
||||
{activeView === 'github-issues' && selectedProjectId && (
|
||||
{activeView === 'github-issues' && (activeProjectId || selectedProjectId) && (
|
||||
<GitHubIssues
|
||||
onOpenSettings={() => {
|
||||
setSettingsInitialProjectSection('github');
|
||||
@@ -455,11 +657,11 @@ export function App() {
|
||||
onNavigateToTask={handleGoToTask}
|
||||
/>
|
||||
)}
|
||||
{activeView === 'changelog' && selectedProjectId && (
|
||||
{activeView === 'changelog' && (activeProjectId || selectedProjectId) && (
|
||||
<Changelog />
|
||||
)}
|
||||
{activeView === 'worktrees' && selectedProjectId && (
|
||||
<Worktrees projectId={selectedProjectId} />
|
||||
{activeView === 'worktrees' && (activeProjectId || selectedProjectId) && (
|
||||
<Worktrees projectId={activeProjectId || selectedProjectId!} />
|
||||
)}
|
||||
{activeView === 'agent-tools' && (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
@@ -477,7 +679,9 @@ export function App() {
|
||||
projects={projects}
|
||||
onNewProject={handleAddProject}
|
||||
onOpenProject={handleAddProject}
|
||||
onSelectProject={(projectId) => useProjectStore.getState().selectProject(projectId)}
|
||||
onSelectProject={(projectId) => {
|
||||
openProjectTab(projectId);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</main>
|
||||
@@ -491,9 +695,9 @@ export function App() {
|
||||
/>
|
||||
|
||||
{/* Dialogs */}
|
||||
{selectedProjectId && (
|
||||
{(activeProjectId || selectedProjectId) && (
|
||||
<TaskCreationWizard
|
||||
projectId={selectedProjectId}
|
||||
projectId={activeProjectId || selectedProjectId!}
|
||||
open={isNewTaskDialogOpen}
|
||||
onOpenChange={setIsNewTaskDialogOpen}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,478 @@
|
||||
/**
|
||||
* Unit tests for Project Store Tab Management
|
||||
* Tests Zustand store for project tab state management
|
||||
*
|
||||
* Note: Tab state persistence is now handled via IPC (saveTabState/getTabState)
|
||||
* rather than localStorage. The saveTabState calls are debounced, so we don't
|
||||
* assert on them directly in these unit tests.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { useProjectStore } from '../stores/project-store';
|
||||
import type { Project, ProjectSettings } from '../../shared/types';
|
||||
|
||||
// Helper to create test projects
|
||||
function createTestProject(overrides: Partial<Project> = {}): Project {
|
||||
const defaultSettings: ProjectSettings = {
|
||||
model: 'claude-3-opus',
|
||||
memoryBackend: 'graphiti',
|
||||
linearSync: false,
|
||||
notifications: {
|
||||
onTaskComplete: true,
|
||||
onTaskFailed: true,
|
||||
onReviewNeeded: true,
|
||||
sound: false
|
||||
},
|
||||
graphitiMcpEnabled: false
|
||||
};
|
||||
|
||||
return {
|
||||
id: `project-${Date.now()}-${Math.random().toString(36).substring(7)}`,
|
||||
name: 'Test Project',
|
||||
path: '/path/to/test-project',
|
||||
autoBuildPath: '.auto-claude',
|
||||
settings: defaultSettings,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
describe('Project Store Tab Management', () => {
|
||||
beforeEach(() => {
|
||||
// Reset store to initial state before each test
|
||||
useProjectStore.setState({
|
||||
projects: [],
|
||||
selectedProjectId: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
openProjectIds: [],
|
||||
activeProjectId: null,
|
||||
tabOrder: []
|
||||
});
|
||||
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('openProjectTab', () => {
|
||||
it('should open a new project tab', () => {
|
||||
const project = createTestProject({ id: 'project-1' });
|
||||
useProjectStore.setState({ projects: [project] });
|
||||
|
||||
useProjectStore.getState().openProjectTab('project-1');
|
||||
|
||||
expect(useProjectStore.getState().openProjectIds).toContain('project-1');
|
||||
expect(useProjectStore.getState().activeProjectId).toBe('project-1');
|
||||
expect(useProjectStore.getState().tabOrder).toContain('project-1');
|
||||
});
|
||||
|
||||
it('should add to existing open tabs', () => {
|
||||
const project1 = createTestProject({ id: 'project-1' });
|
||||
const project2 = createTestProject({ id: 'project-2' });
|
||||
useProjectStore.setState({
|
||||
projects: [project1, project2],
|
||||
openProjectIds: ['project-1'],
|
||||
activeProjectId: 'project-1',
|
||||
tabOrder: ['project-1']
|
||||
});
|
||||
|
||||
useProjectStore.getState().openProjectTab('project-2');
|
||||
|
||||
expect(useProjectStore.getState().openProjectIds).toEqual(['project-1', 'project-2']);
|
||||
expect(useProjectStore.getState().activeProjectId).toBe('project-2');
|
||||
expect(useProjectStore.getState().tabOrder).toEqual(['project-1', 'project-2']);
|
||||
});
|
||||
|
||||
it('should not duplicate existing tab', () => {
|
||||
const project = createTestProject({ id: 'project-1' });
|
||||
useProjectStore.setState({
|
||||
projects: [project],
|
||||
openProjectIds: ['project-1'],
|
||||
activeProjectId: 'project-1',
|
||||
tabOrder: ['project-1']
|
||||
});
|
||||
|
||||
useProjectStore.getState().openProjectTab('project-1');
|
||||
|
||||
// Should only have one entry
|
||||
expect(useProjectStore.getState().openProjectIds).toEqual(['project-1']);
|
||||
expect(useProjectStore.getState().tabOrder).toEqual(['project-1']);
|
||||
// Should still make it active
|
||||
expect(useProjectStore.getState().activeProjectId).toBe('project-1');
|
||||
});
|
||||
|
||||
it('should preserve existing tab order when adding new tab', () => {
|
||||
const project1 = createTestProject({ id: 'project-1' });
|
||||
const project2 = createTestProject({ id: 'project-2' });
|
||||
const project3 = createTestProject({ id: 'project-3' });
|
||||
useProjectStore.setState({
|
||||
projects: [project1, project2, project3],
|
||||
openProjectIds: ['project-1', 'project-3'],
|
||||
activeProjectId: 'project-3',
|
||||
tabOrder: ['project-1', 'project-3']
|
||||
});
|
||||
|
||||
useProjectStore.getState().openProjectTab('project-2');
|
||||
|
||||
expect(useProjectStore.getState().tabOrder).toEqual(['project-1', 'project-3', 'project-2']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('closeProjectTab', () => {
|
||||
it('should close a project tab', () => {
|
||||
useProjectStore.setState({
|
||||
openProjectIds: ['project-1', 'project-2'],
|
||||
activeProjectId: 'project-2',
|
||||
tabOrder: ['project-1', 'project-2']
|
||||
});
|
||||
|
||||
useProjectStore.getState().closeProjectTab('project-1');
|
||||
|
||||
expect(useProjectStore.getState().openProjectIds).toEqual(['project-2']);
|
||||
expect(useProjectStore.getState().tabOrder).toEqual(['project-2']);
|
||||
});
|
||||
|
||||
it('should activate first remaining tab when closing active tab', () => {
|
||||
useProjectStore.setState({
|
||||
openProjectIds: ['project-1', 'project-2', 'project-3'],
|
||||
activeProjectId: 'project-2',
|
||||
tabOrder: ['project-1', 'project-2', 'project-3']
|
||||
});
|
||||
|
||||
useProjectStore.getState().closeProjectTab('project-2');
|
||||
|
||||
// After removing project-2 from tabOrder, we get ['project-1', 'project-3']
|
||||
// The first tab in the remaining order is 'project-1'
|
||||
expect(useProjectStore.getState().activeProjectId).toBe('project-1');
|
||||
});
|
||||
|
||||
it('should activate previous tab when closing active tab and no next tab', () => {
|
||||
useProjectStore.setState({
|
||||
openProjectIds: ['project-1', 'project-2'],
|
||||
activeProjectId: 'project-2',
|
||||
tabOrder: ['project-1', 'project-2']
|
||||
});
|
||||
|
||||
useProjectStore.getState().closeProjectTab('project-2');
|
||||
|
||||
expect(useProjectStore.getState().activeProjectId).toBe('project-1');
|
||||
});
|
||||
|
||||
it('should set activeProjectId to null when closing last tab', () => {
|
||||
useProjectStore.setState({
|
||||
openProjectIds: ['project-1'],
|
||||
activeProjectId: 'project-1',
|
||||
tabOrder: ['project-1']
|
||||
});
|
||||
|
||||
useProjectStore.getState().closeProjectTab('project-1');
|
||||
|
||||
expect(useProjectStore.getState().activeProjectId).toBeNull();
|
||||
});
|
||||
|
||||
it('should not affect activeProjectId when closing non-active tab', () => {
|
||||
useProjectStore.setState({
|
||||
openProjectIds: ['project-1', 'project-2'],
|
||||
activeProjectId: 'project-2',
|
||||
tabOrder: ['project-1', 'project-2']
|
||||
});
|
||||
|
||||
useProjectStore.getState().closeProjectTab('project-1');
|
||||
|
||||
expect(useProjectStore.getState().activeProjectId).toBe('project-2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('setActiveProject', () => {
|
||||
it('should set active project', () => {
|
||||
useProjectStore.setState({ activeProjectId: null });
|
||||
|
||||
useProjectStore.getState().setActiveProject('project-1');
|
||||
|
||||
expect(useProjectStore.getState().activeProjectId).toBe('project-1');
|
||||
});
|
||||
|
||||
it('should clear active project with null', () => {
|
||||
useProjectStore.setState({ activeProjectId: 'project-1' });
|
||||
|
||||
useProjectStore.getState().setActiveProject(null);
|
||||
|
||||
expect(useProjectStore.getState().activeProjectId).toBeNull();
|
||||
});
|
||||
|
||||
it('should also update selectedProjectId for backward compatibility', () => {
|
||||
useProjectStore.setState({ selectedProjectId: null });
|
||||
|
||||
useProjectStore.getState().setActiveProject('project-1');
|
||||
|
||||
expect(useProjectStore.getState().selectedProjectId).toBe('project-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('reorderTabs', () => {
|
||||
it('should reorder tabs by moving from index to index', () => {
|
||||
useProjectStore.setState({
|
||||
tabOrder: ['project-1', 'project-2', 'project-3', 'project-4']
|
||||
});
|
||||
|
||||
// Move project-3 from index 2 to index 1
|
||||
useProjectStore.getState().reorderTabs(2, 1);
|
||||
|
||||
expect(useProjectStore.getState().tabOrder).toEqual(['project-1', 'project-3', 'project-2', 'project-4']);
|
||||
});
|
||||
|
||||
it('should handle moving tab to the end', () => {
|
||||
useProjectStore.setState({
|
||||
tabOrder: ['project-1', 'project-2', 'project-3']
|
||||
});
|
||||
|
||||
// Move project-1 from index 0 to index 2
|
||||
useProjectStore.getState().reorderTabs(0, 2);
|
||||
|
||||
expect(useProjectStore.getState().tabOrder).toEqual(['project-2', 'project-3', 'project-1']);
|
||||
});
|
||||
|
||||
it('should handle moving tab to the beginning', () => {
|
||||
useProjectStore.setState({
|
||||
tabOrder: ['project-1', 'project-2', 'project-3']
|
||||
});
|
||||
|
||||
// Move project-3 from index 2 to index 0
|
||||
useProjectStore.getState().reorderTabs(2, 0);
|
||||
|
||||
expect(useProjectStore.getState().tabOrder).toEqual(['project-3', 'project-1', 'project-2']);
|
||||
});
|
||||
|
||||
it('should handle no-op reordering (same index)', () => {
|
||||
useProjectStore.setState({
|
||||
tabOrder: ['project-1', 'project-2', 'project-3']
|
||||
});
|
||||
|
||||
useProjectStore.getState().reorderTabs(1, 1);
|
||||
|
||||
expect(useProjectStore.getState().tabOrder).toEqual(['project-1', 'project-2', 'project-3']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('restoreTabState', () => {
|
||||
it('should be a no-op (tab state is now loaded via IPC in loadProjects)', () => {
|
||||
// Set up some initial state
|
||||
useProjectStore.setState({
|
||||
openProjectIds: ['existing'],
|
||||
activeProjectId: 'existing',
|
||||
tabOrder: ['existing']
|
||||
});
|
||||
|
||||
// restoreTabState is now a no-op - it just logs
|
||||
useProjectStore.getState().restoreTabState();
|
||||
|
||||
// State should remain unchanged (not modified by restoreTabState)
|
||||
expect(useProjectStore.getState().openProjectIds).toEqual(['existing']);
|
||||
expect(useProjectStore.getState().activeProjectId).toBe('existing');
|
||||
expect(useProjectStore.getState().tabOrder).toEqual(['existing']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getOpenProjects', () => {
|
||||
it('should return projects that are open', () => {
|
||||
const project1 = createTestProject({ id: 'project-1' });
|
||||
const project2 = createTestProject({ id: 'project-2' });
|
||||
const project3 = createTestProject({ id: 'project-3' });
|
||||
|
||||
useProjectStore.setState({
|
||||
projects: [project1, project2, project3],
|
||||
openProjectIds: ['project-1', 'project-3']
|
||||
});
|
||||
|
||||
const openProjects = useProjectStore.getState().getOpenProjects();
|
||||
|
||||
expect(openProjects).toHaveLength(2);
|
||||
expect(openProjects.map(p => p.id)).toEqual(['project-1', 'project-3']);
|
||||
});
|
||||
|
||||
it('should return empty array when no projects are open', () => {
|
||||
const project1 = createTestProject({ id: 'project-1' });
|
||||
|
||||
useProjectStore.setState({
|
||||
projects: [project1],
|
||||
openProjectIds: []
|
||||
});
|
||||
|
||||
const openProjects = useProjectStore.getState().getOpenProjects();
|
||||
|
||||
expect(openProjects).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should handle open project IDs that dont exist in projects', () => {
|
||||
const project1 = createTestProject({ id: 'project-1' });
|
||||
|
||||
useProjectStore.setState({
|
||||
projects: [project1],
|
||||
openProjectIds: ['project-1', 'non-existent']
|
||||
});
|
||||
|
||||
const openProjects = useProjectStore.getState().getOpenProjects();
|
||||
|
||||
expect(openProjects).toHaveLength(1);
|
||||
expect(openProjects[0].id).toBe('project-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getActiveProject', () => {
|
||||
it('should return the active project', () => {
|
||||
const project1 = createTestProject({ id: 'project-1' });
|
||||
const project2 = createTestProject({ id: 'project-2' });
|
||||
|
||||
useProjectStore.setState({
|
||||
projects: [project1, project2],
|
||||
activeProjectId: 'project-2'
|
||||
});
|
||||
|
||||
const activeProject = useProjectStore.getState().getActiveProject();
|
||||
|
||||
expect(activeProject).toBeDefined();
|
||||
expect(activeProject?.id).toBe('project-2');
|
||||
});
|
||||
|
||||
it('should return undefined when no active project', () => {
|
||||
const project1 = createTestProject({ id: 'project-1' });
|
||||
|
||||
useProjectStore.setState({
|
||||
projects: [project1],
|
||||
activeProjectId: null
|
||||
});
|
||||
|
||||
const activeProject = useProjectStore.getState().getActiveProject();
|
||||
|
||||
expect(activeProject).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return undefined when active project ID does not exist', () => {
|
||||
const project1 = createTestProject({ id: 'project-1' });
|
||||
|
||||
useProjectStore.setState({
|
||||
projects: [project1],
|
||||
activeProjectId: 'non-existent'
|
||||
});
|
||||
|
||||
const activeProject = useProjectStore.getState().getActiveProject();
|
||||
|
||||
expect(activeProject).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getProjectTabs', () => {
|
||||
it('should return projects in tab order', () => {
|
||||
const project1 = createTestProject({ id: 'project-1', name: 'Project 1' });
|
||||
const project2 = createTestProject({ id: 'project-2', name: 'Project 2' });
|
||||
const project3 = createTestProject({ id: 'project-3', name: 'Project 3' });
|
||||
|
||||
useProjectStore.setState({
|
||||
projects: [project1, project2, project3],
|
||||
openProjectIds: ['project-1', 'project-2', 'project-3'],
|
||||
tabOrder: ['project-3', 'project-1', 'project-2']
|
||||
});
|
||||
|
||||
const tabs = useProjectStore.getState().getProjectTabs();
|
||||
|
||||
expect(tabs).toHaveLength(3);
|
||||
expect(tabs.map(p => p.id)).toEqual(['project-3', 'project-1', 'project-2']);
|
||||
});
|
||||
|
||||
it('should append open projects not in tab order', () => {
|
||||
const project1 = createTestProject({ id: 'project-1', name: 'Project 1' });
|
||||
const project2 = createTestProject({ id: 'project-2', name: 'Project 2' });
|
||||
const project3 = createTestProject({ id: 'project-3', name: 'Project 3' });
|
||||
|
||||
useProjectStore.setState({
|
||||
projects: [project1, project2, project3],
|
||||
openProjectIds: ['project-1', 'project-2', 'project-3'],
|
||||
tabOrder: ['project-2'] // Only project-2 is in tabOrder
|
||||
});
|
||||
|
||||
const tabs = useProjectStore.getState().getProjectTabs();
|
||||
|
||||
expect(tabs).toHaveLength(3);
|
||||
// project-2 should be first (from tabOrder), others appended
|
||||
expect(tabs[0].id).toBe('project-2');
|
||||
expect(tabs.slice(1).map(p => p.id)).toContain('project-1');
|
||||
expect(tabs.slice(1).map(p => p.id)).toContain('project-3');
|
||||
});
|
||||
|
||||
it('should return empty array when no tabs are open', () => {
|
||||
const project1 = createTestProject({ id: 'project-1' });
|
||||
|
||||
useProjectStore.setState({
|
||||
projects: [project1],
|
||||
openProjectIds: [],
|
||||
tabOrder: []
|
||||
});
|
||||
|
||||
const tabs = useProjectStore.getState().getProjectTabs();
|
||||
|
||||
expect(tabs).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should handle tab order entries for projects that are not open', () => {
|
||||
const project1 = createTestProject({ id: 'project-1' });
|
||||
const project2 = createTestProject({ id: 'project-2' });
|
||||
|
||||
useProjectStore.setState({
|
||||
projects: [project1, project2],
|
||||
openProjectIds: ['project-1'], // Only project-1 is actually open
|
||||
tabOrder: ['project-2', 'project-1'] // tabOrder has project-2
|
||||
});
|
||||
|
||||
const tabs = useProjectStore.getState().getProjectTabs();
|
||||
|
||||
// getProjectTabs returns all projects in tabOrder, then adds open projects not in tabOrder
|
||||
// So it returns project-2 (from tabOrder) and project-1 (from tabOrder)
|
||||
// Even though project-2 is not in openProjectIds
|
||||
expect(tabs).toHaveLength(2);
|
||||
expect(tabs[0].id).toBe('project-2'); // First in tabOrder
|
||||
expect(tabs[1].id).toBe('project-1'); // Second in tabOrder
|
||||
});
|
||||
});
|
||||
|
||||
describe('Integration with existing project operations', () => {
|
||||
it('should open tab when adding project', () => {
|
||||
const project = createTestProject({ id: 'project-1' });
|
||||
|
||||
useProjectStore.setState({ projects: [] });
|
||||
useProjectStore.getState().addProject(project);
|
||||
useProjectStore.getState().selectProject(project.id);
|
||||
useProjectStore.getState().openProjectTab(project.id);
|
||||
|
||||
expect(useProjectStore.getState().projects).toContain(project);
|
||||
expect(useProjectStore.getState().selectedProjectId).toBe(project.id);
|
||||
expect(useProjectStore.getState().openProjectIds).toContain(project.id);
|
||||
expect(useProjectStore.getState().activeProjectId).toBe(project.id);
|
||||
});
|
||||
|
||||
it('should update selectedProjectId when removing project', () => {
|
||||
const project1 = createTestProject({ id: 'project-1' });
|
||||
const project2 = createTestProject({ id: 'project-2' });
|
||||
|
||||
useProjectStore.setState({
|
||||
projects: [project1, project2],
|
||||
openProjectIds: ['project-1', 'project-2'],
|
||||
activeProjectId: 'project-2',
|
||||
selectedProjectId: 'project-1'
|
||||
});
|
||||
|
||||
useProjectStore.getState().removeProject('project-1');
|
||||
|
||||
expect(useProjectStore.getState().projects).not.toContain(
|
||||
expect.objectContaining({ id: 'project-1' })
|
||||
);
|
||||
// removeProject clears selectedProjectId if it matches the removed project
|
||||
expect(useProjectStore.getState().selectedProjectId).toBeNull();
|
||||
// Note: openProjectIds is not automatically cleared by removeProject
|
||||
// This would be handled by the UI layer when it detects the project was removed
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,7 @@ function createTestFeature(overrides: Partial<RoadmapFeature> = {}): RoadmapFeat
|
||||
impact: 'medium',
|
||||
phaseId: 'phase-1',
|
||||
dependencies: [],
|
||||
status: 'idea' as RoadmapFeatureStatus,
|
||||
status: 'under_review' as RoadmapFeatureStatus,
|
||||
acceptanceCriteria: ['Test criteria'],
|
||||
userStories: ['As a user, I want to test'],
|
||||
...overrides
|
||||
@@ -309,7 +309,7 @@ describe('Roadmap Store', () => {
|
||||
impact: 'high' as const,
|
||||
phaseId: 'phase-1',
|
||||
dependencies: [],
|
||||
status: 'idea' as RoadmapFeatureStatus,
|
||||
status: 'under_review' as RoadmapFeatureStatus,
|
||||
acceptanceCriteria: ['Criteria 1'],
|
||||
userStories: ['User story 1']
|
||||
};
|
||||
@@ -336,7 +336,7 @@ describe('Roadmap Store', () => {
|
||||
impact: 'medium' as const,
|
||||
phaseId: 'phase-1',
|
||||
dependencies: [],
|
||||
status: 'idea' as RoadmapFeatureStatus,
|
||||
status: 'under_review' as RoadmapFeatureStatus,
|
||||
acceptanceCriteria: [],
|
||||
userStories: []
|
||||
};
|
||||
@@ -393,7 +393,7 @@ describe('Roadmap Store', () => {
|
||||
impact: 'high' as const,
|
||||
phaseId: 'phase-1',
|
||||
dependencies: [],
|
||||
status: 'idea' as RoadmapFeatureStatus,
|
||||
status: 'under_review' as RoadmapFeatureStatus,
|
||||
acceptanceCriteria: [],
|
||||
userStories: []
|
||||
});
|
||||
@@ -414,7 +414,7 @@ describe('Roadmap Store', () => {
|
||||
impact: 'high' as const,
|
||||
phaseId: 'phase-1',
|
||||
dependencies: [],
|
||||
status: 'idea' as RoadmapFeatureStatus,
|
||||
status: 'under_review' as RoadmapFeatureStatus,
|
||||
acceptanceCriteria: [],
|
||||
userStories: []
|
||||
});
|
||||
@@ -438,7 +438,7 @@ describe('Roadmap Store', () => {
|
||||
impact: 'medium' as const,
|
||||
phaseId: 'phase-3',
|
||||
dependencies: [],
|
||||
status: 'idea' as RoadmapFeatureStatus,
|
||||
status: 'under_review' as RoadmapFeatureStatus,
|
||||
acceptanceCriteria: [],
|
||||
userStories: []
|
||||
});
|
||||
@@ -489,7 +489,7 @@ describe('Roadmap Store', () => {
|
||||
|
||||
describe('updateFeatureStatus', () => {
|
||||
it('should update feature status by id', () => {
|
||||
const features = [createTestFeature({ id: 'feature-1', status: 'idea' })];
|
||||
const features = [createTestFeature({ id: 'feature-1', status: 'under_review' })];
|
||||
const roadmap = createTestRoadmap({ features });
|
||||
|
||||
useRoadmapStore.setState({ roadmap });
|
||||
@@ -502,8 +502,8 @@ describe('Roadmap Store', () => {
|
||||
});
|
||||
|
||||
describe('updateFeatureLinkedSpec', () => {
|
||||
it('should update linked spec and set status to planned', () => {
|
||||
const features = [createTestFeature({ id: 'feature-1', status: 'idea' })];
|
||||
it('should update linked spec and set status to in_progress', () => {
|
||||
const features = [createTestFeature({ id: 'feature-1', status: 'under_review' })];
|
||||
const roadmap = createTestRoadmap({ features });
|
||||
|
||||
useRoadmapStore.setState({ roadmap });
|
||||
@@ -512,7 +512,7 @@ describe('Roadmap Store', () => {
|
||||
|
||||
const state = useRoadmapStore.getState();
|
||||
expect(state.roadmap?.features[0].linkedSpecId).toBe('spec-abc');
|
||||
expect(state.roadmap?.features[0].status).toBe('planned');
|
||||
expect(state.roadmap?.features[0].status).toBe('in_progress');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -596,9 +596,9 @@ describe('Roadmap Store', () => {
|
||||
it('should return correct stats', () => {
|
||||
const roadmap = createTestRoadmap({
|
||||
features: [
|
||||
createTestFeature({ priority: 'must', status: 'idea', complexity: 'high' }),
|
||||
createTestFeature({ priority: 'must', status: 'under_review', complexity: 'high' }),
|
||||
createTestFeature({ priority: 'must', status: 'planned', complexity: 'medium' }),
|
||||
createTestFeature({ priority: 'should', status: 'idea', complexity: 'low' })
|
||||
createTestFeature({ priority: 'should', status: 'under_review', complexity: 'low' })
|
||||
]
|
||||
});
|
||||
|
||||
@@ -607,7 +607,7 @@ describe('Roadmap Store', () => {
|
||||
expect(stats.total).toBe(3);
|
||||
expect(stats.byPriority['must']).toBe(2);
|
||||
expect(stats.byPriority['should']).toBe(1);
|
||||
expect(stats.byStatus['idea']).toBe(2);
|
||||
expect(stats.byStatus['under_review']).toBe(2);
|
||||
expect(stats.byStatus['planned']).toBe(1);
|
||||
expect(stats.byComplexity['high']).toBe(1);
|
||||
expect(stats.byComplexity['medium']).toBe(1);
|
||||
|
||||
@@ -48,7 +48,8 @@ import {
|
||||
import type {
|
||||
RoadmapPhase,
|
||||
RoadmapFeaturePriority,
|
||||
RoadmapFeatureStatus
|
||||
RoadmapFeatureStatus,
|
||||
FeatureSource
|
||||
} from '../../shared/types';
|
||||
|
||||
/**
|
||||
@@ -147,9 +148,10 @@ export function AddFeatureDialog({
|
||||
impact,
|
||||
phaseId,
|
||||
dependencies: [],
|
||||
status: 'idea' as RoadmapFeatureStatus,
|
||||
status: 'under_review' as RoadmapFeatureStatus,
|
||||
acceptanceCriteria: [],
|
||||
userStories: []
|
||||
userStories: [],
|
||||
source: { provider: 'internal' }
|
||||
});
|
||||
|
||||
// Persist to file via IPC
|
||||
|
||||
@@ -149,11 +149,11 @@ export function AgentProfileSelector({
|
||||
description: profile.description
|
||||
};
|
||||
}
|
||||
// Default to balanced
|
||||
// Default to auto profile (the actual default)
|
||||
return {
|
||||
icon: Scale,
|
||||
label: 'Balanced',
|
||||
description: 'Good balance of speed and quality'
|
||||
icon: Sparkles,
|
||||
label: 'Auto (Optimized)',
|
||||
description: 'Uses Opus across all phases with optimized thinking levels'
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
@@ -24,9 +24,10 @@ interface CustomModelModalProps {
|
||||
currentConfig?: InsightsModelConfig;
|
||||
onSave: (config: InsightsModelConfig) => void;
|
||||
onClose: () => void;
|
||||
open?: boolean;
|
||||
}
|
||||
|
||||
export function CustomModelModal({ currentConfig, onSave, onClose }: CustomModelModalProps) {
|
||||
export function CustomModelModal({ currentConfig, onSave, onClose, open = true }: CustomModelModalProps) {
|
||||
const [model, setModel] = useState<ModelType>(
|
||||
currentConfig?.model || 'sonnet'
|
||||
);
|
||||
@@ -34,6 +35,14 @@ export function CustomModelModal({ currentConfig, onSave, onClose }: CustomModel
|
||||
currentConfig?.thinkingLevel || 'medium'
|
||||
);
|
||||
|
||||
// Sync internal state when modal opens or config changes
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setModel(currentConfig?.model || 'sonnet');
|
||||
setThinkingLevel(currentConfig?.thinkingLevel || 'medium');
|
||||
}
|
||||
}, [open, currentConfig]);
|
||||
|
||||
const handleSave = () => {
|
||||
onSave({
|
||||
profileId: 'custom',
|
||||
@@ -43,7 +52,7 @@ export function CustomModelModal({ currentConfig, onSave, onClose }: CustomModel
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={onClose}>
|
||||
<Dialog open={open} onOpenChange={onClose}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Custom Model Configuration</DialogTitle>
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { Globe, RefreshCw, TrendingUp, CheckCircle } from 'lucide-react';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from './ui/alert-dialog';
|
||||
import { Button } from './ui/button';
|
||||
|
||||
interface ExistingCompetitorAnalysisDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onUseExisting: () => void;
|
||||
onRunNew: () => void;
|
||||
onSkip: () => void;
|
||||
analysisDate?: Date;
|
||||
}
|
||||
|
||||
export function ExistingCompetitorAnalysisDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onUseExisting,
|
||||
onRunNew,
|
||||
onSkip,
|
||||
analysisDate,
|
||||
}: ExistingCompetitorAnalysisDialogProps) {
|
||||
const handleUseExisting = () => {
|
||||
onUseExisting();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleRunNew = () => {
|
||||
onRunNew();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleSkip = () => {
|
||||
onSkip();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const formatDate = (date?: Date) => {
|
||||
if (!date) return 'recently';
|
||||
return new Intl.DateTimeFormat('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
}).format(date);
|
||||
};
|
||||
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
<AlertDialogContent className="sm:max-w-[500px]">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2 text-foreground">
|
||||
<TrendingUp className="h-5 w-5 text-primary" />
|
||||
Competitor Analysis Options
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="text-muted-foreground">
|
||||
This project has an existing competitor analysis from {formatDate(analysisDate)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
|
||||
<div className="py-4 space-y-3">
|
||||
{/* Option 1: Use existing (recommended) */}
|
||||
<button
|
||||
onClick={handleUseExisting}
|
||||
className="w-full rounded-lg bg-primary/10 border border-primary/30 p-4 text-left hover:bg-primary/20 transition-colors"
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<CheckCircle className="h-5 w-5 text-primary flex-shrink-0 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<h4 className="text-sm font-medium text-foreground flex items-center gap-2">
|
||||
Use existing analysis
|
||||
<span className="text-xs text-primary font-normal">(Recommended)</span>
|
||||
</h4>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Reuse the competitor insights you already have. Faster and no additional web searches.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Option 2: Run new analysis */}
|
||||
<button
|
||||
onClick={handleRunNew}
|
||||
className="w-full rounded-lg bg-muted/50 border border-border p-4 text-left hover:bg-muted transition-colors"
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<RefreshCw className="h-5 w-5 text-muted-foreground flex-shrink-0 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<h4 className="text-sm font-medium text-foreground">
|
||||
Run new analysis
|
||||
</h4>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Perform fresh web searches to get updated competitor information. Takes longer.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Option 3: Skip */}
|
||||
<button
|
||||
onClick={handleSkip}
|
||||
className="w-full rounded-lg bg-muted/30 border border-border/50 p-4 text-left hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<Globe className="h-5 w-5 text-muted-foreground/60 flex-shrink-0 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<h4 className="text-sm font-medium text-muted-foreground">
|
||||
Skip competitor analysis
|
||||
</h4>
|
||||
<p className="text-xs text-muted-foreground/80 mt-1">
|
||||
Generate roadmap without any competitor insights.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<AlertDialogFooter className="sm:justify-start">
|
||||
<Button variant="ghost" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
|
||||
import { File, Folder, ChevronRight } from 'lucide-react';
|
||||
import { cn } from '../lib/utils';
|
||||
import { useFileExplorerStore } from '../stores/file-explorer-store';
|
||||
import type { FileNode } from '../../shared/types';
|
||||
|
||||
interface FileAutocompleteProps {
|
||||
query: string;
|
||||
projectPath: string;
|
||||
position: { top: number; left: number };
|
||||
onSelect: (filename: string, fullPath: string) => void;
|
||||
onClose: () => void;
|
||||
maxResults?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Autocomplete popup for @ file mentions in the task description.
|
||||
* Shows filtered list of files based on the query after @.
|
||||
*/
|
||||
export function FileAutocomplete({
|
||||
query,
|
||||
projectPath,
|
||||
position,
|
||||
onSelect,
|
||||
onClose,
|
||||
maxResults = 10
|
||||
}: FileAutocompleteProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const { files, loadDirectory } = useFileExplorerStore();
|
||||
|
||||
// Load root directory if not cached
|
||||
useEffect(() => {
|
||||
if (projectPath && !files.has(projectPath)) {
|
||||
loadDirectory(projectPath);
|
||||
}
|
||||
}, [projectPath, files, loadDirectory]);
|
||||
|
||||
// Collect all files from cache (flatten the tree)
|
||||
const allFiles = useMemo(() => {
|
||||
const result: FileNode[] = [];
|
||||
|
||||
// Recursive function to collect all cached files
|
||||
const collectFiles = (dirPath: string, visited = new Set<string>()) => {
|
||||
if (visited.has(dirPath)) return;
|
||||
visited.add(dirPath);
|
||||
|
||||
const dirFiles = files.get(dirPath);
|
||||
if (!dirFiles) return;
|
||||
|
||||
for (const file of dirFiles) {
|
||||
result.push(file);
|
||||
// For directories, also load and collect their children if cached
|
||||
if (file.isDirectory && files.has(file.path)) {
|
||||
collectFiles(file.path, visited);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
collectFiles(projectPath);
|
||||
return result;
|
||||
}, [files, projectPath]);
|
||||
|
||||
// Filter files based on query
|
||||
const filteredFiles = useMemo(() => {
|
||||
if (!query) {
|
||||
// Show most recently accessed or common files when no query
|
||||
return allFiles.filter(f => !f.isDirectory).slice(0, maxResults);
|
||||
}
|
||||
|
||||
const lowerQuery = query.toLowerCase();
|
||||
|
||||
// Score files by match quality
|
||||
const scored = allFiles
|
||||
.filter(f => !f.isDirectory) // Only files, not directories
|
||||
.map(file => {
|
||||
const name = file.name.toLowerCase();
|
||||
const path = file.path.toLowerCase();
|
||||
|
||||
let score = 0;
|
||||
|
||||
// Exact name match (highest priority)
|
||||
if (name === lowerQuery) {
|
||||
score = 1000;
|
||||
}
|
||||
// Name starts with query
|
||||
else if (name.startsWith(lowerQuery)) {
|
||||
score = 100;
|
||||
}
|
||||
// Name contains query
|
||||
else if (name.includes(lowerQuery)) {
|
||||
score = 50;
|
||||
}
|
||||
// Path contains query
|
||||
else if (path.includes(lowerQuery)) {
|
||||
score = 10;
|
||||
}
|
||||
|
||||
return { file, score };
|
||||
})
|
||||
.filter(item => item.score > 0)
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.slice(0, maxResults)
|
||||
.map(item => item.file);
|
||||
|
||||
return scored;
|
||||
}, [allFiles, query, maxResults]);
|
||||
|
||||
// Reset selection when results change
|
||||
useEffect(() => {
|
||||
setSelectedIndex(0);
|
||||
}, [filteredFiles]);
|
||||
|
||||
// Scroll selected item into view
|
||||
useEffect(() => {
|
||||
const list = listRef.current;
|
||||
if (!list) return;
|
||||
|
||||
const selectedElement = list.children[selectedIndex] as HTMLElement;
|
||||
if (selectedElement) {
|
||||
selectedElement.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
}, [selectedIndex]);
|
||||
|
||||
// Handle keyboard navigation
|
||||
const handleKeyDown = useCallback((e: KeyboardEvent) => {
|
||||
switch (e.key) {
|
||||
case 'ArrowDown':
|
||||
e.preventDefault();
|
||||
setSelectedIndex(prev =>
|
||||
prev < filteredFiles.length - 1 ? prev + 1 : prev
|
||||
);
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
e.preventDefault();
|
||||
setSelectedIndex(prev => prev > 0 ? prev - 1 : prev);
|
||||
break;
|
||||
case 'Enter':
|
||||
e.preventDefault();
|
||||
if (filteredFiles[selectedIndex]) {
|
||||
const file = filteredFiles[selectedIndex];
|
||||
onSelect(file.name, file.path);
|
||||
}
|
||||
break;
|
||||
case 'Escape':
|
||||
e.preventDefault();
|
||||
onClose();
|
||||
break;
|
||||
case 'Tab':
|
||||
e.preventDefault();
|
||||
if (filteredFiles[selectedIndex]) {
|
||||
const file = filteredFiles[selectedIndex];
|
||||
onSelect(file.name, file.path);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}, [filteredFiles, selectedIndex, onSelect, onClose]);
|
||||
|
||||
// Attach keyboard listener
|
||||
useEffect(() => {
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}, [handleKeyDown]);
|
||||
|
||||
// Get relative path from project root
|
||||
const getRelativePath = (fullPath: string) => {
|
||||
if (fullPath.startsWith(projectPath)) {
|
||||
return fullPath.slice(projectPath.length + 1); // +1 for the slash
|
||||
}
|
||||
return fullPath;
|
||||
};
|
||||
|
||||
// Don't render if no results
|
||||
if (filteredFiles.length === 0) {
|
||||
return (
|
||||
<div
|
||||
className="absolute z-50 bg-popover border border-border rounded-md shadow-lg p-3 text-sm text-muted-foreground"
|
||||
style={{
|
||||
top: position.top,
|
||||
left: position.left,
|
||||
minWidth: '200px'
|
||||
}}
|
||||
>
|
||||
No files found
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="absolute z-50 bg-popover border border-border rounded-md shadow-lg overflow-hidden"
|
||||
style={{
|
||||
top: position.top,
|
||||
left: position.left,
|
||||
minWidth: '280px',
|
||||
maxWidth: '400px',
|
||||
maxHeight: '240px'
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={listRef}
|
||||
className="overflow-y-auto max-h-[240px]"
|
||||
>
|
||||
{filteredFiles.map((file, index) => (
|
||||
<button
|
||||
key={file.path}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-2 px-3 py-2 text-left text-sm',
|
||||
'hover:bg-accent hover:text-accent-foreground',
|
||||
'focus:outline-none transition-colors',
|
||||
index === selectedIndex && 'bg-accent text-accent-foreground'
|
||||
)}
|
||||
onClick={() => onSelect(file.name, file.path)}
|
||||
onMouseEnter={() => setSelectedIndex(index)}
|
||||
>
|
||||
{file.isDirectory ? (
|
||||
<Folder className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
) : (
|
||||
<File className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium truncate">{file.name}</div>
|
||||
<div className="text-xs text-muted-foreground truncate flex items-center gap-1">
|
||||
<ChevronRight className="h-3 w-3 shrink-0" />
|
||||
{getRelativePath(file.path)}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="border-t border-border px-3 py-1.5 text-[10px] text-muted-foreground bg-muted/30">
|
||||
<span className="font-medium">↑↓</span> navigate · <span className="font-medium">Enter</span> select · <span className="font-medium">Esc</span> close
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -116,13 +116,13 @@ export function FileTreeItem({
|
||||
// Create a custom drag image using safe DOM manipulation (no innerHTML)
|
||||
const dragImage = document.createElement('div');
|
||||
dragImage.className = 'flex items-center gap-2 bg-card border border-primary rounded-md px-3 py-2 shadow-lg text-sm';
|
||||
|
||||
|
||||
const iconSpan = document.createElement('span');
|
||||
iconSpan.textContent = node.isDirectory ? '📁' : '📄';
|
||||
|
||||
|
||||
const nameSpan = document.createElement('span');
|
||||
nameSpan.textContent = node.name;
|
||||
|
||||
|
||||
dragImage.appendChild(iconSpan);
|
||||
dragImage.appendChild(nameSpan);
|
||||
dragImage.style.position = 'absolute';
|
||||
|
||||
@@ -7,7 +7,13 @@ import {
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
ChevronRight,
|
||||
Sparkles
|
||||
Sparkles,
|
||||
Plus,
|
||||
Link,
|
||||
Lock,
|
||||
Globe,
|
||||
Building,
|
||||
User
|
||||
} from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
import {
|
||||
@@ -19,6 +25,7 @@ import {
|
||||
DialogTitle
|
||||
} from './ui/dialog';
|
||||
import { Label } from './ui/label';
|
||||
import { Input } from './ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -38,7 +45,7 @@ interface GitHubSetupModalProps {
|
||||
onSkip?: () => void;
|
||||
}
|
||||
|
||||
type SetupStep = 'github-auth' | 'claude-auth' | 'repo' | 'branch' | 'complete';
|
||||
type SetupStep = 'github-auth' | 'claude-auth' | 'repo-confirm' | 'repo' | 'branch' | 'complete';
|
||||
|
||||
/**
|
||||
* Setup Modal - Required setup flow after Auto Claude initialization
|
||||
@@ -67,10 +74,23 @@ export function GitHubSetupModal({
|
||||
const [isLoadingRepo, setIsLoadingRepo] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Reset state when modal opens
|
||||
// Repo setup state (for when no remote is detected)
|
||||
const [repoAction, setRepoAction] = useState<'create' | 'link' | null>(null);
|
||||
const [newRepoName, setNewRepoName] = useState('');
|
||||
const [isPrivateRepo, setIsPrivateRepo] = useState(true);
|
||||
const [existingRepoName, setExistingRepoName] = useState('');
|
||||
const [isCreatingRepo, setIsCreatingRepo] = useState(false);
|
||||
|
||||
// Organization selection state
|
||||
const [githubUsername, setGithubUsername] = useState<string | null>(null);
|
||||
const [organizations, setOrganizations] = useState<Array<{ login: string; avatarUrl?: string }>>([]);
|
||||
const [selectedOwner, setSelectedOwner] = useState<string | null>(null);
|
||||
const [isLoadingOrgs, setIsLoadingOrgs] = useState(false);
|
||||
|
||||
// Reset state and check existing auth when modal opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setStep('github-auth');
|
||||
// Reset all state first
|
||||
setGithubToken(null);
|
||||
setGithubRepo(null);
|
||||
setDetectedRepo(null);
|
||||
@@ -78,9 +98,84 @@ export function GitHubSetupModal({
|
||||
setSelectedBranch(null);
|
||||
setRecommendedBranch(null);
|
||||
setError(null);
|
||||
// Reset repo setup state
|
||||
setRepoAction(null);
|
||||
setNewRepoName(project.name.replace(/[^A-Za-z0-9_.-]/g, '-'));
|
||||
setIsPrivateRepo(true);
|
||||
setExistingRepoName('');
|
||||
setIsCreatingRepo(false);
|
||||
// Reset organization state
|
||||
setGithubUsername(null);
|
||||
setOrganizations([]);
|
||||
setSelectedOwner(null);
|
||||
setIsLoadingOrgs(false);
|
||||
|
||||
// Check for existing authentication and skip to appropriate step
|
||||
const checkExistingAuth = async () => {
|
||||
try {
|
||||
// Check for existing GitHub token
|
||||
const ghTokenResult = await window.electronAPI.getGitHubToken();
|
||||
const hasGitHubAuth = ghTokenResult.success && ghTokenResult.data?.token;
|
||||
|
||||
// Check for existing Claude authentication
|
||||
const profilesResult = await window.electronAPI.getClaudeProfiles();
|
||||
let hasClaudeAuth = false;
|
||||
if (profilesResult.success && profilesResult.data) {
|
||||
const activeProfile = profilesResult.data.profiles.find(
|
||||
(p) => p.id === profilesResult.data!.activeProfileId
|
||||
);
|
||||
hasClaudeAuth = !!(activeProfile?.oauthToken || (activeProfile?.isDefault && activeProfile?.configDir));
|
||||
}
|
||||
|
||||
// Determine starting step based on existing auth
|
||||
if (hasGitHubAuth && hasClaudeAuth) {
|
||||
// Both authenticated, go directly to repo detection
|
||||
setGithubToken(ghTokenResult.data!.token);
|
||||
// detectRepository will be called and set the step
|
||||
setStep('repo'); // Temporary, detectRepository will update
|
||||
await detectRepository();
|
||||
} else if (hasGitHubAuth) {
|
||||
// Only GitHub authenticated, go to Claude auth
|
||||
setGithubToken(ghTokenResult.data!.token);
|
||||
setStep('claude-auth');
|
||||
} else {
|
||||
// No auth, start from beginning
|
||||
setStep('github-auth');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to check existing auth:', err);
|
||||
// On error, start from beginning
|
||||
setStep('github-auth');
|
||||
}
|
||||
};
|
||||
|
||||
checkExistingAuth();
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// Load user info and organizations
|
||||
const loadUserAndOrgs = async () => {
|
||||
setIsLoadingOrgs(true);
|
||||
try {
|
||||
// Get current user
|
||||
const userResult = await window.electronAPI.getGitHubUser();
|
||||
if (userResult.success && userResult.data) {
|
||||
setGithubUsername(userResult.data.username);
|
||||
setSelectedOwner(userResult.data.username); // Default to personal account
|
||||
}
|
||||
|
||||
// Get organizations
|
||||
const orgsResult = await window.electronAPI.listGitHubOrgs();
|
||||
if (orgsResult.success && orgsResult.data) {
|
||||
setOrganizations(orgsResult.data.orgs);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to load user/orgs:', err);
|
||||
} finally {
|
||||
setIsLoadingOrgs(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Detect repository from git remote when auth succeeds
|
||||
const detectRepository = async () => {
|
||||
setIsLoadingRepo(true);
|
||||
@@ -92,15 +187,16 @@ export function GitHubSetupModal({
|
||||
if (result.success && result.data) {
|
||||
setDetectedRepo(result.data);
|
||||
setGithubRepo(result.data);
|
||||
setStep('branch');
|
||||
// Immediately load branches
|
||||
await loadBranches(result.data);
|
||||
// Go to confirmation step instead of directly to branch
|
||||
setStep('repo-confirm');
|
||||
} else {
|
||||
// No remote detected, show repo input step
|
||||
// No remote detected, load orgs and show repo setup step
|
||||
await loadUserAndOrgs();
|
||||
setStep('repo');
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to detect repository');
|
||||
await loadUserAndOrgs();
|
||||
setStep('repo');
|
||||
} finally {
|
||||
setIsLoadingRepo(false);
|
||||
@@ -146,7 +242,27 @@ export function GitHubSetupModal({
|
||||
// Handle GitHub OAuth success
|
||||
const handleGitHubAuthSuccess = async (token: string) => {
|
||||
setGithubToken(token);
|
||||
// Move to Claude auth step
|
||||
|
||||
// Check if Claude is already authenticated before showing auth step
|
||||
try {
|
||||
const profilesResult = await window.electronAPI.getClaudeProfiles();
|
||||
if (profilesResult.success && profilesResult.data) {
|
||||
const activeProfile = profilesResult.data.profiles.find(
|
||||
(p) => p.id === profilesResult.data!.activeProfileId
|
||||
);
|
||||
// Check if active profile has authentication (oauthToken or default with configDir)
|
||||
if (activeProfile?.oauthToken || (activeProfile?.isDefault && activeProfile?.configDir)) {
|
||||
// Already authenticated, skip Claude auth and go directly to repo detection
|
||||
await detectRepository();
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to check Claude profiles:', err);
|
||||
// On error, fall through to show Claude auth step
|
||||
}
|
||||
|
||||
// Not authenticated, show Claude auth step
|
||||
setStep('claude-auth');
|
||||
};
|
||||
|
||||
@@ -157,6 +273,92 @@ export function GitHubSetupModal({
|
||||
await detectRepository();
|
||||
};
|
||||
|
||||
// Handle creating a new GitHub repository
|
||||
const handleCreateRepo = async () => {
|
||||
if (!newRepoName.trim()) {
|
||||
setError('Please enter a repository name');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!selectedOwner) {
|
||||
setError('Please select an owner for the repository');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreatingRepo(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await window.electronAPI.createGitHubRepo(newRepoName.trim(), {
|
||||
isPrivate: isPrivateRepo,
|
||||
projectPath: project.path,
|
||||
owner: selectedOwner !== githubUsername ? selectedOwner : undefined // Only pass owner if it's an org
|
||||
});
|
||||
|
||||
if (result.success && result.data) {
|
||||
// Repo created and remote added automatically by gh CLI
|
||||
setGithubRepo(result.data.fullName);
|
||||
setDetectedRepo(result.data.fullName);
|
||||
setStep('branch');
|
||||
await loadBranches(result.data.fullName);
|
||||
} else {
|
||||
setError(result.error || 'Failed to create repository');
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to create repository');
|
||||
} finally {
|
||||
setIsCreatingRepo(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle confirming the detected repository
|
||||
const handleConfirmRepo = async () => {
|
||||
if (detectedRepo) {
|
||||
setStep('branch');
|
||||
await loadBranches(detectedRepo);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle changing the repository (go to repo setup)
|
||||
const handleChangeRepo = async () => {
|
||||
await loadUserAndOrgs();
|
||||
setStep('repo');
|
||||
};
|
||||
|
||||
// Handle linking to an existing GitHub repository
|
||||
const handleLinkRepo = async () => {
|
||||
if (!existingRepoName.trim()) {
|
||||
setError('Please enter a repository name (owner/repo format)');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate format
|
||||
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(existingRepoName.trim())) {
|
||||
setError('Invalid format. Use owner/repo (e.g., username/my-project)');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreatingRepo(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await window.electronAPI.addGitRemote(project.path, existingRepoName.trim());
|
||||
|
||||
if (result.success) {
|
||||
setGithubRepo(existingRepoName.trim());
|
||||
setDetectedRepo(existingRepoName.trim());
|
||||
setStep('branch');
|
||||
await loadBranches(existingRepoName.trim());
|
||||
} else {
|
||||
setError(result.error || 'Failed to add remote');
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to add remote');
|
||||
} finally {
|
||||
setIsCreatingRepo(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle branch selection complete
|
||||
const handleComplete = () => {
|
||||
if (githubToken && githubRepo && selectedBranch) {
|
||||
@@ -215,34 +417,235 @@ export function GitHubSetupModal({
|
||||
</>
|
||||
);
|
||||
|
||||
case 'repo-confirm':
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Github className="h-5 w-5" />
|
||||
Confirm Repository
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
We detected a GitHub repository for this project. Please confirm or change it.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="py-4 space-y-4">
|
||||
<div className="rounded-lg border bg-muted/50 p-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<CheckCircle2 className="h-6 w-6 text-green-500" />
|
||||
<div>
|
||||
<p className="font-medium">Repository Detected</p>
|
||||
<p className="text-sm text-muted-foreground font-mono">
|
||||
{detectedRepo}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Auto Claude will use this repository for managing task branches and keeping your code up to date.
|
||||
</p>
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg bg-destructive/10 border border-destructive/30 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleChangeRepo}>
|
||||
Use Different Repository
|
||||
</Button>
|
||||
<Button onClick={handleConfirmRepo}>
|
||||
<CheckCircle2 className="mr-2 h-4 w-4" />
|
||||
Confirm & Continue
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
|
||||
case 'repo':
|
||||
return (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Github className="h-5 w-5" />
|
||||
Repository Not Detected
|
||||
Connect to GitHub
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
We couldn't detect a GitHub repository for this project. Please ensure your project has a GitHub remote configured.
|
||||
Your project needs a GitHub repository. Create a new one or link to an existing repository.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="py-4 space-y-4">
|
||||
<div className="rounded-lg border border-warning/30 bg-warning/10 p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertCircle className="h-5 w-5 text-warning mt-0.5" />
|
||||
{/* Action selection */}
|
||||
{!repoAction && (
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<button
|
||||
onClick={() => setRepoAction('create')}
|
||||
className="flex flex-col items-center gap-2 p-4 rounded-lg border-2 border-dashed hover:border-primary hover:bg-primary/5 transition-colors"
|
||||
>
|
||||
<Plus className="h-8 w-8 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Create New Repo</span>
|
||||
<span className="text-xs text-muted-foreground text-center">
|
||||
Create a new repository on GitHub
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setRepoAction('link')}
|
||||
className="flex flex-col items-center gap-2 p-4 rounded-lg border-2 border-dashed hover:border-primary hover:bg-primary/5 transition-colors"
|
||||
>
|
||||
<Link className="h-8 w-8 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">Link Existing</span>
|
||||
<span className="text-xs text-muted-foreground text-center">
|
||||
Connect to an existing repository
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Create new repo form */}
|
||||
{repoAction === 'create' && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<button
|
||||
onClick={() => setRepoAction(null)}
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
← Back
|
||||
</button>
|
||||
<span>Create a new repository</span>
|
||||
</div>
|
||||
|
||||
{/* Owner selection */}
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">No GitHub remote found</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
To use Auto Claude, your project needs to be connected to a GitHub repository.
|
||||
</p>
|
||||
<div className="text-xs font-mono bg-muted p-2 rounded mt-2">
|
||||
git remote add origin https://github.com/owner/repo.git
|
||||
<Label>Owner</Label>
|
||||
{isLoadingOrgs ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Loading accounts...
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{/* Personal account */}
|
||||
{githubUsername && (
|
||||
<button
|
||||
onClick={() => setSelectedOwner(githubUsername)}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-md border ${
|
||||
selectedOwner === githubUsername
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-muted hover:border-primary/50'
|
||||
}`}
|
||||
disabled={isCreatingRepo}
|
||||
>
|
||||
<User className="h-4 w-4" />
|
||||
<span className="text-sm">{githubUsername}</span>
|
||||
</button>
|
||||
)}
|
||||
{/* Organizations */}
|
||||
{organizations.map((org) => (
|
||||
<button
|
||||
key={org.login}
|
||||
onClick={() => setSelectedOwner(org.login)}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-md border ${
|
||||
selectedOwner === org.login
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-muted hover:border-primary/50'
|
||||
}`}
|
||||
disabled={isCreatingRepo}
|
||||
>
|
||||
<Building className="h-4 w-4" />
|
||||
<span className="text-sm">{org.login}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{organizations.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Select your personal account or an organization
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repo-name">Repository Name</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{selectedOwner || '...'} /
|
||||
</span>
|
||||
<Input
|
||||
id="repo-name"
|
||||
value={newRepoName}
|
||||
onChange={(e) => setNewRepoName(e.target.value)}
|
||||
placeholder="my-project"
|
||||
disabled={isCreatingRepo}
|
||||
className="flex-1"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Visibility</Label>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setIsPrivateRepo(true)}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-md border ${
|
||||
isPrivateRepo
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-muted hover:border-primary/50'
|
||||
}`}
|
||||
disabled={isCreatingRepo}
|
||||
>
|
||||
<Lock className="h-4 w-4" />
|
||||
<span className="text-sm">Private</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setIsPrivateRepo(false)}
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-md border ${
|
||||
!isPrivateRepo
|
||||
? 'border-primary bg-primary/10 text-primary'
|
||||
: 'border-muted hover:border-primary/50'
|
||||
}`}
|
||||
disabled={isCreatingRepo}
|
||||
>
|
||||
<Globe className="h-4 w-4" />
|
||||
<span className="text-sm">Public</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Link existing repo form */}
|
||||
{repoAction === 'link' && (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<button
|
||||
onClick={() => setRepoAction(null)}
|
||||
className="text-primary hover:underline"
|
||||
>
|
||||
← Back
|
||||
</button>
|
||||
<span>Link to existing repository</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="existing-repo">Repository</Label>
|
||||
<Input
|
||||
id="existing-repo"
|
||||
value={existingRepoName}
|
||||
onChange={(e) => setExistingRepoName(e.target.value)}
|
||||
placeholder="username/repository"
|
||||
disabled={isCreatingRepo}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Enter the full repository path (e.g., octocat/hello-world)
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg bg-destructive/10 border border-destructive/30 p-3 text-sm text-destructive">
|
||||
@@ -253,20 +656,52 @@ export function GitHubSetupModal({
|
||||
|
||||
<DialogFooter>
|
||||
{onSkip && (
|
||||
<Button variant="outline" onClick={onSkip}>
|
||||
<Button variant="outline" onClick={onSkip} disabled={isCreatingRepo}>
|
||||
Skip for now
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={detectRepository} disabled={isLoadingRepo}>
|
||||
{isLoadingRepo ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Checking...
|
||||
</>
|
||||
) : (
|
||||
'Retry Detection'
|
||||
)}
|
||||
</Button>
|
||||
{repoAction === 'create' && (
|
||||
<Button onClick={handleCreateRepo} disabled={isCreatingRepo || !newRepoName.trim()}>
|
||||
{isCreatingRepo ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Create Repository
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{repoAction === 'link' && (
|
||||
<Button onClick={handleLinkRepo} disabled={isCreatingRepo || !existingRepoName.trim()}>
|
||||
{isCreatingRepo ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Linking...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Link className="mr-2 h-4 w-4" />
|
||||
Link Repository
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{!repoAction && (
|
||||
<Button variant="outline" onClick={detectRepository} disabled={isLoadingRepo}>
|
||||
{isLoadingRepo ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Checking...
|
||||
</>
|
||||
) : (
|
||||
'Retry Detection'
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { Brain, Scale, Zap, Sliders, Check } from 'lucide-react';
|
||||
import { Brain, Scale, Zap, Sparkles, Sliders, Check } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -22,7 +22,8 @@ interface InsightsModelSelectorProps {
|
||||
const iconMap: Record<string, React.ElementType> = {
|
||||
Brain,
|
||||
Scale,
|
||||
Zap
|
||||
Zap,
|
||||
Sparkles
|
||||
};
|
||||
|
||||
export function InsightsModelSelector({
|
||||
@@ -32,8 +33,9 @@ export function InsightsModelSelector({
|
||||
}: InsightsModelSelectorProps) {
|
||||
const [showCustomModal, setShowCustomModal] = useState(false);
|
||||
|
||||
// Default to 'balanced' if no config
|
||||
const selectedProfileId = currentConfig?.profileId || 'balanced';
|
||||
// Default to 'balanced' if no config, or if 'auto' profile was selected (not applicable for insights)
|
||||
const rawProfileId = currentConfig?.profileId || 'balanced';
|
||||
const selectedProfileId = rawProfileId === 'auto' ? 'balanced' : rawProfileId;
|
||||
const profile = DEFAULT_AGENT_PROFILES.find(p => p.id === selectedProfileId);
|
||||
|
||||
// Get the appropriate icon
|
||||
@@ -90,7 +92,7 @@ export function InsightsModelSelector({
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-64">
|
||||
<DropdownMenuLabel>Agent Profile</DropdownMenuLabel>
|
||||
{DEFAULT_AGENT_PROFILES.map((p) => {
|
||||
{DEFAULT_AGENT_PROFILES.filter(p => !p.isAutoProfile).map((p) => {
|
||||
const ProfileIcon = iconMap[p.icon || 'Brain'];
|
||||
const isSelected = selectedProfileId === p.id;
|
||||
const modelLabel = AVAILABLE_MODELS.find(m => m.value === p.model)?.label;
|
||||
@@ -132,13 +134,12 @@ export function InsightsModelSelector({
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{showCustomModal && (
|
||||
<CustomModelModal
|
||||
currentConfig={currentConfig}
|
||||
onSave={handleCustomSave}
|
||||
onClose={() => setShowCustomModal(false)}
|
||||
/>
|
||||
)}
|
||||
<CustomModelModal
|
||||
open={showCustomModal}
|
||||
currentConfig={currentConfig}
|
||||
onSave={handleCustomSave}
|
||||
onClose={() => setShowCustomModal(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -79,14 +79,9 @@ export function ProjectSettings({ project, open, onOpenChange }: ProjectSettings
|
||||
const {
|
||||
infrastructureStatus,
|
||||
isCheckingInfrastructure,
|
||||
isStartingFalkorDB,
|
||||
isOpeningDocker,
|
||||
handleStartFalkorDB,
|
||||
handleOpenDockerDesktop,
|
||||
handleDownloadDocker,
|
||||
} = useInfrastructureStatus(
|
||||
envConfig?.graphitiEnabled,
|
||||
envConfig?.graphitiFalkorDbPort,
|
||||
envConfig?.graphitiDbPath,
|
||||
open
|
||||
);
|
||||
|
||||
@@ -253,11 +248,6 @@ export function ProjectSettings({ project, open, onOpenChange }: ProjectSettings
|
||||
onUpdateSettings={(updates) => setSettings({ ...settings, ...updates })}
|
||||
infrastructureStatus={infrastructureStatus}
|
||||
isCheckingInfrastructure={isCheckingInfrastructure}
|
||||
isStartingFalkorDB={isStartingFalkorDB}
|
||||
isOpeningDocker={isOpeningDocker}
|
||||
onStartFalkorDB={handleStartFalkorDB}
|
||||
onOpenDockerDesktop={handleOpenDockerDesktop}
|
||||
onDownloadDocker={handleDownloadDocker}
|
||||
/>
|
||||
|
||||
<Separator />
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { cn } from '../lib/utils';
|
||||
import { Button } from './ui/button';
|
||||
import { SortableProjectTab } from './SortableProjectTab';
|
||||
import type { Project } from '../../shared/types';
|
||||
|
||||
interface ProjectTabBarProps {
|
||||
projects: Project[];
|
||||
activeProjectId: string | null;
|
||||
onProjectSelect: (projectId: string) => void;
|
||||
onProjectClose: (projectId: string) => void;
|
||||
onAddProject: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function ProjectTabBar({
|
||||
projects,
|
||||
activeProjectId,
|
||||
onProjectSelect,
|
||||
onProjectClose,
|
||||
onAddProject,
|
||||
className
|
||||
}: ProjectTabBarProps) {
|
||||
// Keyboard shortcuts for tab navigation
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
// Skip if in input fields
|
||||
if (
|
||||
e.target instanceof HTMLInputElement ||
|
||||
e.target instanceof HTMLTextAreaElement ||
|
||||
(e.target as HTMLElement)?.isContentEditable
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isMod = e.metaKey || e.ctrlKey;
|
||||
if (!isMod) return;
|
||||
|
||||
// Cmd/Ctrl + 1-9: Switch to tab N
|
||||
if (e.key >= '1' && e.key <= '9') {
|
||||
e.preventDefault();
|
||||
const index = parseInt(e.key) - 1;
|
||||
if (index < projects.length) {
|
||||
onProjectSelect(projects[index].id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Cmd/Ctrl + Tab: Next tab
|
||||
// Cmd/Ctrl + Shift + Tab: Previous tab
|
||||
if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
const currentIndex = projects.findIndex((p) => p.id === activeProjectId);
|
||||
if (currentIndex === -1 || projects.length === 0) return;
|
||||
|
||||
const nextIndex = e.shiftKey
|
||||
? (currentIndex - 1 + projects.length) % projects.length
|
||||
: (currentIndex + 1) % projects.length;
|
||||
onProjectSelect(projects[nextIndex].id);
|
||||
return;
|
||||
}
|
||||
|
||||
// Cmd/Ctrl + W: Close current tab (only if more than one tab)
|
||||
if (e.key === 'w' && activeProjectId && projects.length > 1) {
|
||||
e.preventDefault();
|
||||
onProjectClose(activeProjectId);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [projects, activeProjectId, onProjectSelect, onProjectClose]);
|
||||
|
||||
if (projects.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn(
|
||||
'flex items-center border-b border-border bg-background',
|
||||
'overflow-x-auto scrollbar-thin scrollbar-thumb-border scrollbar-track-transparent',
|
||||
className
|
||||
)}>
|
||||
<div className="flex items-center flex-1 min-w-0">
|
||||
{projects.map((project, index) => (
|
||||
<SortableProjectTab
|
||||
key={project.id}
|
||||
project={project}
|
||||
isActive={activeProjectId === project.id}
|
||||
canClose={projects.length > 1}
|
||||
tabIndex={index}
|
||||
onSelect={() => onProjectSelect(project.id)}
|
||||
onClose={(e) => {
|
||||
e.stopPropagation();
|
||||
onProjectClose(project.id);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center px-2 py-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={onAddProject}
|
||||
title="Add Project"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -93,7 +93,7 @@ export function RateLimitModal() {
|
||||
// Create a new profile - the backend will set the proper configDir
|
||||
const profileName = newProfileName.trim();
|
||||
const profileSlug = profileName.toLowerCase().replace(/\s+/g, '-');
|
||||
|
||||
|
||||
const result = await window.electronAPI.saveClaudeProfile({
|
||||
id: `profile-${Date.now()}`,
|
||||
name: profileName,
|
||||
@@ -106,14 +106,14 @@ export function RateLimitModal() {
|
||||
if (result.success && result.data) {
|
||||
// Initialize the profile (creates terminal and runs claude setup-token)
|
||||
const initResult = await window.electronAPI.initializeClaudeProfile(result.data.id);
|
||||
|
||||
|
||||
if (initResult.success) {
|
||||
// Reload profiles
|
||||
loadClaudeProfiles();
|
||||
setNewProfileName('');
|
||||
// Close the modal so user can see the terminal
|
||||
hideRateLimitModal();
|
||||
|
||||
|
||||
// Alert the user about the terminal
|
||||
alert(
|
||||
`A terminal has been opened to authenticate "${profileName}".\n\n` +
|
||||
@@ -216,7 +216,7 @@ export function RateLimitModal() {
|
||||
<User className="h-4 w-4" />
|
||||
{hasMultipleProfiles ? 'Switch Claude Account' : 'Use Another Account'}
|
||||
</h4>
|
||||
|
||||
|
||||
{hasMultipleProfiles ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useState } from 'react';
|
||||
import { RoadmapGenerationProgress } from './RoadmapGenerationProgress';
|
||||
import { CompetitorAnalysisDialog } from './CompetitorAnalysisDialog';
|
||||
import { ExistingCompetitorAnalysisDialog } from './ExistingCompetitorAnalysisDialog';
|
||||
import { CompetitorAnalysisViewer } from './CompetitorAnalysisViewer';
|
||||
import { AddFeatureDialog } from './AddFeatureDialog';
|
||||
import { RoadmapHeader } from './roadmap/RoadmapHeader';
|
||||
import { RoadmapEmptyState } from './roadmap/RoadmapEmptyState';
|
||||
import { RoadmapTabs } from './roadmap/RoadmapTabs';
|
||||
import { FeatureDetailPanel } from './roadmap/FeatureDetailPanel';
|
||||
import { useRoadmapData, useFeatureActions, useRoadmapGeneration } from './roadmap/hooks';
|
||||
import { useRoadmapData, useFeatureActions, useRoadmapGeneration, useRoadmapSave, useFeatureDelete } from './roadmap/hooks';
|
||||
import { getCompetitorInsightsForFeature } from './roadmap/utils';
|
||||
import type { RoadmapFeature } from '../../shared/types';
|
||||
import type { RoadmapProps } from './roadmap/types';
|
||||
@@ -15,14 +16,24 @@ import type { RoadmapProps } from './roadmap/types';
|
||||
export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
|
||||
// State management
|
||||
const [selectedFeature, setSelectedFeature] = useState<RoadmapFeature | null>(null);
|
||||
const [activeTab, setActiveTab] = useState('phases');
|
||||
const [activeTab, setActiveTab] = useState('kanban');
|
||||
const [showAddFeatureDialog, setShowAddFeatureDialog] = useState(false);
|
||||
const [showCompetitorViewer, setShowCompetitorViewer] = useState(false);
|
||||
|
||||
// Custom hooks
|
||||
const { roadmap, competitorAnalysis, generationStatus } = useRoadmapData(projectId);
|
||||
const { convertFeatureToSpec } = useFeatureActions();
|
||||
const { saveRoadmap } = useRoadmapSave(projectId);
|
||||
const { deleteFeature } = useFeatureDelete(projectId);
|
||||
const {
|
||||
competitorAnalysisDate,
|
||||
// New dialog for existing analysis
|
||||
showExistingAnalysisDialog,
|
||||
setShowExistingAnalysisDialog,
|
||||
handleUseExistingAnalysis,
|
||||
handleRunNewAnalysis,
|
||||
handleSkipAnalysis,
|
||||
// Original dialog for no existing analysis
|
||||
showCompetitorDialog,
|
||||
setShowCompetitorDialog,
|
||||
handleGenerate,
|
||||
@@ -61,12 +72,22 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
|
||||
return (
|
||||
<>
|
||||
<RoadmapEmptyState onGenerate={handleGenerate} />
|
||||
{/* Dialog for projects WITHOUT existing competitor analysis */}
|
||||
<CompetitorAnalysisDialog
|
||||
open={showCompetitorDialog}
|
||||
onOpenChange={setShowCompetitorDialog}
|
||||
onAccept={handleCompetitorDialogAccept}
|
||||
onDecline={handleCompetitorDialogDecline}
|
||||
/>
|
||||
{/* Dialog for projects WITH existing competitor analysis */}
|
||||
<ExistingCompetitorAnalysisDialog
|
||||
open={showExistingAnalysisDialog}
|
||||
onOpenChange={setShowExistingAnalysisDialog}
|
||||
onUseExisting={handleUseExistingAnalysis}
|
||||
onRunNew={handleRunNewAnalysis}
|
||||
onSkip={handleSkipAnalysis}
|
||||
analysisDate={competitorAnalysisDate}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -92,6 +113,7 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
|
||||
onFeatureSelect={setSelectedFeature}
|
||||
onConvertToSpec={handleConvertToSpec}
|
||||
onGoToTask={handleGoToTask}
|
||||
onSave={saveRoadmap}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -102,11 +124,12 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
|
||||
onClose={() => setSelectedFeature(null)}
|
||||
onConvertToSpec={handleConvertToSpec}
|
||||
onGoToTask={handleGoToTask}
|
||||
onDelete={deleteFeature}
|
||||
competitorInsights={getCompetitorInsightsForFeature(selectedFeature, competitorAnalysis)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Competitor Analysis Permission Dialog */}
|
||||
{/* Competitor Analysis Permission Dialog (no existing analysis) */}
|
||||
<CompetitorAnalysisDialog
|
||||
open={showCompetitorDialog}
|
||||
onOpenChange={setShowCompetitorDialog}
|
||||
@@ -114,6 +137,16 @@ export function Roadmap({ projectId, onGoToTask }: RoadmapProps) {
|
||||
onDecline={handleCompetitorDialogDecline}
|
||||
/>
|
||||
|
||||
{/* Competitor Analysis Options Dialog (existing analysis) */}
|
||||
<ExistingCompetitorAnalysisDialog
|
||||
open={showExistingAnalysisDialog}
|
||||
onOpenChange={setShowExistingAnalysisDialog}
|
||||
onUseExisting={handleUseExistingAnalysis}
|
||||
onRunNew={handleRunNewAnalysis}
|
||||
onSkip={handleSkipAnalysis}
|
||||
analysisDate={competitorAnalysisDate}
|
||||
/>
|
||||
|
||||
{/* Competitor Analysis Viewer */}
|
||||
<CompetitorAnalysisViewer
|
||||
analysis={competitorAnalysis}
|
||||
|
||||
@@ -204,7 +204,7 @@ export function RoadmapGenerationProgress({
|
||||
*/
|
||||
const handleStopClick = async () => {
|
||||
if (!onStop || isStopping) return;
|
||||
|
||||
|
||||
setIsStopping(true);
|
||||
try {
|
||||
await onStop();
|
||||
|
||||
@@ -18,17 +18,18 @@ import {
|
||||
verticalListSortingStrategy,
|
||||
arrayMove
|
||||
} from '@dnd-kit/sortable';
|
||||
import { Plus, Inbox } from 'lucide-react';
|
||||
import { Plus, Inbox, Eye, Calendar, Play, Check } from 'lucide-react';
|
||||
import { ScrollArea } from './ui/scroll-area';
|
||||
import { Badge } from './ui/badge';
|
||||
import { Card } from './ui/card';
|
||||
import { SortableFeatureCard } from './SortableFeatureCard';
|
||||
import { cn } from '../lib/utils';
|
||||
import { useRoadmapStore } from '../stores/roadmap-store';
|
||||
import {
|
||||
useRoadmapStore,
|
||||
getFeaturesByPhase
|
||||
} from '../stores/roadmap-store';
|
||||
import type { RoadmapFeature, RoadmapPhase, Roadmap } from '../../shared/types';
|
||||
ROADMAP_STATUS_COLUMNS,
|
||||
type RoadmapStatusColumn
|
||||
} from '../../shared/constants';
|
||||
import type { RoadmapFeature, RoadmapFeatureStatus, Roadmap } from '../../shared/types';
|
||||
|
||||
interface RoadmapKanbanViewProps {
|
||||
roadmap: Roadmap;
|
||||
@@ -38,37 +39,43 @@ interface RoadmapKanbanViewProps {
|
||||
onSave?: () => void;
|
||||
}
|
||||
|
||||
interface DroppablePhaseColumnProps {
|
||||
phase: RoadmapPhase;
|
||||
interface DroppableStatusColumnProps {
|
||||
column: RoadmapStatusColumn;
|
||||
features: RoadmapFeature[];
|
||||
roadmap: Roadmap;
|
||||
onFeatureClick: (feature: RoadmapFeature) => void;
|
||||
onConvertToSpec?: (feature: RoadmapFeature) => void;
|
||||
onGoToTask?: (specId: string) => void;
|
||||
isOver: boolean;
|
||||
}
|
||||
|
||||
// Get phase status color for column header
|
||||
function getPhaseStatusColor(status: string): string {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
return 'border-t-success';
|
||||
case 'in_progress':
|
||||
return 'border-t-primary';
|
||||
// Get icon component for status
|
||||
function getStatusIcon(iconName: string) {
|
||||
switch (iconName) {
|
||||
case 'Eye':
|
||||
return <Eye className="h-3.5 w-3.5" />;
|
||||
case 'Calendar':
|
||||
return <Calendar className="h-3.5 w-3.5" />;
|
||||
case 'Play':
|
||||
return <Play className="h-3.5 w-3.5" />;
|
||||
case 'Check':
|
||||
return <Check className="h-3.5 w-3.5" />;
|
||||
default:
|
||||
return 'border-t-muted-foreground/30';
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function DroppablePhaseColumn({
|
||||
phase,
|
||||
function DroppableStatusColumn({
|
||||
column,
|
||||
features,
|
||||
roadmap,
|
||||
onFeatureClick,
|
||||
onConvertToSpec,
|
||||
onGoToTask,
|
||||
isOver
|
||||
}: DroppablePhaseColumnProps) {
|
||||
}: DroppableStatusColumnProps) {
|
||||
const { setNodeRef } = useDroppable({
|
||||
id: phase.id
|
||||
id: column.id
|
||||
});
|
||||
|
||||
const featureIds = features.map((f) => f.id);
|
||||
@@ -78,7 +85,7 @@ function DroppablePhaseColumn({
|
||||
ref={setNodeRef}
|
||||
className={cn(
|
||||
'flex min-w-80 w-80 shrink-0 flex-col rounded-xl border border-white/5 bg-linear-to-b from-secondary/30 to-transparent backdrop-blur-sm transition-all duration-200',
|
||||
getPhaseStatusColor(phase.status),
|
||||
column.color,
|
||||
'border-t-2',
|
||||
isOver && 'drop-zone-highlight'
|
||||
)}
|
||||
@@ -87,29 +94,26 @@ function DroppablePhaseColumn({
|
||||
<div className="flex items-center justify-between p-4 border-b border-white/5">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div
|
||||
className={`w-6 h-6 rounded-full flex items-center justify-center text-xs font-semibold ${
|
||||
phase.status === 'completed'
|
||||
className={cn(
|
||||
'w-6 h-6 rounded-full flex items-center justify-center',
|
||||
column.id === 'done'
|
||||
? 'bg-success/10 text-success'
|
||||
: phase.status === 'in_progress'
|
||||
: column.id === 'in_progress'
|
||||
? 'bg-primary/10 text-primary'
|
||||
: column.id === 'planned'
|
||||
? 'bg-info/10 text-info'
|
||||
: 'bg-muted text-muted-foreground'
|
||||
}`}
|
||||
)}
|
||||
>
|
||||
{phase.order}
|
||||
{getStatusIcon(column.icon)}
|
||||
</div>
|
||||
<h2 className="font-semibold text-sm text-foreground truncate max-w-[180px]">
|
||||
{phase.name}
|
||||
<h2 className="font-semibold text-sm text-foreground">
|
||||
{column.label}
|
||||
</h2>
|
||||
<span className="column-count-badge">
|
||||
{features.length}
|
||||
</span>
|
||||
</div>
|
||||
<Badge
|
||||
variant={phase.status === 'completed' ? 'default' : 'outline'}
|
||||
className="text-xs"
|
||||
>
|
||||
{phase.status.replace('_', ' ')}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* Features list */}
|
||||
@@ -151,6 +155,7 @@ function DroppablePhaseColumn({
|
||||
<SortableFeatureCard
|
||||
key={feature.id}
|
||||
feature={feature}
|
||||
roadmap={roadmap}
|
||||
onClick={() => onFeatureClick(feature)}
|
||||
onConvertToSpec={onConvertToSpec}
|
||||
onGoToTask={onGoToTask}
|
||||
@@ -175,8 +180,7 @@ export function RoadmapKanbanView({
|
||||
const [activeFeature, setActiveFeature] = useState<RoadmapFeature | null>(null);
|
||||
const [overColumnId, setOverColumnId] = useState<string | null>(null);
|
||||
|
||||
const reorderFeatures = useRoadmapStore((state) => state.reorderFeatures);
|
||||
const updateFeaturePhase = useRoadmapStore((state) => state.updateFeaturePhase);
|
||||
const updateFeatureStatus = useRoadmapStore((state) => state.updateFeatureStatus);
|
||||
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, {
|
||||
@@ -189,17 +193,17 @@ export function RoadmapKanbanView({
|
||||
})
|
||||
);
|
||||
|
||||
// Get features grouped by phase
|
||||
const featuresByPhase = useMemo(() => {
|
||||
// Get features grouped by status
|
||||
const featuresByStatus = useMemo(() => {
|
||||
const grouped: Record<string, RoadmapFeature[]> = {};
|
||||
roadmap.phases.forEach((phase) => {
|
||||
grouped[phase.id] = getFeaturesByPhase(roadmap, phase.id);
|
||||
ROADMAP_STATUS_COLUMNS.forEach((column) => {
|
||||
grouped[column.id] = roadmap.features.filter((f) => f.status === column.id);
|
||||
});
|
||||
return grouped;
|
||||
}, [roadmap]);
|
||||
}, [roadmap.features]);
|
||||
|
||||
// Get all phase IDs for detecting column drops
|
||||
const phaseIds = useMemo(() => roadmap.phases.map((p) => p.id), [roadmap.phases]);
|
||||
// Get all status IDs for detecting column drops
|
||||
const statusIds = useMemo(() => ROADMAP_STATUS_COLUMNS.map((c) => c.id), []);
|
||||
|
||||
const handleDragStart = (event: DragStartEvent) => {
|
||||
const { active } = event;
|
||||
@@ -219,16 +223,16 @@ export function RoadmapKanbanView({
|
||||
|
||||
const overId = over.id as string;
|
||||
|
||||
// Check if over a phase column
|
||||
if (phaseIds.includes(overId)) {
|
||||
// Check if over a status column
|
||||
if (statusIds.includes(overId)) {
|
||||
setOverColumnId(overId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if over a feature - get its phase
|
||||
// Check if over a feature - get its status
|
||||
const overFeature = roadmap.features.find((f) => f.id === overId);
|
||||
if (overFeature) {
|
||||
setOverColumnId(overFeature.phaseId);
|
||||
setOverColumnId(overFeature.status);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -245,59 +249,36 @@ export function RoadmapKanbanView({
|
||||
|
||||
if (!draggedFeature) return;
|
||||
|
||||
// Determine target phase
|
||||
let targetPhaseId: string;
|
||||
let targetFeatureIndex: number = -1;
|
||||
// Determine target status
|
||||
let targetStatus: RoadmapFeatureStatus;
|
||||
|
||||
if (phaseIds.includes(overId)) {
|
||||
// Dropped directly on a phase column
|
||||
targetPhaseId = overId;
|
||||
if (statusIds.includes(overId)) {
|
||||
// Dropped directly on a status column
|
||||
targetStatus = overId as RoadmapFeatureStatus;
|
||||
} else {
|
||||
// Dropped on a feature - get its phase and position
|
||||
// Dropped on a feature - get its status
|
||||
const overFeature = roadmap.features.find((f) => f.id === overId);
|
||||
if (!overFeature) return;
|
||||
targetPhaseId = overFeature.phaseId;
|
||||
const targetFeatures = featuresByPhase[targetPhaseId] || [];
|
||||
targetFeatureIndex = targetFeatures.findIndex((f) => f.id === overId);
|
||||
targetStatus = overFeature.status;
|
||||
}
|
||||
|
||||
const sourcePhaseId = draggedFeature.phaseId;
|
||||
const sourceStatus = draggedFeature.status;
|
||||
|
||||
if (sourcePhaseId !== targetPhaseId) {
|
||||
// Moving to a different phase
|
||||
updateFeaturePhase(activeFeatureId, targetPhaseId);
|
||||
|
||||
// If dropped on a specific feature, reorder within the new phase
|
||||
if (targetFeatureIndex !== -1) {
|
||||
const targetFeatures = [...(featuresByPhase[targetPhaseId] || [])];
|
||||
// Add the moved feature at the target position
|
||||
const updatedIds = targetFeatures.map((f) => f.id);
|
||||
if (!updatedIds.includes(activeFeatureId)) {
|
||||
updatedIds.splice(targetFeatureIndex, 0, activeFeatureId);
|
||||
reorderFeatures(targetPhaseId, updatedIds);
|
||||
}
|
||||
}
|
||||
if (sourceStatus !== targetStatus) {
|
||||
// Moving to a different status
|
||||
updateFeatureStatus(activeFeatureId, targetStatus);
|
||||
|
||||
// Trigger save callback
|
||||
onSave?.();
|
||||
} else {
|
||||
// Reordering within the same phase
|
||||
const sourceFeatures = featuresByPhase[sourcePhaseId] || [];
|
||||
const oldIndex = sourceFeatures.findIndex((f) => f.id === activeFeatureId);
|
||||
const newIndex = targetFeatureIndex !== -1 ? targetFeatureIndex : sourceFeatures.length - 1;
|
||||
|
||||
if (oldIndex !== newIndex) {
|
||||
const reorderedIds = arrayMove(
|
||||
sourceFeatures.map((f) => f.id),
|
||||
oldIndex,
|
||||
newIndex
|
||||
);
|
||||
reorderFeatures(sourcePhaseId, reorderedIds);
|
||||
|
||||
// Trigger save callback
|
||||
onSave?.();
|
||||
}
|
||||
}
|
||||
// Note: We don't support reordering within status columns for now
|
||||
// Features are displayed in their natural order within each status
|
||||
};
|
||||
|
||||
// Get status label for a feature (for display in drag overlay)
|
||||
const getStatusLabelForFeature = (feature: RoadmapFeature) => {
|
||||
const statusColumn = ROADMAP_STATUS_COLUMNS.find((c) => c.id === feature.status);
|
||||
return statusColumn?.label || 'Unknown Status';
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -311,19 +292,18 @@ export function RoadmapKanbanView({
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
<div className="flex flex-1 gap-4 overflow-x-auto p-6">
|
||||
{roadmap.phases
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((phase) => (
|
||||
<DroppablePhaseColumn
|
||||
key={phase.id}
|
||||
phase={phase}
|
||||
features={featuresByPhase[phase.id] || []}
|
||||
onFeatureClick={onFeatureClick}
|
||||
onConvertToSpec={onConvertToSpec}
|
||||
onGoToTask={onGoToTask}
|
||||
isOver={overColumnId === phase.id}
|
||||
/>
|
||||
))}
|
||||
{ROADMAP_STATUS_COLUMNS.map((column) => (
|
||||
<DroppableStatusColumn
|
||||
key={column.id}
|
||||
column={column}
|
||||
features={featuresByStatus[column.id] || []}
|
||||
roadmap={roadmap}
|
||||
onFeatureClick={onFeatureClick}
|
||||
onConvertToSpec={onConvertToSpec}
|
||||
onGoToTask={onGoToTask}
|
||||
isOver={overColumnId === column.id}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Drag overlay - enhanced visual feedback */}
|
||||
@@ -331,6 +311,11 @@ export function RoadmapKanbanView({
|
||||
{activeFeature ? (
|
||||
<div className="drag-overlay-card">
|
||||
<Card className="p-4 w-80 shadow-2xl">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Badge variant="outline" className="text-[10px] px-1.5 py-0">
|
||||
{getStatusLabelForFeature(activeFeature)}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="font-medium">{activeFeature.title}</div>
|
||||
<p className="text-sm text-muted-foreground line-clamp-2 mt-1">
|
||||
{activeFeature.description}
|
||||
|
||||
@@ -139,7 +139,7 @@ export function SDKRateLimitModal() {
|
||||
// Create a new profile - the backend will set the proper configDir
|
||||
const profileName = newProfileName.trim();
|
||||
const profileSlug = profileName.toLowerCase().replace(/\s+/g, '-');
|
||||
|
||||
|
||||
const result = await window.electronAPI.saveClaudeProfile({
|
||||
id: `profile-${Date.now()}`,
|
||||
name: profileName,
|
||||
@@ -152,14 +152,14 @@ export function SDKRateLimitModal() {
|
||||
if (result.success && result.data) {
|
||||
// Initialize the profile (creates terminal and runs claude setup-token)
|
||||
const initResult = await window.electronAPI.initializeClaudeProfile(result.data.id);
|
||||
|
||||
|
||||
if (initResult.success) {
|
||||
// Reload profiles
|
||||
loadClaudeProfiles();
|
||||
setNewProfileName('');
|
||||
// Close the modal so user can see the terminal
|
||||
hideSDKRateLimitModal();
|
||||
|
||||
|
||||
// Alert the user about the terminal
|
||||
alert(
|
||||
`A terminal has been opened to authenticate "${profileName}".\n\n` +
|
||||
@@ -312,7 +312,7 @@ export function SDKRateLimitModal() {
|
||||
<User className="h-4 w-4" />
|
||||
{hasMultipleProfiles ? 'Switch Account & Retry' : 'Use Another Account'}
|
||||
</h4>
|
||||
|
||||
|
||||
{hasMultipleProfiles ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
FolderOpen,
|
||||
Plus,
|
||||
Settings,
|
||||
Trash2,
|
||||
@@ -21,13 +20,6 @@ import {
|
||||
import { Button } from './ui/button';
|
||||
import { ScrollArea } from './ui/scroll-area';
|
||||
import { Separator } from './ui/separator';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from './ui/select';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
@@ -255,13 +247,6 @@ export function Sidebar({
|
||||
await removeProject(projectId);
|
||||
};
|
||||
|
||||
const handleProjectChange = (projectId: string) => {
|
||||
if (projectId === '__add_new__') {
|
||||
handleAddProject();
|
||||
} else {
|
||||
selectProject(projectId);
|
||||
}
|
||||
};
|
||||
|
||||
const handleNavClick = (view: SidebarView) => {
|
||||
onViewChange?.(view);
|
||||
@@ -304,67 +289,6 @@ export function Sidebar({
|
||||
|
||||
<Separator className="mt-2" />
|
||||
|
||||
{/* Project Selector Dropdown */}
|
||||
<div className="px-4 py-4">
|
||||
<Select
|
||||
value={selectedProjectId || ''}
|
||||
onValueChange={handleProjectChange}
|
||||
>
|
||||
<SelectTrigger className="w-full [&_span]:truncate">
|
||||
<div className="flex items-center gap-2 min-w-0 flex-1 overflow-hidden">
|
||||
<FolderOpen className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<SelectValue placeholder="Select a project..." className="truncate min-w-0 flex-1" />
|
||||
</div>
|
||||
</SelectTrigger>
|
||||
<SelectContent className="min-w-(--radix-select-trigger-width) max-w-(--radix-select-trigger-width)">
|
||||
{projects.length === 0 ? (
|
||||
<div className="px-2 py-4 text-center text-sm text-muted-foreground">
|
||||
<p>No projects yet</p>
|
||||
</div>
|
||||
) : (
|
||||
projects.map((project) => (
|
||||
<div key={project.id} className="relative flex items-center">
|
||||
<SelectItem value={project.id} className="flex-1 pr-10">
|
||||
<span className="truncate" title={`${project.name} - ${project.path}`}>
|
||||
{project.name}
|
||||
</span>
|
||||
</SelectItem>
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 flex h-6 w-6 items-center justify-center rounded-md hover:bg-destructive/10 transition-colors"
|
||||
onPointerDown={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
removeProject(project.id);
|
||||
}}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 text-destructive" />
|
||||
</button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
<Separator className="my-1" />
|
||||
<SelectItem value="__add_new__">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4 shrink-0" />
|
||||
<span>Add Project...</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{/* Project path - shown when project is selected */}
|
||||
{selectedProject && (
|
||||
<div className="mt-2">
|
||||
<span className="truncate block text-xs text-muted-foreground" title={selectedProject.path}>
|
||||
{selectedProject.path}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
|
||||
@@ -9,17 +9,18 @@ import {
|
||||
TooltipContent,
|
||||
TooltipTrigger
|
||||
} from './ui/tooltip';
|
||||
import { Play, ExternalLink, TrendingUp } from 'lucide-react';
|
||||
import { Play, ExternalLink, TrendingUp, Layers, ThumbsUp } from 'lucide-react';
|
||||
import {
|
||||
ROADMAP_PRIORITY_COLORS,
|
||||
ROADMAP_PRIORITY_LABELS,
|
||||
ROADMAP_COMPLEXITY_COLORS,
|
||||
ROADMAP_IMPACT_COLORS
|
||||
} from '../../shared/constants';
|
||||
import type { RoadmapFeature } from '../../shared/types';
|
||||
import type { RoadmapFeature, Roadmap } from '../../shared/types';
|
||||
|
||||
interface SortableFeatureCardProps {
|
||||
feature: RoadmapFeature;
|
||||
roadmap?: Roadmap;
|
||||
onClick: () => void;
|
||||
onConvertToSpec?: (feature: RoadmapFeature) => void;
|
||||
onGoToTask?: (specId: string) => void;
|
||||
@@ -27,6 +28,7 @@ interface SortableFeatureCardProps {
|
||||
|
||||
export function SortableFeatureCard({
|
||||
feature,
|
||||
roadmap,
|
||||
onClick,
|
||||
onConvertToSpec,
|
||||
onGoToTask
|
||||
@@ -51,6 +53,12 @@ export function SortableFeatureCard({
|
||||
const hasCompetitorInsight =
|
||||
!!feature.competitorInsightIds && feature.competitorInsightIds.length > 0;
|
||||
|
||||
// Get phase name for the feature
|
||||
const phaseName = roadmap?.phases.find((p) => p.id === feature.phaseId)?.name;
|
||||
|
||||
// Check if feature has external source (e.g., Canny)
|
||||
const isExternal = feature.source?.provider && feature.source.provider !== 'internal';
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
@@ -70,13 +78,29 @@ export function SortableFeatureCard({
|
||||
{/* Header - Title with priority badge and action button */}
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-1.5 mb-1">
|
||||
<div className="flex items-center gap-1.5 mb-1 flex-wrap">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn('text-[10px] px-1.5 py-0', ROADMAP_PRIORITY_COLORS[feature.priority])}
|
||||
>
|
||||
{ROADMAP_PRIORITY_LABELS[feature.priority]}
|
||||
</Badge>
|
||||
{phaseName && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] px-1.5 py-0 text-muted-foreground border-muted-foreground/30"
|
||||
>
|
||||
<Layers className="h-2.5 w-2.5 mr-0.5" />
|
||||
{phaseName.length > 12 ? `${phaseName.slice(0, 12)}...` : phaseName}
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
Phase: {phaseName}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{hasCompetitorInsight && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
@@ -135,7 +159,7 @@ export function SortableFeatureCard({
|
||||
</p>
|
||||
|
||||
{/* Metadata badges - compact row */}
|
||||
<div className="mt-2 flex items-center gap-1.5">
|
||||
<div className="mt-2 flex items-center gap-1.5 flex-wrap">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn('text-[10px] px-1.5 py-0', ROADMAP_COMPLEXITY_COLORS[feature.complexity])}
|
||||
@@ -148,6 +172,39 @@ export function SortableFeatureCard({
|
||||
>
|
||||
{feature.impact}
|
||||
</Badge>
|
||||
{/* Show vote count if from external source */}
|
||||
{feature.votes !== undefined && feature.votes > 0 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] px-1.5 py-0 text-muted-foreground"
|
||||
>
|
||||
<ThumbsUp className="h-2.5 w-2.5 mr-0.5" />
|
||||
{feature.votes}
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{feature.votes} votes from user feedback
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{/* Show external source indicator */}
|
||||
{isExternal && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] px-1.5 py-0 text-orange-500 border-orange-500/30"
|
||||
>
|
||||
{feature.source?.provider === 'canny' ? 'Canny' : 'External'}
|
||||
</Badge>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
Imported from {feature.source?.provider}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import { useSortable } from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { cn } from '../lib/utils';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
|
||||
import type { Project } from '../../shared/types';
|
||||
|
||||
interface SortableProjectTabProps {
|
||||
project: Project;
|
||||
isActive: boolean;
|
||||
canClose: boolean;
|
||||
tabIndex: number;
|
||||
onSelect: () => void;
|
||||
onClose: (e: React.MouseEvent) => void;
|
||||
}
|
||||
|
||||
// Detect if running on macOS for keyboard shortcut display
|
||||
const isMac = typeof navigator !== 'undefined' && navigator.platform.toUpperCase().indexOf('MAC') >= 0;
|
||||
const modKey = isMac ? '⌘' : 'Ctrl+';
|
||||
|
||||
export function SortableProjectTab({
|
||||
project,
|
||||
isActive,
|
||||
canClose,
|
||||
tabIndex,
|
||||
onSelect,
|
||||
onClose
|
||||
}: SortableProjectTabProps) {
|
||||
// Build tooltip with keyboard shortcut hint (only for tabs 1-9)
|
||||
const shortcutHint = tabIndex < 9 ? `${modKey}${tabIndex + 1}` : '';
|
||||
const closeShortcut = `${modKey}W`;
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging
|
||||
} = useSortable({ id: project.id });
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
// Prevent z-index stacking issues during drag
|
||||
zIndex: isDragging ? 50 : undefined
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
className={cn(
|
||||
'group relative flex items-center min-w-0 max-w-[200px]',
|
||||
'border-r border-border last:border-r-0',
|
||||
'touch-none transition-all duration-200',
|
||||
isDragging && 'opacity-60 scale-[0.98] shadow-lg'
|
||||
)}
|
||||
{...attributes}
|
||||
>
|
||||
<Tooltip delayDuration={200}>
|
||||
<TooltipTrigger asChild>
|
||||
<div
|
||||
className={cn(
|
||||
'flex-1 flex items-center gap-2 px-4 py-2.5 text-sm',
|
||||
'min-w-0 truncate hover:bg-muted/50 transition-colors',
|
||||
'border-b-2 border-transparent cursor-pointer',
|
||||
isActive && [
|
||||
'bg-background border-b-primary text-foreground',
|
||||
'hover:bg-background'
|
||||
],
|
||||
!isActive && [
|
||||
'text-muted-foreground',
|
||||
'hover:text-foreground'
|
||||
]
|
||||
)}
|
||||
onClick={onSelect}
|
||||
>
|
||||
{/* Drag handle - visible on hover */}
|
||||
<div
|
||||
{...listeners}
|
||||
className={cn(
|
||||
'opacity-0 group-hover:opacity-60 transition-opacity',
|
||||
'cursor-grab active:cursor-grabbing',
|
||||
'w-1 h-4 bg-muted-foreground rounded-full'
|
||||
)}
|
||||
/>
|
||||
<span className="truncate font-medium">
|
||||
{project.name}
|
||||
</span>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" className="flex items-center gap-2">
|
||||
<span>{project.name}</span>
|
||||
{shortcutHint && (
|
||||
<kbd className="px-1.5 py-0.5 text-xs bg-muted rounded border border-border font-mono">
|
||||
{shortcutHint}
|
||||
</kbd>
|
||||
)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{canClose && (
|
||||
<Tooltip delayDuration={200}>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
className={cn(
|
||||
'h-6 w-6 p-0 mr-1 opacity-0 group-hover:opacity-100',
|
||||
'transition-opacity duration-200 rounded',
|
||||
'hover:bg-destructive hover:text-destructive-foreground',
|
||||
'flex items-center justify-center',
|
||||
isActive && 'opacity-100'
|
||||
)}
|
||||
onClick={onClose}
|
||||
>
|
||||
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom" className="flex items-center gap-2">
|
||||
<span>Close tab</span>
|
||||
<kbd className="px-1.5 py-0.5 text-xs bg-muted rounded border border-border font-mono">
|
||||
{closeShortcut}
|
||||
</kbd>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -45,7 +45,7 @@ export function TaskCard({ task, onClick }: TaskCardProps) {
|
||||
const isRunning = task.status === 'in_progress';
|
||||
const executionPhase = task.executionProgress?.phase;
|
||||
const hasActiveExecution = executionPhase && executionPhase !== 'idle' && executionPhase !== 'complete' && executionPhase !== 'failed';
|
||||
|
||||
|
||||
// Check if task is in human_review but has no completed subtasks (crashed/incomplete)
|
||||
const isIncomplete = isIncompleteHumanReview(task);
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user