Compare commits
75 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 92b7534db6 | |||
| 76fdbade6f | |||
| 979d97757f | |||
| 3f8e16edb2 | |||
| 86dadb3981 | |||
| 53b55468c9 | |||
| d6360e492c | |||
| 1984a62d9b | |||
| dcdd75376d | |||
| 48f8396bdd | |||
| 33107fcd91 | |||
| eb20eed304 | |||
| 8f3ea8f311 | |||
| 7da21d131e | |||
| 7705c563bb | |||
| 13a48e26e1 | |||
| dcc6afad2d | |||
| 7896be5f69 | |||
| be83ad46f6 | |||
| 5eac6d8d0f | |||
| 7a1db877f9 | |||
| 7a39253214 | |||
| 60bdf51aef | |||
| b437dc6f30 | |||
| 2e56176514 | |||
| dfa08dc588 | |||
| a8f7519a53 | |||
| 302233b31c | |||
| 80170562a4 | |||
| 4e2a614112 | |||
| db5eff4b9b | |||
| b188fed7e2 | |||
| 7fd0b4be38 | |||
| de04b81d60 | |||
| f2d2b0b680 | |||
| 8b279bf1ff | |||
| 9492440460 | |||
| 86da9ee6dd | |||
| 228a58a87c | |||
| af4c7fe89e | |||
| cd3fb11239 | |||
| 5d50a87d3c | |||
| d45c2033fc | |||
| 5236d6285b | |||
| 186940964a | |||
| 94621fde2b | |||
| f64d5decd1 | |||
| 0d727a3b91 | |||
| 7af1c57e20 | |||
| be78dc6849 | |||
| fb6c666706 | |||
| 35585053cd | |||
| 74d95d14a9 | |||
| efce7cdd46 | |||
| d5a276ebfa | |||
| 532458546f | |||
| 63c608b38f | |||
| a91163200d | |||
| 571bf51b33 | |||
| e4c517c09f | |||
| 11ed33569c | |||
| f21610a8b2 | |||
| 011a24239e | |||
| 9a11866f12 | |||
| 13c07f0a51 | |||
| b470b367bf | |||
| 42469a75df | |||
| 11299f59cb | |||
| c14e2fbaa2 | |||
| 8e29eb03ec | |||
| 53d24262e1 | |||
| a5670a6912 | |||
| d958fa65cb | |||
| bec3fc88a2 | |||
| 1308ec1433 |
@@ -338,7 +338,7 @@ jobs:
|
||||
run: |
|
||||
set -e
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y flatpak flatpak-builder libarchive-tools
|
||||
sudo apt-get install -y flatpak flatpak-builder squashfs-tools
|
||||
flatpak remote-add --user --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
|
||||
flatpak install -y --user flathub org.freedesktop.Platform//25.08 org.freedesktop.Sdk//25.08
|
||||
flatpak install -y --user flathub org.electronjs.Electron2.BaseApp//25.08
|
||||
|
||||
@@ -34,6 +34,7 @@ concurrency:
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
# --------------------------------------------------------------------------
|
||||
@@ -61,9 +62,35 @@ jobs:
|
||||
working-directory: apps/desktop
|
||||
run: npm run typecheck
|
||||
|
||||
- name: Run unit tests
|
||||
- name: Run unit tests with coverage
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
working-directory: apps/desktop
|
||||
run: npm run test
|
||||
run: npm run test:coverage
|
||||
|
||||
- name: Run unit tests
|
||||
if: matrix.os != 'ubuntu-latest'
|
||||
working-directory: apps/desktop
|
||||
run: npm run test:unit
|
||||
|
||||
- name: Run integration tests
|
||||
working-directory: apps/desktop
|
||||
run: npm run test:integration
|
||||
|
||||
- name: Upload coverage report
|
||||
if: matrix.os == 'ubuntu-latest' && always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: coverage-report
|
||||
path: apps/desktop/coverage/
|
||||
retention-days: 14
|
||||
|
||||
- name: Coverage PR comment
|
||||
if: matrix.os == 'ubuntu-latest' && github.event_name == 'pull_request'
|
||||
uses: davelosert/vitest-coverage-report-action@v2
|
||||
with:
|
||||
working-directory: apps/desktop
|
||||
json-summary-path: coverage/coverage-summary.json
|
||||
json-final-path: coverage/coverage-final.json
|
||||
|
||||
- name: Build application
|
||||
working-directory: apps/desktop
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# E2E Tests
|
||||
#
|
||||
# Runs Playwright E2E tests for the Electron desktop app on Linux.
|
||||
# Ubuntu-only since Electron E2E is platform-agnostic (Chromium renderer).
|
||||
# Non-blocking initially — separate from ci-complete gate while stabilizing.
|
||||
|
||||
name: E2E
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, develop]
|
||||
paths:
|
||||
- 'apps/**'
|
||||
- '.github/workflows/e2e.yml'
|
||||
pull_request:
|
||||
branches: [main, develop]
|
||||
paths:
|
||||
- 'apps/**'
|
||||
- '.github/workflows/e2e.yml'
|
||||
|
||||
concurrency:
|
||||
group: e2e-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
name: E2E Tests
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js frontend
|
||||
uses: ./.github/actions/setup-node-frontend
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: apps/desktop
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Build application
|
||||
working-directory: apps/desktop
|
||||
run: npm run build
|
||||
|
||||
- name: Run E2E tests
|
||||
working-directory: apps/desktop
|
||||
continue-on-error: true # Non-blocking while stabilizing — pre-existing __dirname ESM issue
|
||||
run: xvfb-run --auto-servernum npm run test:e2e
|
||||
|
||||
- name: Upload E2E report
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-report
|
||||
path: |
|
||||
apps/desktop/e2e/playwright-report/
|
||||
apps/desktop/e2e/test-results/
|
||||
retention-days: 14
|
||||
@@ -276,7 +276,7 @@ jobs:
|
||||
- name: Setup Flatpak and verification tools
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y flatpak flatpak-builder libarchive-tools
|
||||
sudo apt-get install -y flatpak flatpak-builder squashfs-tools
|
||||
flatpak remote-add --user --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
|
||||
flatpak install -y --user flathub org.freedesktop.Platform//25.08 org.freedesktop.Sdk//25.08
|
||||
flatpak install -y --user flathub org.electronjs.Electron2.BaseApp//25.08
|
||||
@@ -572,9 +572,9 @@ jobs:
|
||||
IS_PRERELEASE="${{ steps.version.outputs.is_prerelease }}"
|
||||
|
||||
if [ "$IS_PRERELEASE" = "true" ]; then
|
||||
python3 scripts/update-readme.py "$VERSION" --prerelease
|
||||
node scripts/update-readme.mjs "$VERSION" --prerelease
|
||||
else
|
||||
python3 scripts/update-readme.py "$VERSION"
|
||||
node scripts/update-readme.mjs "$VERSION"
|
||||
fi
|
||||
|
||||
echo "--- Verifying update ---"
|
||||
|
||||
@@ -36,18 +36,18 @@
|
||||
> ⚠️ Beta releases may contain bugs and breaking changes. [View all releases](https://github.com/AndyMik90/Auto-Claude/releases)
|
||||
|
||||
<!-- BETA_VERSION_BADGE -->
|
||||
[](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.8.0-beta.1)
|
||||
[](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.8.0-beta.5)
|
||||
<!-- BETA_VERSION_BADGE_END -->
|
||||
|
||||
<!-- BETA_DOWNLOADS -->
|
||||
| Platform | Download |
|
||||
|----------|----------|
|
||||
| **Windows** | [Auto-Claude-2.8.0-beta.1-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.8.0-beta.1/Auto-Claude-2.8.0-beta.1-win32-x64.exe) |
|
||||
| **macOS (Apple Silicon)** | [Auto-Claude-2.8.0-beta.1-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.8.0-beta.1/Auto-Claude-2.8.0-beta.1-darwin-arm64.dmg) |
|
||||
| **macOS (Intel)** | [Auto-Claude-2.8.0-beta.1-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.8.0-beta.1/Auto-Claude-2.8.0-beta.1-darwin-x64.dmg) |
|
||||
| **Linux** | [Auto-Claude-2.8.0-beta.1-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.8.0-beta.1/Auto-Claude-2.8.0-beta.1-linux-x86_64.AppImage) |
|
||||
| **Linux (Debian)** | [Auto-Claude-2.8.0-beta.1-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.8.0-beta.1/Auto-Claude-2.8.0-beta.1-linux-amd64.deb) |
|
||||
| **Linux (Flatpak)** | [Auto-Claude-2.8.0-beta.1-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.8.0-beta.1/Auto-Claude-2.8.0-beta.1-linux-x86_64.flatpak) |
|
||||
| **Windows** | [Aperant-2.8.0-beta.5-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.8.0-beta.5/Aperant-2.8.0-beta.5-win32-x64.exe) |
|
||||
| **macOS (Apple Silicon)** | [Aperant-2.8.0-beta.5-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.8.0-beta.5/Aperant-2.8.0-beta.5-darwin-arm64.dmg) |
|
||||
| **macOS (Intel)** | [Aperant-2.8.0-beta.5-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.8.0-beta.5/Aperant-2.8.0-beta.5-darwin-x64.dmg) |
|
||||
| **Linux** | [Aperant-2.8.0-beta.5-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.8.0-beta.5/Aperant-2.8.0-beta.5-linux-x86_64.AppImage) |
|
||||
| **Linux (Debian)** | [Aperant-2.8.0-beta.5-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.8.0-beta.5/Aperant-2.8.0-beta.5-linux-amd64.deb) |
|
||||
| **Linux (Flatpak)** | [Aperant-2.8.0-beta.5-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.8.0-beta.5/Aperant-2.8.0-beta.5-linux-x86_64.flatpak) |
|
||||
<!-- BETA_DOWNLOADS_END -->
|
||||
|
||||
> All releases include SHA256 checksums and VirusTotal scan results for security verification.
|
||||
|
||||
@@ -45,7 +45,8 @@
|
||||
"noProcessEnv": "off",
|
||||
"useNodejsImportProtocol": "off",
|
||||
"useImportType": "off",
|
||||
"useTemplate": "off"
|
||||
"useTemplate": "off",
|
||||
"noNonNullAssertion": "warn"
|
||||
},
|
||||
"suspicious": {
|
||||
"recommended": true,
|
||||
|
||||
@@ -78,7 +78,9 @@ export default defineConfig({
|
||||
// spawned via `new Worker(path)` from WorkerBridge
|
||||
'ai/agent/worker': resolve(__dirname, 'src/main/ai/agent/worker.ts'),
|
||||
},
|
||||
// Only node-pty needs to be external (native module rebuilt by electron-builder)
|
||||
// Native modules that must remain external (loaded from disk, not bundled).
|
||||
// @libsql/client is loaded lazily via globalThis.require() and resolved
|
||||
// from extraResources/node_modules via Module.globalPaths (see index.ts).
|
||||
external: ['@lydell/node-pty']
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "auto-claude-ui",
|
||||
"name": "aperant",
|
||||
"version": "2.8.0-beta.1",
|
||||
"type": "module",
|
||||
"description": "Desktop UI for Auto Claude autonomous coding framework",
|
||||
"homepage": "https://github.com/AndyMik90/Auto-Claude",
|
||||
"description": "Autonomous multi-agent coding framework",
|
||||
"homepage": "https://github.com/AndyMik90/Aperant",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/AndyMik90/Auto-Claude.git"
|
||||
"url": "https://github.com/AndyMik90/Aperant.git"
|
||||
},
|
||||
"main": "./out/main/index.js",
|
||||
"author": {
|
||||
"name": "Auto Claude Team",
|
||||
"name": "Aperant Team",
|
||||
"email": "119136210+AndyMik90@users.noreply.github.com"
|
||||
},
|
||||
"license": "AGPL-3.0",
|
||||
@@ -35,10 +35,12 @@
|
||||
"package:flatpak": "electron-builder --linux flatpak",
|
||||
"verify:linux": "node scripts/verify-linux-packages.cjs dist",
|
||||
"test:verify-linux": "node --test scripts/verify-linux-packages.test.mjs",
|
||||
"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",
|
||||
"start:packaged:mac": "open dist/mac-arm64/Aperant.app || open dist/mac/Aperant.app",
|
||||
"start:packaged:win": "start \"\" \"dist\\win-unpacked\\Aperant.exe\"",
|
||||
"start:packaged:linux": "./dist/linux-unpacked/aperant",
|
||||
"test": "vitest run",
|
||||
"test:unit": "vitest run --exclude src/__tests__/integration/ --exclude src/__tests__/e2e/",
|
||||
"test:integration": "vitest run src/__tests__/integration/",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"test:e2e": "npx playwright test --config=e2e/playwright.config.ts",
|
||||
@@ -48,27 +50,27 @@
|
||||
"typecheck": "tsc --noEmit --incremental"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/amazon-bedrock": "^4.0.61",
|
||||
"@ai-sdk/anthropic": "^3.0.45",
|
||||
"@ai-sdk/azure": "^3.0.31",
|
||||
"@ai-sdk/google": "^3.0.29",
|
||||
"@ai-sdk/groq": "^3.0.24",
|
||||
"@ai-sdk/mcp": "^1.0.21",
|
||||
"@ai-sdk/mistral": "^2.0.28",
|
||||
"@ai-sdk/openai": "^3.0.30",
|
||||
"@ai-sdk/openai-compatible": "^2.0.30",
|
||||
"@ai-sdk/xai": "^3.0.57",
|
||||
"@anthropic-ai/sdk": "^0.71.2",
|
||||
"@ai-sdk/amazon-bedrock": "^4.0.77",
|
||||
"@ai-sdk/anthropic": "^3.0.58",
|
||||
"@ai-sdk/azure": "^3.0.42",
|
||||
"@ai-sdk/google": "^3.0.43",
|
||||
"@ai-sdk/groq": "^3.0.29",
|
||||
"@ai-sdk/mcp": "^1.0.25",
|
||||
"@ai-sdk/mistral": "^3.0.24",
|
||||
"@ai-sdk/openai": "^3.0.41",
|
||||
"@ai-sdk/openai-compatible": "^2.0.35",
|
||||
"@ai-sdk/xai": "^3.0.67",
|
||||
"@anthropic-ai/sdk": "^0.78.0",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@libsql/client": "^0.17.0",
|
||||
"@lydell/node-pty": "^1.1.0",
|
||||
"@modelcontextprotocol/sdk": "^1.26.0",
|
||||
"@openrouter/ai-sdk-provider": "^2.2.3",
|
||||
"@modelcontextprotocol/sdk": "^1.27.1",
|
||||
"@openrouter/ai-sdk-provider": "^2.3.1",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.15",
|
||||
"@radix-ui/react-checkbox": "^1.1.4",
|
||||
"@radix-ui/react-collapsible": "^1.1.3",
|
||||
"@radix-ui/react-checkbox": "^1.3.3",
|
||||
"@radix-ui/react-collapsible": "^1.1.12",
|
||||
"@radix-ui/react-dialog": "^1.1.15",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.16",
|
||||
"@radix-ui/react-popover": "^1.1.15",
|
||||
@@ -82,88 +84,89 @@
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@radix-ui/react-toast": "^1.2.15",
|
||||
"@radix-ui/react-tooltip": "^1.2.8",
|
||||
"@sentry/electron": "^7.5.0",
|
||||
"@sentry/electron": "^7.10.0",
|
||||
"@tailwindcss/typography": "^0.5.19",
|
||||
"@tanstack/react-virtual": "^3.13.13",
|
||||
"@tanstack/react-virtual": "^3.13.22",
|
||||
"@tavily/core": "^0.7.2",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-serialize": "^0.14.0",
|
||||
"@xterm/addon-web-links": "^0.12.0",
|
||||
"@xterm/addon-webgl": "^0.19.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"ai": "^6.0.91",
|
||||
"ai": "^6.0.116",
|
||||
"chokidar": "^5.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"dotenv": "^17.2.3",
|
||||
"dotenv": "^17.3.1",
|
||||
"electron-log": "^5.4.3",
|
||||
"electron-updater": "^6.6.2",
|
||||
"i18next": "^25.7.3",
|
||||
"lucide-react": "^0.562.0",
|
||||
"minimatch": "^10.1.1",
|
||||
"motion": "^12.23.26",
|
||||
"electron-updater": "^6.8.3",
|
||||
"i18next": "^25.8.18",
|
||||
"lucide-react": "^0.577.0",
|
||||
"minimatch": "^10.2.4",
|
||||
"motion": "^12.36.0",
|
||||
"proper-lockfile": "^4.1.2",
|
||||
"react": "^19.2.3",
|
||||
"react-dom": "^19.2.3",
|
||||
"react-i18next": "^16.5.0",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"react-i18next": "^16.5.8",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-raw": "^7.0.0",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"semver": "^7.7.3",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"semver": "^7.7.4",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"uuid": "^13.0.0",
|
||||
"web-tree-sitter": "^0.26.5",
|
||||
"xstate": "^5.26.0",
|
||||
"zod": "^4.2.1",
|
||||
"zustand": "^5.0.9"
|
||||
"web-tree-sitter": "^0.26.7",
|
||||
"xstate": "^5.28.0",
|
||||
"zod": "^4.3.6",
|
||||
"zustand": "^5.0.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "2.3.11",
|
||||
"@biomejs/biome": "2.4.7",
|
||||
"@electron-toolkit/preload": "^3.0.2",
|
||||
"@electron-toolkit/utils": "^4.0.0",
|
||||
"@electron/rebuild": "^4.0.2",
|
||||
"@playwright/test": "^1.52.0",
|
||||
"@tailwindcss/postcss": "^4.1.17",
|
||||
"@testing-library/dom": "^10.0.0",
|
||||
"@electron/rebuild": "^4.0.3",
|
||||
"@playwright/test": "^1.58.2",
|
||||
"@tailwindcss/postcss": "^4.2.1",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.1.0",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@types/minimatch": "^6.0.0",
|
||||
"@types/node": "^25.0.0",
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/node": "^25.5.0",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/semver": "^7.7.1",
|
||||
"@types/uuid": "^11.0.0",
|
||||
"@vitejs/plugin-react": "^5.1.2",
|
||||
"autoprefixer": "^10.4.22",
|
||||
"@vitest/coverage-v8": "^4.1.0",
|
||||
"autoprefixer": "^10.4.27",
|
||||
"cross-env": "^10.1.0",
|
||||
"electron": "40.0.0",
|
||||
"electron-builder": "^26.4.0",
|
||||
"electron-builder": "^26.8.1",
|
||||
"electron-vite": "^5.0.0",
|
||||
"husky": "^9.1.7",
|
||||
"jsdom": "^27.3.0",
|
||||
"lint-staged": "^16.2.7",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "^4.1.17",
|
||||
"lint-staged": "^16.4.0",
|
||||
"postcss": "^8.5.8",
|
||||
"tailwindcss": "^4.2.1",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^7.2.7",
|
||||
"vitest": "^4.0.16"
|
||||
"vitest": "^4.1.0"
|
||||
},
|
||||
"overrides": {
|
||||
"electron-builder-squirrel-windows": "^26.0.12",
|
||||
"dmg-builder": "^26.0.12",
|
||||
"@electron/rebuild": "4.0.2"
|
||||
"@electron/rebuild": "4.0.3"
|
||||
},
|
||||
"build": {
|
||||
"appId": "com.autoclaude.ui",
|
||||
"productName": "Auto-Claude",
|
||||
"appId": "com.aperant.app",
|
||||
"productName": "Aperant",
|
||||
"npmRebuild": false,
|
||||
"artifactName": "${productName}-${version}-${platform}-${arch}.${ext}",
|
||||
"publish": [
|
||||
{
|
||||
"provider": "github",
|
||||
"owner": "AndyMik90",
|
||||
"repo": "Auto-Claude"
|
||||
"repo": "Aperant"
|
||||
}
|
||||
],
|
||||
"directories": {
|
||||
@@ -185,6 +188,22 @@
|
||||
{
|
||||
"from": "prompts",
|
||||
"to": "prompts"
|
||||
},
|
||||
{
|
||||
"from": "../../node_modules/@libsql",
|
||||
"to": "node_modules/@libsql"
|
||||
},
|
||||
{
|
||||
"from": "../../node_modules/libsql",
|
||||
"to": "node_modules/libsql"
|
||||
},
|
||||
{
|
||||
"from": "../../node_modules/@neon-rs",
|
||||
"to": "node_modules/@neon-rs"
|
||||
},
|
||||
{
|
||||
"from": "../../node_modules/detect-libc",
|
||||
"to": "node_modules/detect-libc"
|
||||
}
|
||||
],
|
||||
"mac": {
|
||||
|
||||
|
Before Width: | Height: | Size: 84 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 74 KiB After Width: | Height: | Size: 275 KiB |
|
Before Width: | Height: | Size: 20 MiB After Width: | Height: | Size: 236 KiB |
|
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 6.6 KiB |
|
Before Width: | Height: | Size: 921 B After Width: | Height: | Size: 455 B |
|
Before Width: | Height: | Size: 80 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 290 KiB After Width: | Height: | Size: 64 KiB |
|
Before Width: | Height: | Size: 6.9 KiB After Width: | Height: | Size: 2.5 KiB |
@@ -123,36 +123,102 @@ function verifyFileList(files, packageType) {
|
||||
};
|
||||
}
|
||||
|
||||
// Minimum expected AppImage file size (50 MB)
|
||||
const APPIMAGE_MIN_SIZE_MB = 50;
|
||||
|
||||
/**
|
||||
* Verify AppImage contents using bsdtar (libarchive)
|
||||
* Verify AppImage contents.
|
||||
* AppImages are ELF executables with an embedded SquashFS filesystem.
|
||||
* We try unsquashfs first (can list SquashFS contents), then fall back
|
||||
* to the AppImage's own --appimage-extract, and finally to a size check.
|
||||
*/
|
||||
function verifyAppImage(appImagePath) {
|
||||
logInfo(`Verifying AppImage: ${path.basename(appImagePath)}`);
|
||||
|
||||
if (!commandExists('bsdtar')) {
|
||||
logWarning('bsdtar not found. Install with: sudo apt-get install libarchive-tools');
|
||||
logWarning('Skipping AppImage verification');
|
||||
return { verified: false, reason: 'bsdtar not available', critical: true };
|
||||
// Try unsquashfs -l (lists squashfs contents without extracting)
|
||||
if (commandExists('unsquashfs')) {
|
||||
const result = spawnSync('unsquashfs', ['-l', appImagePath], {
|
||||
stdio: 'pipe',
|
||||
encoding: 'utf-8',
|
||||
maxBuffer: 50 * 1024 * 1024,
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
logWarning(`unsquashfs failed: ${result.error.message}, falling back to size check`);
|
||||
} else if (result.status !== 0) {
|
||||
logWarning(`unsquashfs could not read AppImage, falling back to size check`);
|
||||
} else {
|
||||
const files = result.stdout.split('\n');
|
||||
return verifyFileList(files, 'AppImage');
|
||||
}
|
||||
}
|
||||
|
||||
const result = spawnSync('bsdtar', ['-t', '-f', appImagePath], {
|
||||
// Try self-extraction to list contents (AppImages support --appimage-extract-and-run)
|
||||
// Make the AppImage executable first
|
||||
try {
|
||||
fs.chmodSync(appImagePath, 0o755);
|
||||
} catch (_) {
|
||||
// Ignore chmod errors
|
||||
}
|
||||
|
||||
const extractResult = spawnSync(appImagePath, ['--appimage-extract', '--stdout'], {
|
||||
stdio: 'pipe',
|
||||
encoding: 'utf-8',
|
||||
maxBuffer: 50 * 1024 * 1024,
|
||||
timeout: 30000,
|
||||
env: { ...process.env, APPIMAGE_EXTRACT_AND_RUN: '1' },
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
logError(`Failed to execute bsdtar: ${result.error.message}`);
|
||||
return { verified: false, issues: [`Command execution failed: ${result.error.message}`] };
|
||||
// --appimage-extract creates a squashfs-root directory; check if it exists
|
||||
const squashfsRoot = path.join(path.dirname(appImagePath), 'squashfs-root');
|
||||
if (fs.existsSync(squashfsRoot)) {
|
||||
try {
|
||||
const collectFiles = (dir, prefix = '') => {
|
||||
const entries = [];
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
|
||||
entries.push(rel);
|
||||
if (entry.isDirectory()) {
|
||||
entries.push(...collectFiles(path.join(dir, entry.name), rel));
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
};
|
||||
const files = collectFiles(squashfsRoot);
|
||||
const verifyResult = verifyFileList(files, 'AppImage');
|
||||
// Clean up extracted directory
|
||||
fs.rmSync(squashfsRoot, { recursive: true, force: true });
|
||||
return verifyResult;
|
||||
} catch (e) {
|
||||
logWarning(`Failed to read extracted AppImage contents: ${e.message}`);
|
||||
fs.rmSync(squashfsRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
if (result.status !== 0) {
|
||||
logError(`Failed to read AppImage: ${result.stderr}`);
|
||||
return { verified: false, issues: ['Failed to extract file list'] };
|
||||
// Fall back to basic size validation (same approach as Flatpak)
|
||||
logWarning('Could not inspect AppImage contents (unsquashfs not available). Using size validation.');
|
||||
const issues = [];
|
||||
const stats = fs.statSync(appImagePath);
|
||||
|
||||
if (stats.size === 0) {
|
||||
return { verified: false, issues: ['AppImage file is empty'] };
|
||||
}
|
||||
|
||||
const files = result.stdout.split('\n');
|
||||
return verifyFileList(files, 'AppImage');
|
||||
if (stats.size < APPIMAGE_MIN_SIZE_MB * 1024 * 1024) {
|
||||
issues.push(
|
||||
`AppImage file seems too small (${(stats.size / 1024 / 1024).toFixed(2)} MB, expected at least ${APPIMAGE_MIN_SIZE_MB} MB)`,
|
||||
);
|
||||
}
|
||||
|
||||
if (issues.length === 0) {
|
||||
logInfo('AppImage passed size validation (content inspection was not possible)');
|
||||
}
|
||||
|
||||
return {
|
||||
verified: issues.length === 0,
|
||||
issues,
|
||||
size: stats.size,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -315,7 +381,7 @@ function main() {
|
||||
if (hasCriticalSkips) {
|
||||
log('Some packages could not be verified due to missing required tools.\n', colors.red);
|
||||
log('Install required tools:\n', colors.red);
|
||||
log(' - bsdtar: sudo apt-get install libarchive-tools\n', colors.red);
|
||||
log(' - unsquashfs: sudo apt-get install squashfs-tools\n', colors.red);
|
||||
log(' - dpkg-deb: sudo apt-get install dpkg\n', colors.red);
|
||||
}
|
||||
process.exit(1);
|
||||
|
||||
@@ -7,17 +7,20 @@ import { EventEmitter } from 'events';
|
||||
// Mock app
|
||||
export const app = {
|
||||
getPath: vi.fn((name: string) => {
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const paths: Record<string, string> = {
|
||||
userData: '/tmp/test-app-data',
|
||||
home: '/tmp/test-home',
|
||||
temp: '/tmp'
|
||||
userData: path.join(os.homedir(), '.aperant-test-data'),
|
||||
home: os.homedir(),
|
||||
temp: os.tmpdir()
|
||||
};
|
||||
return paths[name] || '/tmp';
|
||||
return paths[name] || path.join(os.homedir(), '.aperant-test');
|
||||
}),
|
||||
getAppPath: vi.fn(() => '/tmp/test-app'),
|
||||
getVersion: vi.fn(() => '0.1.0'),
|
||||
isPackaged: false,
|
||||
on: vi.fn(),
|
||||
whenReady: vi.fn(() => Promise.resolve()),
|
||||
quit: vi.fn()
|
||||
};
|
||||
|
||||
|
||||
@@ -209,7 +209,6 @@ describe('Claude Profile IPC Integration', () => {
|
||||
|
||||
await handleProfileSave?.(null, profile);
|
||||
|
||||
// biome-ignore lint/style/noNonNullAssertion: Test file - configDir is set in createTestProfile
|
||||
expect(existsSync(profile.configDir!)).toBe(true);
|
||||
});
|
||||
|
||||
@@ -224,7 +223,6 @@ describe('Claude Profile IPC Integration', () => {
|
||||
|
||||
await handleProfileSave?.(null, profile);
|
||||
|
||||
// biome-ignore lint/style/noNonNullAssertion: Test file - configDir is set in createTestProfile
|
||||
expect(existsSync(profile.configDir!)).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -302,7 +302,7 @@ describe('Application Logger', () => {
|
||||
const { generateDebugReport } = await import('../app-logger');
|
||||
const report = generateDebugReport();
|
||||
|
||||
expect(report).toContain('=== Auto Claude Debug Report ===');
|
||||
expect(report).toContain('=== Aperant Debug Report ===');
|
||||
expect(report).toContain('--- System Information ---');
|
||||
expect(report).toContain('--- Recent Errors ---');
|
||||
expect(report).toContain('=== End Debug Report ===');
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* Tests for ensureOnboardingComplete function in cli-integration-handler.ts
|
||||
*
|
||||
* Tests the exported ensureOnboardingComplete() which reads/writes .claude.json
|
||||
* to set hasCompletedOnboarding: true, suppressing Claude's onboarding wizard
|
||||
* for already-authenticated profiles.
|
||||
*/
|
||||
|
||||
import { describe, test, expect, vi, beforeEach } from 'vitest';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
|
||||
// ---- fs mock (sync only — the function uses fs, not fs/promises) ----
|
||||
const mockFiles: Map<string, string | Error> = new Map();
|
||||
|
||||
vi.mock('fs', () => {
|
||||
const readFileSync = vi.fn((filePath: string, _encoding?: string): string => {
|
||||
const entry = mockFiles.get(filePath);
|
||||
if (entry === undefined) {
|
||||
const err = new Error(`ENOENT: no such file or directory, open '${filePath}'`) as NodeJS.ErrnoException;
|
||||
err.code = 'ENOENT';
|
||||
throw err;
|
||||
}
|
||||
if (entry instanceof Error) {
|
||||
throw entry;
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
|
||||
const writeFileSync = vi.fn();
|
||||
const renameSync = vi.fn();
|
||||
|
||||
return { default: { readFileSync, writeFileSync, renameSync }, readFileSync, writeFileSync, renameSync };
|
||||
});
|
||||
|
||||
// ---- stubs for heavy transitive dependencies ----
|
||||
vi.mock('electron', () => ({
|
||||
ipcMain: { handle: vi.fn() },
|
||||
app: { getPath: vi.fn(() => os.tmpdir()), getAppPath: vi.fn(() => os.tmpdir()) },
|
||||
dialog: { showOpenDialog: vi.fn() },
|
||||
shell: { openExternal: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: true } }));
|
||||
|
||||
vi.mock('../../shared/constants', async () => {
|
||||
const actual = await vi.importActual<typeof import('../../shared/constants')>('../../shared/constants');
|
||||
return { ...actual };
|
||||
});
|
||||
|
||||
vi.mock('../claude-profile-manager', () => ({
|
||||
getClaudeProfileManager: vi.fn(),
|
||||
initializeClaudeProfileManager: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../claude-profile/credential-utils', () => ({
|
||||
getFullCredentialsFromKeychain: vi.fn(),
|
||||
clearKeychainCache: vi.fn(),
|
||||
updateProfileSubscriptionMetadata: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../claude-profile/usage-monitor', () => ({
|
||||
getUsageMonitor: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../claude-profile/profile-utils', () => ({
|
||||
getEmailFromConfigDir: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../terminal/output-parser', () => ({}));
|
||||
vi.mock('../terminal/session-handler', () => ({}));
|
||||
|
||||
vi.mock('./pty-manager', () => ({
|
||||
writeToPty: vi.fn(),
|
||||
resizePty: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../ipc-handlers/utils', () => ({
|
||||
safeSendToRenderer: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../shared/utils/debug-logger', () => ({
|
||||
debugLog: vi.fn(),
|
||||
debugError: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../shared/utils/shell-escape', () => ({
|
||||
escapeShellArg: vi.fn((s: string) => s),
|
||||
escapeForWindowsDoubleQuote: vi.fn((s: string) => s),
|
||||
buildCdCommand: vi.fn((cwd: string) => `cd ${cwd}`),
|
||||
}));
|
||||
|
||||
vi.mock('../cli-utils', () => ({
|
||||
getClaudeCliInvocation: vi.fn(() => 'claude'),
|
||||
getClaudeCliInvocationAsync: vi.fn(async () => 'claude'),
|
||||
}));
|
||||
|
||||
vi.mock('../platform', () => ({
|
||||
isWindows: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
vi.mock('../settings-utils', () => ({
|
||||
readSettingsFileAsync: vi.fn(async () => ({})),
|
||||
readSettingsFile: vi.fn(() => ({})),
|
||||
}));
|
||||
|
||||
// ---- import the function under test ----
|
||||
import { ensureOnboardingComplete } from '../terminal/cli-integration-handler';
|
||||
import * as fs from 'fs';
|
||||
|
||||
// ---- helpers ----
|
||||
function claudeJsonPath(configDir: string): string {
|
||||
const expanded = configDir.startsWith('~')
|
||||
? configDir.replace(/^~/, os.homedir())
|
||||
: configDir;
|
||||
return path.join(path.resolve(expanded), '.claude.json');
|
||||
}
|
||||
|
||||
const TEST_DIR = '/tmp/test-profile';
|
||||
|
||||
describe('ensureOnboardingComplete', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockFiles.clear();
|
||||
});
|
||||
|
||||
// ---- ENOENT: file does not exist ----
|
||||
test('returns early (no write) when .claude.json does not exist', () => {
|
||||
// mockFiles is empty → readFileSync will throw ENOENT
|
||||
ensureOnboardingComplete(TEST_DIR);
|
||||
|
||||
expect(fs.writeFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// ---- already set ----
|
||||
test('returns early (no write) when hasCompletedOnboarding is already true', () => {
|
||||
const filePath = claudeJsonPath(TEST_DIR);
|
||||
mockFiles.set(filePath, JSON.stringify({ hasCompletedOnboarding: true }));
|
||||
|
||||
ensureOnboardingComplete(TEST_DIR);
|
||||
|
||||
expect(fs.writeFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// ---- missing flag → should write ----
|
||||
test('writes hasCompletedOnboarding: true when flag is absent', () => {
|
||||
const filePath = claudeJsonPath(TEST_DIR);
|
||||
mockFiles.set(filePath, JSON.stringify({ someOtherField: 'value' }));
|
||||
|
||||
ensureOnboardingComplete(TEST_DIR);
|
||||
|
||||
expect(fs.writeFileSync).toHaveBeenCalledOnce();
|
||||
const written = JSON.parse((fs.writeFileSync as ReturnType<typeof vi.fn>).mock.calls[0][1] as string);
|
||||
expect(written.hasCompletedOnboarding).toBe(true);
|
||||
expect(written.someOtherField).toBe('value');
|
||||
});
|
||||
|
||||
// ---- flag is false → should write ----
|
||||
test('writes hasCompletedOnboarding: true when flag is false', () => {
|
||||
const filePath = claudeJsonPath(TEST_DIR);
|
||||
mockFiles.set(filePath, JSON.stringify({ hasCompletedOnboarding: false }));
|
||||
|
||||
ensureOnboardingComplete(TEST_DIR);
|
||||
|
||||
expect(fs.writeFileSync).toHaveBeenCalledOnce();
|
||||
const written = JSON.parse((fs.writeFileSync as ReturnType<typeof vi.fn>).mock.calls[0][1] as string);
|
||||
expect(written.hasCompletedOnboarding).toBe(true);
|
||||
});
|
||||
|
||||
// ---- non-object JSON (string) → should return silently ----
|
||||
test('returns early (no write) when .claude.json contains a JSON string', () => {
|
||||
const filePath = claudeJsonPath(TEST_DIR);
|
||||
mockFiles.set(filePath, JSON.stringify('just a string'));
|
||||
|
||||
ensureOnboardingComplete(TEST_DIR);
|
||||
|
||||
expect(fs.writeFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// ---- array JSON → should return silently ----
|
||||
test('returns early (no write) when .claude.json contains a JSON array', () => {
|
||||
const filePath = claudeJsonPath(TEST_DIR);
|
||||
mockFiles.set(filePath, JSON.stringify([1, 2, 3]));
|
||||
|
||||
ensureOnboardingComplete(TEST_DIR);
|
||||
|
||||
expect(fs.writeFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// ---- corrupted / invalid JSON → outer catch swallows error ----
|
||||
test('handles corrupted JSON gracefully without throwing', () => {
|
||||
const filePath = claudeJsonPath(TEST_DIR);
|
||||
mockFiles.set(filePath, '{ invalid json }');
|
||||
|
||||
expect(() => ensureOnboardingComplete(TEST_DIR)).not.toThrow();
|
||||
expect(fs.writeFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// ---- tilde expansion ----
|
||||
test('expands leading tilde to home directory', () => {
|
||||
const tildeDir = '~/myprofile';
|
||||
const resolvedDir = path.resolve(tildeDir.replace(/^~/, os.homedir()));
|
||||
const filePath = path.join(resolvedDir, '.claude.json');
|
||||
|
||||
mockFiles.set(filePath, JSON.stringify({}));
|
||||
|
||||
ensureOnboardingComplete(tildeDir);
|
||||
|
||||
expect(fs.writeFileSync).toHaveBeenCalledOnce();
|
||||
// Writes to a temp file (claudeJsonPath + UUID + .tmp), then renames to target
|
||||
const writtenPath = (fs.writeFileSync as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;
|
||||
expect(writtenPath).toMatch(new RegExp(`^${filePath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\..*\\.tmp$`));
|
||||
expect(fs.renameSync).toHaveBeenCalledWith(writtenPath, filePath);
|
||||
});
|
||||
|
||||
// ---- write error → outer catch swallows error ----
|
||||
test('handles write error gracefully without throwing', () => {
|
||||
const filePath = claudeJsonPath(TEST_DIR);
|
||||
mockFiles.set(filePath, JSON.stringify({}));
|
||||
|
||||
(fs.writeFileSync as ReturnType<typeof vi.fn>).mockImplementationOnce(() => {
|
||||
throw new Error('EACCES: permission denied');
|
||||
});
|
||||
|
||||
expect(() => ensureOnboardingComplete(TEST_DIR)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -40,8 +40,8 @@ const __dirname = path.dirname(__filename);
|
||||
*/
|
||||
function resolveWorkerPath(): string {
|
||||
if (app.isPackaged) {
|
||||
// Production: worker is bundled alongside other main-process code
|
||||
return path.join(process.resourcesPath, 'app', 'main', 'ai', 'agent', 'worker.js');
|
||||
// Production: worker is inside app.asar at out/main/ai/agent/worker.js
|
||||
return path.join(process.resourcesPath, 'app.asar', 'out', 'main', 'ai', 'agent', 'worker.js');
|
||||
}
|
||||
// Dev: electron-vite outputs worker at out/main/ai/agent/worker.js
|
||||
// because the Rollup input key is 'ai/agent/worker'.
|
||||
|
||||
@@ -0,0 +1,507 @@
|
||||
/**
|
||||
* Tests for AI Auth Resolver
|
||||
*
|
||||
* Validates the multi-stage credential resolution fallback chain,
|
||||
* provider account resolution, settings accessor registration,
|
||||
* environment variable fallback, and Z.AI endpoint routing.
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
// Mock token-refresh before importing resolver
|
||||
// Path resolution from src/main/ai/auth/__tests__/:
|
||||
// ../ = src/main/ai/auth/
|
||||
// ../../ = src/main/ai/
|
||||
// ../../../ = src/main/
|
||||
// So ../../../claude-profile/ = src/main/claude-profile/
|
||||
vi.mock('../../../claude-profile/token-refresh', () => ({
|
||||
ensureValidToken: vi.fn(),
|
||||
reactiveTokenRefresh: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock profile-scorer
|
||||
vi.mock('../../../claude-profile/profile-scorer', () => ({
|
||||
scoreProviderAccount: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock model equivalence
|
||||
// ../../../../shared/ = src/shared/ (4 levels up from __tests__ = src/)
|
||||
vi.mock('../../../../shared/constants/models', () => ({
|
||||
resolveModelEquivalent: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock provider factory detection
|
||||
// ../../providers/ = src/main/ai/providers/
|
||||
vi.mock('../../providers/factory', () => ({
|
||||
detectProviderFromModel: vi.fn(),
|
||||
}));
|
||||
|
||||
import { ensureValidToken, reactiveTokenRefresh } from '../../../claude-profile/token-refresh';
|
||||
import { scoreProviderAccount } from '../../../claude-profile/profile-scorer';
|
||||
import { resolveModelEquivalent } from '../../../../shared/constants/models';
|
||||
import { detectProviderFromModel } from '../../providers/factory';
|
||||
import {
|
||||
resolveAuth,
|
||||
hasCredentials,
|
||||
registerSettingsAccessor,
|
||||
refreshOAuthTokenReactive,
|
||||
resolveAuthFromQueue,
|
||||
buildDefaultQueueConfig,
|
||||
} from '../resolver';
|
||||
|
||||
const mockEnsureValidToken = vi.mocked(ensureValidToken);
|
||||
const mockReactiveTokenRefresh = vi.mocked(reactiveTokenRefresh);
|
||||
const mockScoreProviderAccount = vi.mocked(scoreProviderAccount);
|
||||
const mockResolveModelEquivalent = vi.mocked(resolveModelEquivalent);
|
||||
const _mockDetectProviderFromModel = vi.mocked(detectProviderFromModel);
|
||||
|
||||
// Helper: reset the module-level settings accessor between tests
|
||||
function clearSettingsAccessor() {
|
||||
registerSettingsAccessor(() => undefined);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
clearSettingsAccessor();
|
||||
// Clean up any environment variable side effects
|
||||
delete process.env.ANTHROPIC_API_KEY;
|
||||
delete process.env.OPENAI_API_KEY;
|
||||
delete process.env.ANTHROPIC_BASE_URL;
|
||||
delete process.env.OPENAI_BASE_URL;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.ANTHROPIC_API_KEY;
|
||||
delete process.env.OPENAI_API_KEY;
|
||||
delete process.env.ANTHROPIC_BASE_URL;
|
||||
delete process.env.OPENAI_BASE_URL;
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// registerSettingsAccessor
|
||||
// =============================================================================
|
||||
|
||||
describe('registerSettingsAccessor', () => {
|
||||
it('wires up settings so subsequent calls read from the accessor', async () => {
|
||||
registerSettingsAccessor((key) => (key === 'globalAnthropicApiKey' ? 'sk-from-settings' : undefined));
|
||||
|
||||
const auth = await resolveAuth({ provider: 'anthropic' });
|
||||
expect(auth).not.toBeNull();
|
||||
expect(auth?.apiKey).toBe('sk-from-settings');
|
||||
expect(auth?.source).toBe('profile-api-key');
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// Stage 1: Profile OAuth Token
|
||||
// =============================================================================
|
||||
|
||||
describe('resolveAuth — Stage 1: Profile OAuth', () => {
|
||||
it('returns oauth token for anthropic when ensureValidToken resolves', async () => {
|
||||
mockEnsureValidToken.mockResolvedValueOnce({ token: 'oauth-token-abc', wasRefreshed: false });
|
||||
|
||||
const auth = await resolveAuth({ provider: 'anthropic', configDir: '/home/.config/claude' });
|
||||
|
||||
expect(auth).not.toBeNull();
|
||||
expect(auth?.apiKey).toBe('oauth-token-abc');
|
||||
expect(auth?.source).toBe('profile-oauth');
|
||||
expect(auth?.headers).toMatchObject({ 'anthropic-beta': expect.stringContaining('oauth') });
|
||||
});
|
||||
|
||||
it('includes custom base URL when ANTHROPIC_BASE_URL is set', async () => {
|
||||
process.env.ANTHROPIC_BASE_URL = 'https://proxy.example.com';
|
||||
mockEnsureValidToken.mockResolvedValueOnce({ token: 'oauth-token-abc', wasRefreshed: false });
|
||||
|
||||
const auth = await resolveAuth({ provider: 'anthropic' });
|
||||
|
||||
expect(auth?.baseURL).toBe('https://proxy.example.com');
|
||||
});
|
||||
|
||||
it('skips oauth stage for non-anthropic providers', async () => {
|
||||
// openai has no oauth stage; should fall through to environment
|
||||
process.env.OPENAI_API_KEY = 'sk-env-openai';
|
||||
|
||||
const auth = await resolveAuth({ provider: 'openai' });
|
||||
|
||||
expect(mockEnsureValidToken).not.toHaveBeenCalled();
|
||||
expect(auth?.source).toBe('environment');
|
||||
});
|
||||
|
||||
it('falls through when ensureValidToken throws', async () => {
|
||||
mockEnsureValidToken.mockRejectedValueOnce(new Error('keychain locked'));
|
||||
process.env.ANTHROPIC_API_KEY = 'sk-env-fallback';
|
||||
|
||||
const auth = await resolveAuth({ provider: 'anthropic' });
|
||||
|
||||
expect(auth?.apiKey).toBe('sk-env-fallback');
|
||||
expect(auth?.source).toBe('environment');
|
||||
});
|
||||
|
||||
it('falls through when ensureValidToken returns no token', async () => {
|
||||
mockEnsureValidToken.mockResolvedValueOnce({ token: null, wasRefreshed: false });
|
||||
process.env.ANTHROPIC_API_KEY = 'sk-env-fallback';
|
||||
|
||||
const auth = await resolveAuth({ provider: 'anthropic' });
|
||||
|
||||
expect(auth?.source).toBe('environment');
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// Stage 2: Profile API Key (from settings)
|
||||
// =============================================================================
|
||||
|
||||
describe('resolveAuth — Stage 2: Profile API Key', () => {
|
||||
it('returns api-key from settings when no oauth token available', async () => {
|
||||
mockEnsureValidToken.mockResolvedValueOnce({ token: null, wasRefreshed: false });
|
||||
registerSettingsAccessor((key) => (key === 'globalAnthropicApiKey' ? 'sk-settings-key' : undefined));
|
||||
|
||||
const auth = await resolveAuth({ provider: 'anthropic' });
|
||||
|
||||
expect(auth?.apiKey).toBe('sk-settings-key');
|
||||
expect(auth?.source).toBe('profile-api-key');
|
||||
});
|
||||
|
||||
it('includes base URL from environment even for settings-based keys', async () => {
|
||||
process.env.ANTHROPIC_BASE_URL = 'https://custom.proxy.io';
|
||||
mockEnsureValidToken.mockResolvedValueOnce({ token: null, wasRefreshed: false });
|
||||
registerSettingsAccessor((key) => (key === 'globalAnthropicApiKey' ? 'sk-settings' : undefined));
|
||||
|
||||
const auth = await resolveAuth({ provider: 'anthropic' });
|
||||
|
||||
expect(auth?.baseURL).toBe('https://custom.proxy.io');
|
||||
});
|
||||
|
||||
it('returns null from settings stage when accessor returns nothing', async () => {
|
||||
mockEnsureValidToken.mockResolvedValueOnce({ token: null, wasRefreshed: false });
|
||||
// settings accessor returns undefined for everything, env also not set
|
||||
const auth = await resolveAuth({ provider: 'anthropic' });
|
||||
expect(auth).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// Stage 3: Environment Variable
|
||||
// =============================================================================
|
||||
|
||||
describe('resolveAuth — Stage 3: Environment Variable', () => {
|
||||
it('returns env key for openai', async () => {
|
||||
process.env.OPENAI_API_KEY = 'sk-env-openai-123';
|
||||
|
||||
const auth = await resolveAuth({ provider: 'openai' });
|
||||
|
||||
expect(auth?.apiKey).toBe('sk-env-openai-123');
|
||||
expect(auth?.source).toBe('environment');
|
||||
});
|
||||
|
||||
it('includes base URL from env when OPENAI_BASE_URL is set', async () => {
|
||||
process.env.OPENAI_API_KEY = 'sk-env-openai';
|
||||
process.env.OPENAI_BASE_URL = 'https://openai-proxy.com';
|
||||
|
||||
const auth = await resolveAuth({ provider: 'openai' });
|
||||
|
||||
expect(auth?.baseURL).toBe('https://openai-proxy.com');
|
||||
});
|
||||
|
||||
it('returns null for bedrock (no env var defined)', async () => {
|
||||
const auth = await resolveAuth({ provider: 'bedrock' });
|
||||
expect(auth).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// Stage 4: Default Credentials (no-auth providers)
|
||||
// =============================================================================
|
||||
|
||||
describe('resolveAuth — Stage 4: Default Credentials', () => {
|
||||
it('returns empty api key for ollama', async () => {
|
||||
const auth = await resolveAuth({ provider: 'ollama' });
|
||||
|
||||
expect(auth).not.toBeNull();
|
||||
expect(auth?.apiKey).toBe('');
|
||||
expect(auth?.source).toBe('default');
|
||||
});
|
||||
|
||||
it('returns null for unknown provider with no credentials', async () => {
|
||||
const auth = await resolveAuth({ provider: 'groq' });
|
||||
expect(auth).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// hasCredentials
|
||||
// =============================================================================
|
||||
|
||||
describe('hasCredentials', () => {
|
||||
it('returns true when credentials resolve', async () => {
|
||||
process.env.OPENAI_API_KEY = 'sk-test';
|
||||
expect(await hasCredentials({ provider: 'openai' })).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true for ollama (no-auth)', async () => {
|
||||
expect(await hasCredentials({ provider: 'ollama' })).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false when no credentials available', async () => {
|
||||
expect(await hasCredentials({ provider: 'groq' })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// refreshOAuthTokenReactive
|
||||
// =============================================================================
|
||||
|
||||
describe('refreshOAuthTokenReactive', () => {
|
||||
it('returns new token from reactiveTokenRefresh', async () => {
|
||||
mockReactiveTokenRefresh.mockResolvedValueOnce({ token: 'refreshed-token-xyz', wasRefreshed: true });
|
||||
|
||||
const result = await refreshOAuthTokenReactive('/some/config/dir');
|
||||
|
||||
expect(result).toBe('refreshed-token-xyz');
|
||||
expect(mockReactiveTokenRefresh).toHaveBeenCalledWith('/some/config/dir');
|
||||
});
|
||||
|
||||
it('returns null when reactiveTokenRefresh returns no token', async () => {
|
||||
mockReactiveTokenRefresh.mockResolvedValueOnce({ token: null, wasRefreshed: false });
|
||||
|
||||
const result = await refreshOAuthTokenReactive(undefined);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when reactiveTokenRefresh throws', async () => {
|
||||
mockReactiveTokenRefresh.mockRejectedValueOnce(new Error('network error'));
|
||||
|
||||
const result = await refreshOAuthTokenReactive('/config');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// Provider Account Resolution (Stage 0)
|
||||
// =============================================================================
|
||||
|
||||
describe('resolveAuth — Stage 0: Provider Account', () => {
|
||||
it('returns api-key auth from providerAccounts setting', async () => {
|
||||
const accounts = [
|
||||
{
|
||||
provider: 'openai',
|
||||
isActive: true,
|
||||
authType: 'api-key',
|
||||
apiKey: 'sk-provider-account-key',
|
||||
},
|
||||
];
|
||||
registerSettingsAccessor((key) => {
|
||||
if (key === 'providerAccounts') return JSON.stringify(accounts);
|
||||
return undefined;
|
||||
});
|
||||
|
||||
const auth = await resolveAuth({ provider: 'openai' });
|
||||
|
||||
expect(auth?.apiKey).toBe('sk-provider-account-key');
|
||||
expect(auth?.source).toBe('profile-api-key');
|
||||
});
|
||||
|
||||
it('routes z.ai subscription to coding API endpoint', async () => {
|
||||
const accounts = [
|
||||
{
|
||||
provider: 'zai',
|
||||
isActive: true,
|
||||
authType: 'api-key',
|
||||
apiKey: 'zhipu-key',
|
||||
billingModel: 'subscription',
|
||||
},
|
||||
];
|
||||
registerSettingsAccessor((key) => {
|
||||
if (key === 'providerAccounts') return JSON.stringify(accounts);
|
||||
return undefined;
|
||||
});
|
||||
|
||||
const auth = await resolveAuth({ provider: 'zai' });
|
||||
|
||||
expect(auth?.apiKey).toBe('zhipu-key');
|
||||
expect(auth?.baseURL).toContain('/coding/paas/v4');
|
||||
});
|
||||
|
||||
it('routes z.ai pay-per-use to general API endpoint', async () => {
|
||||
const accounts = [
|
||||
{
|
||||
provider: 'zai',
|
||||
isActive: true,
|
||||
authType: 'api-key',
|
||||
apiKey: 'zhipu-key',
|
||||
billingModel: 'pay-per-use',
|
||||
},
|
||||
];
|
||||
registerSettingsAccessor((key) => {
|
||||
if (key === 'providerAccounts') return JSON.stringify(accounts);
|
||||
return undefined;
|
||||
});
|
||||
|
||||
const auth = await resolveAuth({ provider: 'zai' });
|
||||
|
||||
expect(auth?.baseURL).toContain('/paas/v4');
|
||||
expect(auth?.baseURL).not.toContain('/coding/');
|
||||
});
|
||||
|
||||
it('skips inactive accounts and falls through', async () => {
|
||||
const accounts = [
|
||||
{ provider: 'openai', isActive: false, authType: 'api-key', apiKey: 'sk-inactive' },
|
||||
];
|
||||
registerSettingsAccessor((key) => {
|
||||
if (key === 'providerAccounts') return JSON.stringify(accounts);
|
||||
return undefined;
|
||||
});
|
||||
process.env.OPENAI_API_KEY = 'sk-env-fallback';
|
||||
|
||||
const auth = await resolveAuth({ provider: 'openai' });
|
||||
|
||||
expect(auth?.source).toBe('environment');
|
||||
});
|
||||
|
||||
it('handles malformed providerAccounts JSON gracefully', async () => {
|
||||
registerSettingsAccessor((key) => {
|
||||
if (key === 'providerAccounts') return 'not-valid-json{{';
|
||||
return undefined;
|
||||
});
|
||||
process.env.OPENAI_API_KEY = 'sk-fallback';
|
||||
|
||||
const auth = await resolveAuth({ provider: 'openai' });
|
||||
expect(auth?.source).toBe('environment');
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// resolveAuthFromQueue
|
||||
// =============================================================================
|
||||
|
||||
describe('resolveAuthFromQueue', () => {
|
||||
const baseAccount = {
|
||||
id: 'acc-1',
|
||||
provider: 'anthropic' as const,
|
||||
authType: 'api-key' as const,
|
||||
apiKey: 'sk-queue-key',
|
||||
isActive: true,
|
||||
name: 'Primary Account',
|
||||
billingModel: 'pay-per-use' as const,
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockScoreProviderAccount.mockReturnValue({ available: true, score: 100 });
|
||||
mockResolveModelEquivalent.mockReturnValue({
|
||||
modelId: 'claude-sonnet-4-5-20250929',
|
||||
reasoning: { type: 'none' },
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves auth from the first available account in queue', async () => {
|
||||
const result = await resolveAuthFromQueue('sonnet', [baseAccount]);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.accountId).toBe('acc-1');
|
||||
expect(result?.apiKey).toBe('sk-queue-key');
|
||||
expect(result?.resolvedProvider).toBe('anthropic');
|
||||
});
|
||||
|
||||
it('skips excluded account IDs', async () => {
|
||||
const result = await resolveAuthFromQueue('sonnet', [baseAccount], {
|
||||
excludeAccountIds: ['acc-1'],
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('skips unavailable accounts', async () => {
|
||||
mockScoreProviderAccount.mockReturnValueOnce({ available: false, score: 0 });
|
||||
|
||||
const result = await resolveAuthFromQueue('sonnet', [baseAccount]);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when queue is empty', async () => {
|
||||
const result = await resolveAuthFromQueue('sonnet', []);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('uses the resolved model ID from equivalence table', async () => {
|
||||
mockResolveModelEquivalent.mockReturnValueOnce({
|
||||
modelId: 'claude-haiku-4-5',
|
||||
reasoning: { type: 'none' },
|
||||
});
|
||||
|
||||
const result = await resolveAuthFromQueue('haiku', [baseAccount]);
|
||||
|
||||
expect(result?.resolvedModelId).toBe('claude-haiku-4-5');
|
||||
});
|
||||
|
||||
it('falls through to next account when first has no credentials', async () => {
|
||||
const noKeyAccount = { ...baseAccount, id: 'acc-no-key', apiKey: undefined, authType: 'api-key' as const };
|
||||
const goodAccount = { ...baseAccount, id: 'acc-2' };
|
||||
|
||||
const result = await resolveAuthFromQueue('sonnet', [noKeyAccount, goodAccount]);
|
||||
|
||||
expect(result?.accountId).toBe('acc-2');
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// buildDefaultQueueConfig
|
||||
// =============================================================================
|
||||
|
||||
describe('buildDefaultQueueConfig', () => {
|
||||
it('returns undefined when no settings accessor is registered', () => {
|
||||
// accessor returns undefined for everything
|
||||
const result = buildDefaultQueueConfig('claude-sonnet-4-5-20250929');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns sorted queue when providerAccounts are configured', () => {
|
||||
const accounts = [
|
||||
{ id: 'b', provider: 'openai', isActive: true },
|
||||
{ id: 'a', provider: 'anthropic', isActive: true },
|
||||
];
|
||||
const priorityOrder = ['a', 'b'];
|
||||
|
||||
registerSettingsAccessor((key) => {
|
||||
if (key === 'providerAccounts') return JSON.stringify(accounts);
|
||||
if (key === 'globalPriorityOrder') return JSON.stringify(priorityOrder);
|
||||
return undefined;
|
||||
});
|
||||
|
||||
const result = buildDefaultQueueConfig('claude-sonnet-4-5-20250929');
|
||||
|
||||
expect(result).not.toBeUndefined();
|
||||
expect(result?.queue[0].id).toBe('a');
|
||||
expect(result?.queue[1].id).toBe('b');
|
||||
});
|
||||
|
||||
it('returns undefined when providerAccounts is empty array', () => {
|
||||
registerSettingsAccessor((key) => {
|
||||
if (key === 'providerAccounts') return JSON.stringify([]);
|
||||
return undefined;
|
||||
});
|
||||
|
||||
const result = buildDefaultQueueConfig('sonnet');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns accounts in natural order when no priority order is set', () => {
|
||||
const accounts = [
|
||||
{ id: 'x', provider: 'groq', isActive: true },
|
||||
{ id: 'y', provider: 'mistral', isActive: true },
|
||||
];
|
||||
registerSettingsAccessor((key) => {
|
||||
if (key === 'providerAccounts') return JSON.stringify(accounts);
|
||||
return undefined;
|
||||
});
|
||||
|
||||
const result = buildDefaultQueueConfig('some-model');
|
||||
|
||||
expect(result?.queue[0].id).toBe('x');
|
||||
expect(result?.queue[1].id).toBe('y');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Tests for AI Auth Types
|
||||
*
|
||||
* Validates that exported constants have the correct mappings
|
||||
* for environment variables, settings keys, and base URL env vars.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
PROVIDER_ENV_VARS,
|
||||
PROVIDER_SETTINGS_KEY,
|
||||
PROVIDER_BASE_URL_ENV,
|
||||
} from '../types';
|
||||
|
||||
describe('PROVIDER_ENV_VARS', () => {
|
||||
it('maps anthropic to ANTHROPIC_API_KEY', () => {
|
||||
expect(PROVIDER_ENV_VARS.anthropic).toBe('ANTHROPIC_API_KEY');
|
||||
});
|
||||
|
||||
it('maps openai to OPENAI_API_KEY', () => {
|
||||
expect(PROVIDER_ENV_VARS.openai).toBe('OPENAI_API_KEY');
|
||||
});
|
||||
|
||||
it('maps google to GOOGLE_GENERATIVE_AI_API_KEY', () => {
|
||||
expect(PROVIDER_ENV_VARS.google).toBe('GOOGLE_GENERATIVE_AI_API_KEY');
|
||||
});
|
||||
|
||||
it('maps bedrock to undefined (uses AWS credential chain)', () => {
|
||||
expect(PROVIDER_ENV_VARS.bedrock).toBeUndefined();
|
||||
});
|
||||
|
||||
it('maps azure to AZURE_OPENAI_API_KEY', () => {
|
||||
expect(PROVIDER_ENV_VARS.azure).toBe('AZURE_OPENAI_API_KEY');
|
||||
});
|
||||
|
||||
it('maps mistral to MISTRAL_API_KEY', () => {
|
||||
expect(PROVIDER_ENV_VARS.mistral).toBe('MISTRAL_API_KEY');
|
||||
});
|
||||
|
||||
it('maps groq to GROQ_API_KEY', () => {
|
||||
expect(PROVIDER_ENV_VARS.groq).toBe('GROQ_API_KEY');
|
||||
});
|
||||
|
||||
it('maps xai to XAI_API_KEY', () => {
|
||||
expect(PROVIDER_ENV_VARS.xai).toBe('XAI_API_KEY');
|
||||
});
|
||||
|
||||
it('maps openrouter to OPENROUTER_API_KEY', () => {
|
||||
expect(PROVIDER_ENV_VARS.openrouter).toBe('OPENROUTER_API_KEY');
|
||||
});
|
||||
|
||||
it('maps zai to ZHIPU_API_KEY', () => {
|
||||
expect(PROVIDER_ENV_VARS.zai).toBe('ZHIPU_API_KEY');
|
||||
});
|
||||
|
||||
it('maps ollama to undefined (no auth required)', () => {
|
||||
expect(PROVIDER_ENV_VARS.ollama).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PROVIDER_SETTINGS_KEY', () => {
|
||||
it('maps anthropic to globalAnthropicApiKey', () => {
|
||||
expect(PROVIDER_SETTINGS_KEY.anthropic).toBe('globalAnthropicApiKey');
|
||||
});
|
||||
|
||||
it('maps openai to globalOpenAIApiKey', () => {
|
||||
expect(PROVIDER_SETTINGS_KEY.openai).toBe('globalOpenAIApiKey');
|
||||
});
|
||||
|
||||
it('maps google to globalGoogleApiKey', () => {
|
||||
expect(PROVIDER_SETTINGS_KEY.google).toBe('globalGoogleApiKey');
|
||||
});
|
||||
|
||||
it('maps groq to globalGroqApiKey', () => {
|
||||
expect(PROVIDER_SETTINGS_KEY.groq).toBe('globalGroqApiKey');
|
||||
});
|
||||
|
||||
it('maps mistral to globalMistralApiKey', () => {
|
||||
expect(PROVIDER_SETTINGS_KEY.mistral).toBe('globalMistralApiKey');
|
||||
});
|
||||
|
||||
it('maps xai to globalXAIApiKey', () => {
|
||||
expect(PROVIDER_SETTINGS_KEY.xai).toBe('globalXAIApiKey');
|
||||
});
|
||||
|
||||
it('maps azure to globalAzureApiKey', () => {
|
||||
expect(PROVIDER_SETTINGS_KEY.azure).toBe('globalAzureApiKey');
|
||||
});
|
||||
|
||||
it('maps openrouter to globalOpenRouterApiKey', () => {
|
||||
expect(PROVIDER_SETTINGS_KEY.openrouter).toBe('globalOpenRouterApiKey');
|
||||
});
|
||||
|
||||
it('maps zai to globalZAIApiKey', () => {
|
||||
expect(PROVIDER_SETTINGS_KEY.zai).toBe('globalZAIApiKey');
|
||||
});
|
||||
|
||||
it('does not have a key for bedrock', () => {
|
||||
expect(PROVIDER_SETTINGS_KEY.bedrock).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not have a key for ollama', () => {
|
||||
expect(PROVIDER_SETTINGS_KEY.ollama).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PROVIDER_BASE_URL_ENV', () => {
|
||||
it('maps anthropic to ANTHROPIC_BASE_URL', () => {
|
||||
expect(PROVIDER_BASE_URL_ENV.anthropic).toBe('ANTHROPIC_BASE_URL');
|
||||
});
|
||||
|
||||
it('maps openai to OPENAI_BASE_URL', () => {
|
||||
expect(PROVIDER_BASE_URL_ENV.openai).toBe('OPENAI_BASE_URL');
|
||||
});
|
||||
|
||||
it('maps azure to AZURE_OPENAI_ENDPOINT', () => {
|
||||
expect(PROVIDER_BASE_URL_ENV.azure).toBe('AZURE_OPENAI_ENDPOINT');
|
||||
});
|
||||
|
||||
it('does not define base URL env for other providers', () => {
|
||||
expect(PROVIDER_BASE_URL_ENV.google).toBeUndefined();
|
||||
expect(PROVIDER_BASE_URL_ENV.groq).toBeUndefined();
|
||||
expect(PROVIDER_BASE_URL_ENV.mistral).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -253,7 +253,7 @@ export async function startCodexOAuthFlow(): Promise<CodexAuthResult> {
|
||||
<body style="font-family: system-ui, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; background: #1a1a1a; color: #e0e0e0;">
|
||||
<div style="text-align: center;">
|
||||
<h2 style="color: #4ade80;">Authentication successful!</h2>
|
||||
<p>You can close this tab and return to Auto Claude.</p>
|
||||
<p>You can close this tab and return to Aperant.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
/**
|
||||
* Tests for Client Factory
|
||||
*
|
||||
* Validates createSimpleClient() and createAgentClient() — model resolution,
|
||||
* credential wiring, tool registry binding, queue-based auth, and cleanup.
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
|
||||
// Mock auth resolver — inline to avoid hoisting issues
|
||||
vi.mock('../../auth/resolver', () => ({
|
||||
resolveAuth: vi.fn().mockResolvedValue({ apiKey: 'sk-default', source: 'environment' }),
|
||||
resolveAuthFromQueue: vi.fn().mockResolvedValue(null),
|
||||
buildDefaultQueueConfig: vi.fn().mockReturnValue(undefined),
|
||||
}));
|
||||
|
||||
// Mock provider factory — inline
|
||||
vi.mock('../../providers/factory', () => ({
|
||||
createProvider: vi.fn().mockReturnValue({ type: 'language-model', modelId: 'mock-model-id' }),
|
||||
detectProviderFromModel: vi.fn().mockReturnValue('anthropic'),
|
||||
}));
|
||||
|
||||
// Mock phase config — inline
|
||||
vi.mock('../../config/phase-config', () => ({
|
||||
resolveModelId: vi.fn().mockReturnValue('claude-haiku-4-5'),
|
||||
}));
|
||||
|
||||
// Mock agent configs — inline
|
||||
vi.mock('../../config/agent-configs', () => ({
|
||||
getDefaultThinkingLevel: vi.fn().mockReturnValue('medium'),
|
||||
getRequiredMcpServers: vi.fn().mockReturnValue([]),
|
||||
}));
|
||||
|
||||
// Mock MCP client module — inline
|
||||
vi.mock('../../mcp/client', () => ({
|
||||
createMcpClientsForAgent: vi.fn().mockResolvedValue([]),
|
||||
closeAllMcpClients: vi.fn().mockResolvedValue(undefined),
|
||||
mergeMcpTools: vi.fn().mockReturnValue({}),
|
||||
}));
|
||||
|
||||
// Mock tool registry — inline
|
||||
vi.mock('../../tools/build-registry', () => ({
|
||||
buildToolRegistry: vi.fn().mockReturnValue({
|
||||
getToolsForAgent: vi.fn().mockReturnValue({ Read: {}, Write: {} }),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock config/types resolveReasoningParams — inline
|
||||
vi.mock('../../config/types', () => ({
|
||||
resolveReasoningParams: vi.fn().mockReturnValue({}),
|
||||
}));
|
||||
|
||||
import { resolveAuth, resolveAuthFromQueue, buildDefaultQueueConfig } from '../../auth/resolver';
|
||||
import { createProvider, detectProviderFromModel } from '../../providers/factory';
|
||||
import { resolveModelId } from '../../config/phase-config';
|
||||
import { getDefaultThinkingLevel, getRequiredMcpServers } from '../../config/agent-configs';
|
||||
import { createMcpClientsForAgent, closeAllMcpClients, mergeMcpTools } from '../../mcp/client';
|
||||
import { buildToolRegistry } from '../../tools/build-registry';
|
||||
import { createSimpleClient, createAgentClient } from '../factory';
|
||||
import type { LanguageModel, Tool } from 'ai';
|
||||
import type { ToolContext } from '../../tools/types';
|
||||
import type { AgentClientConfig } from '../types';
|
||||
import type { ProviderAccount } from '../../../../shared/types/provider-account';
|
||||
import type { McpClientResult } from '../../mcp/types';
|
||||
import type { ToolRegistry } from '../../tools/registry';
|
||||
|
||||
const mockResolveAuth = vi.mocked(resolveAuth);
|
||||
const mockResolveAuthFromQueue = vi.mocked(resolveAuthFromQueue);
|
||||
const mockBuildDefaultQueueConfig = vi.mocked(buildDefaultQueueConfig);
|
||||
const mockCreateProvider = vi.mocked(createProvider);
|
||||
const mockDetectProviderFromModel = vi.mocked(detectProviderFromModel);
|
||||
const mockResolveModelId = vi.mocked(resolveModelId);
|
||||
const mockGetDefaultThinkingLevel = vi.mocked(getDefaultThinkingLevel);
|
||||
const mockGetRequiredMcpServers = vi.mocked(getRequiredMcpServers);
|
||||
const mockCreateMcpClientsForAgent = vi.mocked(createMcpClientsForAgent);
|
||||
const mockCloseAllMcpClients = vi.mocked(closeAllMcpClients);
|
||||
const mockMergeMcpTools = vi.mocked(mergeMcpTools);
|
||||
const mockBuildToolRegistry = vi.mocked(buildToolRegistry);
|
||||
|
||||
const FAKE_MODEL = { type: 'language-model', modelId: 'mock-model-id' };
|
||||
|
||||
const baseToolContext = {
|
||||
cwd: '/project',
|
||||
projectDir: '/project',
|
||||
specDir: '/project/.auto-claude/specs/001',
|
||||
securityProfile: 'standard' as const,
|
||||
} as unknown as ToolContext;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Re-establish defaults after clearAllMocks
|
||||
mockResolveAuth.mockResolvedValue({ apiKey: 'sk-default', source: 'environment' });
|
||||
mockResolveAuthFromQueue.mockResolvedValue(null);
|
||||
mockBuildDefaultQueueConfig.mockReturnValue(undefined);
|
||||
mockCreateProvider.mockReturnValue(FAKE_MODEL as unknown as LanguageModel);
|
||||
mockDetectProviderFromModel.mockReturnValue('anthropic');
|
||||
mockResolveModelId.mockReturnValue('claude-haiku-4-5');
|
||||
mockGetDefaultThinkingLevel.mockReturnValue('medium');
|
||||
mockGetRequiredMcpServers.mockReturnValue([]);
|
||||
mockCreateMcpClientsForAgent.mockResolvedValue([]);
|
||||
mockCloseAllMcpClients.mockResolvedValue(undefined);
|
||||
mockMergeMcpTools.mockReturnValue({});
|
||||
|
||||
// ToolRegistry mock: getToolsForAgent returns a basic tools map
|
||||
const mockRegistry = { getToolsForAgent: vi.fn().mockReturnValue({ Read: {}, Write: {} }) };
|
||||
mockBuildToolRegistry.mockReturnValue(mockRegistry as unknown as ToolRegistry);
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// createSimpleClient
|
||||
// =============================================================================
|
||||
|
||||
describe('createSimpleClient', () => {
|
||||
it('returns model, resolvedModelId, tools, systemPrompt, maxSteps, and thinkingLevel', async () => {
|
||||
const result = await createSimpleClient({ systemPrompt: 'You are helpful.' });
|
||||
|
||||
expect(result.model).toBe(FAKE_MODEL);
|
||||
expect(result.resolvedModelId).toBeDefined();
|
||||
expect(result.tools).toBeDefined();
|
||||
expect(result.systemPrompt).toBe('You are helpful.');
|
||||
expect(result.maxSteps).toBe(1);
|
||||
expect(result.thinkingLevel).toBe('low');
|
||||
});
|
||||
|
||||
it('defaults modelShorthand to haiku when not specified', async () => {
|
||||
await createSimpleClient({ systemPrompt: 'Test' });
|
||||
expect(mockResolveModelId).toHaveBeenCalledWith('haiku');
|
||||
});
|
||||
|
||||
it('uses the specified modelShorthand', async () => {
|
||||
await createSimpleClient({ systemPrompt: 'Test', modelShorthand: 'sonnet' });
|
||||
expect(mockResolveModelId).toHaveBeenCalledWith('sonnet');
|
||||
});
|
||||
|
||||
it('uses the specified thinkingLevel', async () => {
|
||||
const result = await createSimpleClient({ systemPrompt: 'Test', thinkingLevel: 'high' });
|
||||
expect(result.thinkingLevel).toBe('high');
|
||||
});
|
||||
|
||||
it('uses specified maxSteps', async () => {
|
||||
const result = await createSimpleClient({ systemPrompt: 'Test', maxSteps: 5 });
|
||||
expect(result.maxSteps).toBe(5);
|
||||
});
|
||||
|
||||
it('wires resolved auth credentials into createProvider', async () => {
|
||||
mockResolveAuth.mockResolvedValueOnce({
|
||||
apiKey: 'sk-resolved',
|
||||
source: 'environment',
|
||||
baseURL: 'https://custom.api.com',
|
||||
});
|
||||
|
||||
await createSimpleClient({ systemPrompt: 'Test' });
|
||||
|
||||
expect(mockCreateProvider).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
config: expect.objectContaining({
|
||||
apiKey: 'sk-resolved',
|
||||
baseURL: 'https://custom.api.com',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('passes tools option through to result', async () => {
|
||||
const customTools = { myTool: {} as unknown as Tool };
|
||||
const result = await createSimpleClient({ systemPrompt: 'Test', tools: customTools });
|
||||
expect(result.tools).toBe(customTools);
|
||||
});
|
||||
|
||||
it('uses queue-based resolution when queueConfig is provided', async () => {
|
||||
const queueAuth = {
|
||||
apiKey: 'sk-queue',
|
||||
source: 'profile-api-key' as const,
|
||||
accountId: 'acc-1',
|
||||
resolvedProvider: 'anthropic' as const,
|
||||
resolvedModelId: 'claude-opus-4-6',
|
||||
reasoningConfig: { type: 'none' as const },
|
||||
};
|
||||
mockResolveAuthFromQueue.mockResolvedValueOnce(queueAuth);
|
||||
|
||||
const queueConfig = {
|
||||
queue: [{ id: 'acc-1' } as unknown as ProviderAccount],
|
||||
requestedModel: 'claude-opus-4-6',
|
||||
};
|
||||
|
||||
const result = await createSimpleClient({ systemPrompt: 'Test', queueConfig });
|
||||
|
||||
expect(mockResolveAuthFromQueue).toHaveBeenCalled();
|
||||
expect(result.queueAuth).toBe(queueAuth);
|
||||
expect(result.resolvedModelId).toBe('claude-opus-4-6');
|
||||
});
|
||||
|
||||
it('throws when queueConfig is provided but no account is available', async () => {
|
||||
mockResolveAuthFromQueue.mockResolvedValueOnce(null);
|
||||
|
||||
const queueConfig = { queue: [], requestedModel: 'sonnet' };
|
||||
|
||||
await expect(
|
||||
createSimpleClient({ systemPrompt: 'Test', queueConfig }),
|
||||
).rejects.toThrow('No available account in priority queue');
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// createAgentClient
|
||||
// =============================================================================
|
||||
|
||||
describe('createAgentClient', () => {
|
||||
const baseConfig = {
|
||||
agentType: 'coder' as const,
|
||||
systemPrompt: 'You are a coder.',
|
||||
toolContext: baseToolContext,
|
||||
phase: 'coding' as const,
|
||||
};
|
||||
|
||||
it('returns model, tools, mcpClients, systemPrompt, maxSteps, thinkingLevel, and cleanup', async () => {
|
||||
const result = await createAgentClient(baseConfig);
|
||||
|
||||
expect(result.model).toBe(FAKE_MODEL);
|
||||
expect(result.tools).toBeDefined();
|
||||
expect(result.mcpClients).toEqual([]);
|
||||
expect(result.systemPrompt).toBe('You are a coder.');
|
||||
expect(result.maxSteps).toBe(200);
|
||||
expect(result.thinkingLevel).toBeDefined();
|
||||
expect(typeof result.cleanup).toBe('function');
|
||||
});
|
||||
|
||||
it('uses agent-config default thinking level', async () => {
|
||||
mockGetDefaultThinkingLevel.mockReturnValueOnce('high');
|
||||
|
||||
const result = await createAgentClient(baseConfig);
|
||||
|
||||
expect(result.thinkingLevel).toBe('high');
|
||||
expect(mockGetDefaultThinkingLevel).toHaveBeenCalledWith('coder');
|
||||
});
|
||||
|
||||
it('overrides thinking level when thinkingLevel is specified', async () => {
|
||||
const result = await createAgentClient({ ...baseConfig, thinkingLevel: 'low' });
|
||||
expect(result.thinkingLevel).toBe('low');
|
||||
});
|
||||
|
||||
it('uses specified maxSteps', async () => {
|
||||
const result = await createAgentClient({ ...baseConfig, maxSteps: 50 });
|
||||
expect(result.maxSteps).toBe(50);
|
||||
});
|
||||
|
||||
it('calls getToolsForAgent with agentType and toolContext', async () => {
|
||||
const mockRegistry = { getToolsForAgent: vi.fn().mockReturnValue({ Read: {}, Write: {} }) };
|
||||
mockBuildToolRegistry.mockReturnValueOnce(mockRegistry as unknown as ToolRegistry);
|
||||
|
||||
await createAgentClient(baseConfig);
|
||||
|
||||
expect(mockRegistry.getToolsForAgent).toHaveBeenCalledWith('coder', baseToolContext);
|
||||
});
|
||||
|
||||
it('creates MCP clients when agent requires servers', async () => {
|
||||
const mockMcpClient = { serverId: 'context7', tools: { ctx7_tool: {} }, close: vi.fn() };
|
||||
mockGetRequiredMcpServers.mockReturnValueOnce(['context7']);
|
||||
mockCreateMcpClientsForAgent.mockResolvedValueOnce([mockMcpClient] as unknown as McpClientResult[]);
|
||||
mockMergeMcpTools.mockReturnValueOnce({ ctx7_tool: {} });
|
||||
|
||||
const result = await createAgentClient(baseConfig);
|
||||
|
||||
expect(mockCreateMcpClientsForAgent).toHaveBeenCalledWith('coder', expect.any(Object));
|
||||
expect(result.mcpClients).toHaveLength(1);
|
||||
expect(result.tools).toHaveProperty('ctx7_tool');
|
||||
});
|
||||
|
||||
it('cleanup calls closeAllMcpClients with the client list', async () => {
|
||||
const result = await createAgentClient(baseConfig);
|
||||
await result.cleanup();
|
||||
expect(mockCloseAllMcpClients).toHaveBeenCalledWith(result.mcpClients);
|
||||
});
|
||||
|
||||
it('uses queue-based auth when queueConfig is provided', async () => {
|
||||
const queueAuth = {
|
||||
apiKey: 'sk-queue-coder',
|
||||
source: 'profile-api-key' as const,
|
||||
accountId: 'acc-coder',
|
||||
resolvedProvider: 'anthropic' as const,
|
||||
resolvedModelId: 'claude-sonnet-4-5-20250929',
|
||||
reasoningConfig: { type: 'none' as const },
|
||||
};
|
||||
mockResolveAuthFromQueue.mockResolvedValueOnce(queueAuth);
|
||||
|
||||
const result = await createAgentClient({
|
||||
...baseConfig,
|
||||
queueConfig: {
|
||||
queue: [{ id: 'acc-coder' } as unknown as ProviderAccount],
|
||||
requestedModel: 'claude-sonnet-4-5-20250929',
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.queueAuth).toBe(queueAuth);
|
||||
expect(mockCreateProvider).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
config: expect.objectContaining({
|
||||
provider: 'anthropic',
|
||||
apiKey: 'sk-queue-coder',
|
||||
}),
|
||||
modelId: 'claude-sonnet-4-5-20250929',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when queueConfig provided but no account available', async () => {
|
||||
mockResolveAuthFromQueue.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
createAgentClient({
|
||||
...baseConfig,
|
||||
queueConfig: { queue: [], requestedModel: 'sonnet' },
|
||||
}),
|
||||
).rejects.toThrow('No available account in priority queue');
|
||||
});
|
||||
|
||||
it('merges additionalMcpServers into the required servers list', async () => {
|
||||
mockGetRequiredMcpServers.mockReturnValueOnce(['context7']);
|
||||
|
||||
await createAgentClient({
|
||||
...baseConfig,
|
||||
additionalMcpServers: ['custom-server'],
|
||||
});
|
||||
|
||||
// createMcpClientsForAgent is called because the combined server list is non-empty
|
||||
expect(mockCreateMcpClientsForAgent).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -89,6 +89,10 @@ describe('resolveModelId', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
// Clear model override env vars to ensure consistent test results
|
||||
delete process.env.ANTHROPIC_DEFAULT_OPUS_MODEL;
|
||||
delete process.env.ANTHROPIC_DEFAULT_SONNET_MODEL;
|
||||
delete process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
/**
|
||||
* Tests for MCP Client
|
||||
*
|
||||
* Validates transport creation, client initialization, parallel agent setup,
|
||||
* tool merging, and cleanup behavior.
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
|
||||
// Mock @ai-sdk/mcp using inline factory to avoid vi.mock hoisting issues
|
||||
vi.mock('@ai-sdk/mcp', () => ({
|
||||
createMCPClient: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock StdioClientTransport constructor using a proper constructor function
|
||||
vi.mock('@modelcontextprotocol/sdk/client/stdio.js', () => ({
|
||||
// biome-ignore lint/suspicious/noExplicitAny: test mock constructor
|
||||
StdioClientTransport: vi.fn().mockImplementation(function (this: any) {
|
||||
Object.assign(this, { __kind: 'stdio-transport' });
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock registry to control which servers get resolved
|
||||
vi.mock('../registry', () => ({
|
||||
resolveMcpServers: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock agent-configs to control required servers
|
||||
vi.mock('../../config/agent-configs', () => ({
|
||||
getRequiredMcpServers: vi.fn().mockReturnValue([]),
|
||||
}));
|
||||
|
||||
import { createMCPClient } from '@ai-sdk/mcp';
|
||||
import type { MCPClient } from '@ai-sdk/mcp';
|
||||
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
||||
import { resolveMcpServers } from '../registry';
|
||||
import { getRequiredMcpServers } from '../../config/agent-configs';
|
||||
import type { McpServerResolveOptions } from '../../config/agent-configs';
|
||||
import {
|
||||
createMcpClient,
|
||||
createMcpClientsForAgent,
|
||||
closeAllMcpClients,
|
||||
mergeMcpTools,
|
||||
} from '../client';
|
||||
import type { McpServerConfig } from '../types';
|
||||
|
||||
const mockCreateMCPClient = vi.mocked(createMCPClient);
|
||||
const mockStdioClientTransport = vi.mocked(StdioClientTransport);
|
||||
const mockResolveMcpServers = vi.mocked(resolveMcpServers);
|
||||
const mockGetRequiredMcpServers = vi.mocked(getRequiredMcpServers);
|
||||
|
||||
// Sentinel: what StdioClientTransport instances look like after construction
|
||||
const FAKE_STDIO_TRANSPORT_PROPS = { __kind: 'stdio-transport' };
|
||||
|
||||
// Helper: build a mock MCP client instance
|
||||
function makeMockMcpInstance(tools = { tool_a: {}, tool_b: {} }) {
|
||||
return {
|
||||
tools: vi.fn().mockResolvedValue(tools),
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
}
|
||||
|
||||
// Helpers: server configs
|
||||
const stdioConfig: McpServerConfig = {
|
||||
id: 'test-stdio',
|
||||
name: 'Test Stdio Server',
|
||||
description: 'A test stdio server',
|
||||
enabledByDefault: true,
|
||||
transport: {
|
||||
type: 'stdio',
|
||||
command: 'npx',
|
||||
args: ['-y', 'some-mcp-server'],
|
||||
env: { MY_VAR: 'value' },
|
||||
},
|
||||
};
|
||||
|
||||
const httpConfig: McpServerConfig = {
|
||||
id: 'test-http',
|
||||
name: 'Test HTTP Server',
|
||||
description: 'A test streamable-http server',
|
||||
enabledByDefault: true,
|
||||
transport: {
|
||||
type: 'streamable-http',
|
||||
url: 'https://mcp.example.com/sse',
|
||||
headers: { Authorization: 'Bearer token123' },
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Default: StdioClientTransport constructor sets __kind on instance
|
||||
// biome-ignore lint/suspicious/noExplicitAny: test mock constructor
|
||||
mockStdioClientTransport.mockImplementation(function (this: any) {
|
||||
Object.assign(this, FAKE_STDIO_TRANSPORT_PROPS);
|
||||
} as unknown as typeof StdioClientTransport);
|
||||
// Default: createMCPClient returns a standard mock instance
|
||||
mockCreateMCPClient.mockResolvedValue(makeMockMcpInstance() as unknown as MCPClient);
|
||||
mockGetRequiredMcpServers.mockReturnValue([]);
|
||||
mockResolveMcpServers.mockReturnValue([]);
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// createMcpClient — transport creation
|
||||
// =============================================================================
|
||||
|
||||
describe('createMcpClient', () => {
|
||||
it('creates a StdioClientTransport for stdio server config', async () => {
|
||||
await createMcpClient(stdioConfig);
|
||||
|
||||
expect(mockStdioClientTransport).toHaveBeenCalledWith({
|
||||
command: 'npx',
|
||||
args: ['-y', 'some-mcp-server'],
|
||||
env: expect.objectContaining({ MY_VAR: 'value' }),
|
||||
cwd: undefined,
|
||||
});
|
||||
// The transport passed to createMCPClient is an instance of the mocked StdioClientTransport
|
||||
expect(mockCreateMCPClient).toHaveBeenCalledWith({
|
||||
transport: expect.objectContaining(FAKE_STDIO_TRANSPORT_PROPS),
|
||||
});
|
||||
});
|
||||
|
||||
it('creates an SSE transport object for streamable-http config', async () => {
|
||||
await createMcpClient(httpConfig);
|
||||
|
||||
expect(mockCreateMCPClient).toHaveBeenCalledWith({
|
||||
transport: {
|
||||
type: 'sse',
|
||||
url: 'https://mcp.example.com/sse',
|
||||
headers: { Authorization: 'Bearer token123' },
|
||||
},
|
||||
});
|
||||
// StdioClientTransport should NOT be called for HTTP config
|
||||
expect(mockStdioClientTransport).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns a result with serverId, tools, and close function', async () => {
|
||||
const result = await createMcpClient(stdioConfig);
|
||||
|
||||
expect(result.serverId).toBe('test-stdio');
|
||||
expect(result.tools).toEqual({ tool_a: {}, tool_b: {} });
|
||||
expect(typeof result.close).toBe('function');
|
||||
});
|
||||
|
||||
it('merges process.env with server env for stdio transport', async () => {
|
||||
const originalPath = process.env.PATH;
|
||||
process.env.PATH = '/usr/bin';
|
||||
|
||||
await createMcpClient(stdioConfig);
|
||||
|
||||
expect(mockStdioClientTransport).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
env: expect.objectContaining({ PATH: '/usr/bin', MY_VAR: 'value' }),
|
||||
}),
|
||||
);
|
||||
|
||||
process.env.PATH = originalPath;
|
||||
});
|
||||
|
||||
it('passes undefined env to StdioClientTransport when no env in config', async () => {
|
||||
const noEnvConfig: McpServerConfig = {
|
||||
...stdioConfig,
|
||||
transport: { type: 'stdio', command: 'node', args: ['server.js'] },
|
||||
};
|
||||
|
||||
await createMcpClient(noEnvConfig);
|
||||
|
||||
expect(mockStdioClientTransport).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ env: undefined }),
|
||||
);
|
||||
});
|
||||
|
||||
it('close() delegates to the underlying MCP client close method', async () => {
|
||||
const mockInstance = makeMockMcpInstance();
|
||||
mockCreateMCPClient.mockResolvedValueOnce(mockInstance as unknown as MCPClient);
|
||||
|
||||
const result = await createMcpClient(stdioConfig);
|
||||
await result.close();
|
||||
|
||||
expect(mockInstance.close).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// createMcpClientsForAgent
|
||||
// =============================================================================
|
||||
|
||||
describe('createMcpClientsForAgent', () => {
|
||||
it('returns empty array when agent requires no MCP servers', async () => {
|
||||
mockGetRequiredMcpServers.mockReturnValueOnce([]);
|
||||
mockResolveMcpServers.mockReturnValueOnce([]);
|
||||
|
||||
const clients = await createMcpClientsForAgent('commit_message');
|
||||
|
||||
expect(clients).toEqual([]);
|
||||
});
|
||||
|
||||
it('creates clients for each resolved server config', async () => {
|
||||
mockGetRequiredMcpServers.mockReturnValueOnce(['context7', 'auto-claude']);
|
||||
mockResolveMcpServers.mockReturnValueOnce([
|
||||
{ ...stdioConfig, id: 'context7' },
|
||||
{ ...stdioConfig, id: 'auto-claude' },
|
||||
]);
|
||||
// Two separate mock instances for the two servers
|
||||
mockCreateMCPClient
|
||||
.mockResolvedValueOnce(makeMockMcpInstance() as unknown as MCPClient)
|
||||
.mockResolvedValueOnce(makeMockMcpInstance() as unknown as MCPClient);
|
||||
|
||||
const clients = await createMcpClientsForAgent('coder');
|
||||
|
||||
expect(clients).toHaveLength(2);
|
||||
expect(clients[0].serverId).toBe('context7');
|
||||
expect(clients[1].serverId).toBe('auto-claude');
|
||||
});
|
||||
|
||||
it('skips failed connections without throwing', async () => {
|
||||
mockGetRequiredMcpServers.mockReturnValueOnce(['context7', 'broken-server']);
|
||||
mockResolveMcpServers.mockReturnValueOnce([
|
||||
{ ...stdioConfig, id: 'context7' },
|
||||
{ ...stdioConfig, id: 'broken-server' },
|
||||
]);
|
||||
|
||||
// First call succeeds, second call fails
|
||||
mockCreateMCPClient
|
||||
.mockResolvedValueOnce(makeMockMcpInstance() as unknown as MCPClient)
|
||||
.mockRejectedValueOnce(new Error('connection refused'));
|
||||
|
||||
const clients = await createMcpClientsForAgent('coder');
|
||||
|
||||
// Only the successful client should be returned
|
||||
expect(clients).toHaveLength(1);
|
||||
expect(clients[0].serverId).toBe('context7');
|
||||
});
|
||||
|
||||
it('passes resolveOptions to getRequiredMcpServers', async () => {
|
||||
mockGetRequiredMcpServers.mockReturnValueOnce([]);
|
||||
mockResolveMcpServers.mockReturnValueOnce([]);
|
||||
|
||||
const resolveOptions = { electronMcpEnabled: true };
|
||||
await createMcpClientsForAgent('qa_reviewer', resolveOptions as unknown as McpServerResolveOptions);
|
||||
|
||||
expect(mockGetRequiredMcpServers).toHaveBeenCalledWith('qa_reviewer', resolveOptions);
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// mergeMcpTools
|
||||
// =============================================================================
|
||||
|
||||
describe('mergeMcpTools', () => {
|
||||
it('merges tools from multiple clients into a single object', () => {
|
||||
const clients = [
|
||||
{ serverId: 'a', tools: { tool1: {}, tool2: {} }, close: vi.fn() },
|
||||
{ serverId: 'b', tools: { tool3: {}, tool4: {} }, close: vi.fn() },
|
||||
];
|
||||
|
||||
const merged = mergeMcpTools(clients);
|
||||
|
||||
expect(Object.keys(merged)).toHaveLength(4);
|
||||
expect(merged).toHaveProperty('tool1');
|
||||
expect(merged).toHaveProperty('tool3');
|
||||
});
|
||||
|
||||
it('returns empty object for empty clients array', () => {
|
||||
expect(mergeMcpTools([])).toEqual({});
|
||||
});
|
||||
|
||||
it('later client tools overwrite earlier ones on key collision', () => {
|
||||
const clients = [
|
||||
{ serverId: 'a', tools: { shared_tool: { version: 1 } }, close: vi.fn() },
|
||||
{ serverId: 'b', tools: { shared_tool: { version: 2 } }, close: vi.fn() },
|
||||
];
|
||||
|
||||
const merged = mergeMcpTools(clients);
|
||||
|
||||
// biome-ignore lint/suspicious/noExplicitAny: test mock property access
|
||||
expect((merged.shared_tool as any).version).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// closeAllMcpClients
|
||||
// =============================================================================
|
||||
|
||||
describe('closeAllMcpClients', () => {
|
||||
it('calls close on all clients', async () => {
|
||||
const close1 = vi.fn().mockResolvedValue(undefined);
|
||||
const close2 = vi.fn().mockResolvedValue(undefined);
|
||||
const clients = [
|
||||
{ serverId: 'a', tools: {}, close: close1 },
|
||||
{ serverId: 'b', tools: {}, close: close2 },
|
||||
];
|
||||
|
||||
await closeAllMcpClients(clients);
|
||||
|
||||
expect(close1).toHaveBeenCalled();
|
||||
expect(close2).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resolves even when one client fails to close', async () => {
|
||||
const close1 = vi.fn().mockResolvedValue(undefined);
|
||||
const close2 = vi.fn().mockRejectedValue(new Error('close failed'));
|
||||
const clients = [
|
||||
{ serverId: 'a', tools: {}, close: close1 },
|
||||
{ serverId: 'b', tools: {}, close: close2 },
|
||||
];
|
||||
|
||||
// Should not throw
|
||||
await expect(closeAllMcpClients(clients)).resolves.toBeUndefined();
|
||||
expect(close1).toHaveBeenCalled();
|
||||
expect(close2).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resolves immediately for empty clients array', async () => {
|
||||
await expect(closeAllMcpClients([])).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* Tests for MCP Server Registry
|
||||
*
|
||||
* Validates server configuration resolution, required server lookup,
|
||||
* and option-based server filtering.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { getMcpServerConfig, resolveMcpServers } from '../registry';
|
||||
|
||||
// =============================================================================
|
||||
// getMcpServerConfig
|
||||
// =============================================================================
|
||||
|
||||
describe('getMcpServerConfig', () => {
|
||||
describe('context7', () => {
|
||||
it('returns the context7 server config', () => {
|
||||
const config = getMcpServerConfig('context7');
|
||||
expect(config).not.toBeNull();
|
||||
expect(config?.id).toBe('context7');
|
||||
expect(config?.enabledByDefault).toBe(true);
|
||||
});
|
||||
|
||||
it('uses stdio transport with npx', () => {
|
||||
const config = getMcpServerConfig('context7');
|
||||
expect(config?.transport.type).toBe('stdio');
|
||||
if (config?.transport.type === 'stdio') {
|
||||
expect(config.transport.command).toBe('npx');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('linear', () => {
|
||||
it('returns null when no API key provided', () => {
|
||||
const config = getMcpServerConfig('linear', {});
|
||||
expect(config).toBeNull();
|
||||
});
|
||||
|
||||
it('returns config when linearApiKey is provided', () => {
|
||||
const config = getMcpServerConfig('linear', { linearApiKey: 'lin_api_123' });
|
||||
expect(config).not.toBeNull();
|
||||
expect(config?.id).toBe('linear');
|
||||
});
|
||||
|
||||
it('returns config when LINEAR_API_KEY is in env option', () => {
|
||||
const config = getMcpServerConfig('linear', { env: { LINEAR_API_KEY: 'lin_env_456' } });
|
||||
expect(config).not.toBeNull();
|
||||
});
|
||||
|
||||
it('injects LINEAR_API_KEY into the transport env', () => {
|
||||
const config = getMcpServerConfig('linear', { linearApiKey: 'lin_inject' });
|
||||
expect(config?.transport.type).toBe('stdio');
|
||||
if (config?.transport.type === 'stdio') {
|
||||
expect(config.transport.env?.LINEAR_API_KEY).toBe('lin_inject');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('memory', () => {
|
||||
it('returns null when no memory URL provided', () => {
|
||||
const config = getMcpServerConfig('memory', {});
|
||||
expect(config).toBeNull();
|
||||
});
|
||||
|
||||
it('returns config with streamable-http transport when URL is provided', () => {
|
||||
const config = getMcpServerConfig('memory', { memoryMcpUrl: 'http://localhost:8080/mcp' });
|
||||
expect(config).not.toBeNull();
|
||||
expect(config?.transport.type).toBe('streamable-http');
|
||||
if (config?.transport.type === 'streamable-http') {
|
||||
expect(config.transport.url).toBe('http://localhost:8080/mcp');
|
||||
}
|
||||
});
|
||||
|
||||
it('reads URL from env.GRAPHITI_MCP_URL option', () => {
|
||||
const config = getMcpServerConfig('memory', { env: { GRAPHITI_MCP_URL: 'http://graphiti.local' } });
|
||||
expect(config?.transport.type).toBe('streamable-http');
|
||||
});
|
||||
});
|
||||
|
||||
describe('electron', () => {
|
||||
it('returns the electron server config', () => {
|
||||
const config = getMcpServerConfig('electron');
|
||||
expect(config).not.toBeNull();
|
||||
expect(config?.id).toBe('electron');
|
||||
expect(config?.enabledByDefault).toBe(false);
|
||||
});
|
||||
|
||||
it('uses stdio transport', () => {
|
||||
const config = getMcpServerConfig('electron');
|
||||
expect(config?.transport.type).toBe('stdio');
|
||||
});
|
||||
});
|
||||
|
||||
describe('puppeteer', () => {
|
||||
it('returns the puppeteer server config', () => {
|
||||
const config = getMcpServerConfig('puppeteer');
|
||||
expect(config).not.toBeNull();
|
||||
expect(config?.id).toBe('puppeteer');
|
||||
});
|
||||
|
||||
it('uses stdio transport', () => {
|
||||
const config = getMcpServerConfig('puppeteer');
|
||||
expect(config?.transport.type).toBe('stdio');
|
||||
});
|
||||
});
|
||||
|
||||
describe('auto-claude', () => {
|
||||
it('returns auto-claude config with empty specDir as default', () => {
|
||||
const config = getMcpServerConfig('auto-claude', {});
|
||||
expect(config).not.toBeNull();
|
||||
expect(config?.id).toBe('auto-claude');
|
||||
});
|
||||
|
||||
it('injects SPEC_DIR into transport env', () => {
|
||||
const config = getMcpServerConfig('auto-claude', { specDir: '/project/.auto-claude/specs/001-feature' });
|
||||
expect(config?.transport.type).toBe('stdio');
|
||||
if (config?.transport.type === 'stdio') {
|
||||
expect(config.transport.env?.SPEC_DIR).toBe('/project/.auto-claude/specs/001-feature');
|
||||
}
|
||||
});
|
||||
|
||||
it('uses node command', () => {
|
||||
const config = getMcpServerConfig('auto-claude', {});
|
||||
if (config?.transport.type === 'stdio') {
|
||||
expect(config.transport.command).toBe('node');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('unknown server', () => {
|
||||
it('returns null for unrecognized server ID', () => {
|
||||
const config = getMcpServerConfig('nonexistent-server');
|
||||
expect(config).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// resolveMcpServers
|
||||
// =============================================================================
|
||||
|
||||
describe('resolveMcpServers', () => {
|
||||
it('returns configs for all recognized server IDs', () => {
|
||||
const configs = resolveMcpServers(['context7', 'electron', 'puppeteer']);
|
||||
expect(configs).toHaveLength(3);
|
||||
expect(configs.map((c) => c.id)).toEqual(['context7', 'electron', 'puppeteer']);
|
||||
});
|
||||
|
||||
it('filters out servers that cannot be configured (e.g. linear without API key)', () => {
|
||||
const configs = resolveMcpServers(['context7', 'linear'], {});
|
||||
expect(configs).toHaveLength(1);
|
||||
expect(configs[0].id).toBe('context7');
|
||||
});
|
||||
|
||||
it('includes linear when API key option is provided', () => {
|
||||
const configs = resolveMcpServers(['context7', 'linear'], { linearApiKey: 'lin_test' });
|
||||
expect(configs).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('returns empty array for empty input', () => {
|
||||
const configs = resolveMcpServers([]);
|
||||
expect(configs).toEqual([]);
|
||||
});
|
||||
|
||||
it('skips unrecognized server IDs silently', () => {
|
||||
const configs = resolveMcpServers(['context7', 'bogus-server-id']);
|
||||
expect(configs).toHaveLength(1);
|
||||
expect(configs[0].id).toBe('context7');
|
||||
});
|
||||
|
||||
it('includes memory server when memoryMcpUrl is provided', () => {
|
||||
const configs = resolveMcpServers(['memory'], { memoryMcpUrl: 'http://memory.local' });
|
||||
expect(configs).toHaveLength(1);
|
||||
expect(configs[0].id).toBe('memory');
|
||||
});
|
||||
|
||||
it('passes specDir through to auto-claude config', () => {
|
||||
const specDir = '/my-project/.auto-claude/specs/042-auth';
|
||||
const configs = resolveMcpServers(['auto-claude'], { specDir });
|
||||
expect(configs).toHaveLength(1);
|
||||
if (configs[0].transport.type === 'stdio') {
|
||||
expect(configs[0].transport.env?.SPEC_DIR).toBe(specDir);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -106,7 +106,7 @@ const PUPPETEER_SERVER: McpServerConfig = {
|
||||
function createAutoClaudeServer(specDir: string): McpServerConfig {
|
||||
return {
|
||||
id: 'auto-claude',
|
||||
name: 'Auto-Claude',
|
||||
name: 'Aperant',
|
||||
description: 'Build management tools (progress tracking, session context)',
|
||||
enabledByDefault: true,
|
||||
transport: {
|
||||
|
||||
@@ -7,11 +7,51 @@
|
||||
* 3. Web app (Next.js SaaS) — pure cloud libSQL
|
||||
*/
|
||||
|
||||
import { createClient } from '@libsql/client';
|
||||
import type { Client } from '@libsql/client';
|
||||
import type { Client, Config } from '@libsql/client/sqlite3';
|
||||
import { createRequire } from 'module';
|
||||
import { join } from 'path';
|
||||
import { MEMORY_SCHEMA_SQL, MEMORY_PRAGMA_SQL } from './schema';
|
||||
|
||||
/**
|
||||
* Lazy-load @libsql/client via CJS require().
|
||||
*
|
||||
* @libsql/client depends on native platform-specific modules (@libsql/darwin-arm64,
|
||||
* @libsql/linux-x64-gnu, etc.). In packaged Electron apps these live in
|
||||
* Resources/node_modules/ (via extraResources). ESM import() can't resolve them
|
||||
* from within app.asar, but CJS require() works because Module.globalPaths is
|
||||
* patched at startup in index.ts to include Resources/node_modules/.
|
||||
*
|
||||
* Using a lazy getter avoids a static import that would crash at startup before
|
||||
* the globalPaths patch runs.
|
||||
*/
|
||||
let _createClient: ((config: Config) => Client) | null = null;
|
||||
|
||||
function loadCreateClient(): (config: Config) => Client {
|
||||
if (!_createClient) {
|
||||
// In Electron: globalThis.require is set up in index.ts with Module.globalPaths
|
||||
// patched to include Resources/node_modules/ for extraResources packages.
|
||||
// In tests/dev: fall back to createRequire (deps are in normal node_modules).
|
||||
const req = globalThis.require ?? createRequire(import.meta.url);
|
||||
let mod: Record<string, unknown>;
|
||||
try {
|
||||
mod = req('@libsql/client/sqlite3');
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Failed to load @libsql/client/sqlite3: ${(err as Error).message}. ` +
|
||||
`Ensure native modules are available in Resources/node_modules/`
|
||||
);
|
||||
}
|
||||
if (typeof mod.createClient !== 'function') {
|
||||
throw new Error(
|
||||
`@libsql/client/sqlite3 did not export createClient (got ${typeof mod.createClient}). ` +
|
||||
`Check that native modules are available in Resources/node_modules/`
|
||||
);
|
||||
}
|
||||
_createClient = mod.createClient as (config: Config) => Client;
|
||||
}
|
||||
return _createClient!;
|
||||
}
|
||||
|
||||
let _client: Client | null = null;
|
||||
|
||||
/**
|
||||
@@ -31,7 +71,7 @@ export async function getMemoryClient(
|
||||
const { app } = await import('electron');
|
||||
const localPath = join(app.getPath('userData'), 'memory.db');
|
||||
|
||||
_client = createClient({
|
||||
_client = loadCreateClient()({
|
||||
url: `file:${localPath}`,
|
||||
...(tursoSyncUrl && authToken
|
||||
? { syncUrl: tursoSyncUrl, authToken, syncInterval: 60 }
|
||||
@@ -78,7 +118,7 @@ export async function getWebMemoryClient(
|
||||
tursoUrl: string,
|
||||
authToken: string,
|
||||
): Promise<Client> {
|
||||
const client = createClient({ url: tursoUrl, authToken });
|
||||
const client = loadCreateClient()({ url: tursoUrl, authToken });
|
||||
|
||||
// Apply PRAGMAs
|
||||
for (const pragma of MEMORY_PRAGMA_SQL.split('\n').filter(l => l.trim())) {
|
||||
@@ -97,7 +137,7 @@ export async function getWebMemoryClient(
|
||||
* Create an in-memory client (for tests — no Electron dependency).
|
||||
*/
|
||||
export async function getInMemoryClient(): Promise<Client> {
|
||||
const client = createClient({ url: ':memory:' });
|
||||
const client = loadCreateClient()({ url: ':memory:' });
|
||||
await client.executeMultiple(MEMORY_SCHEMA_SQL);
|
||||
return client;
|
||||
}
|
||||
|
||||
@@ -251,7 +251,7 @@ export interface MemoryMethodologyPlugin {
|
||||
|
||||
export const nativePlugin: MemoryMethodologyPlugin = {
|
||||
id: 'native',
|
||||
displayName: 'Auto Claude (Subtasks)',
|
||||
displayName: 'Aperant (Subtasks)',
|
||||
mapPhase: (p: string): UniversalPhase => {
|
||||
const map: Record<string, UniversalPhase> = {
|
||||
planning: 'define',
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
import { executeParallel } from '../parallel-executor';
|
||||
import type { ParallelExecutorConfig, SubtaskSessionRunner } from '../parallel-executor';
|
||||
import type { SubtaskInfo } from '../build-orchestrator';
|
||||
import type { SessionResult } from '../../session/types';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makeSubtask(id: string): SubtaskInfo {
|
||||
return {
|
||||
id,
|
||||
description: `Subtask ${id}`,
|
||||
status: 'pending',
|
||||
};
|
||||
}
|
||||
|
||||
function makeResult(outcome: SessionResult['outcome']): SessionResult {
|
||||
return {
|
||||
outcome,
|
||||
error: outcome === 'error' ? new Error('session error') : undefined,
|
||||
totalSteps: 1,
|
||||
lastMessage: '',
|
||||
} as unknown as SessionResult;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helper: run executeParallel with fake timers advanced automatically
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function runWithFakeTimers<T>(fn: () => Promise<T>): Promise<T> {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const promise = fn();
|
||||
await vi.runAllTimersAsync();
|
||||
return await promise;
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('executeParallel', () => {
|
||||
// -------------------------------------------------------------------------
|
||||
// Empty task list
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('returns empty results for an empty subtask list', async () => {
|
||||
const runner = vi.fn() as unknown as SubtaskSessionRunner;
|
||||
const result = await executeParallel([], runner);
|
||||
|
||||
expect(result.results).toHaveLength(0);
|
||||
expect(result.successCount).toBe(0);
|
||||
expect(result.failureCount).toBe(0);
|
||||
expect(result.rateLimitedCount).toBe(0);
|
||||
expect(result.cancelled).toBe(false);
|
||||
expect(runner).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// All succeed
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('returns successCount equal to number of subtasks when all succeed', async () => {
|
||||
const subtasks = [makeSubtask('t1'), makeSubtask('t2'), makeSubtask('t3')];
|
||||
const runner = vi.fn().mockResolvedValue(makeResult('completed')) as SubtaskSessionRunner;
|
||||
|
||||
const result = await runWithFakeTimers(() =>
|
||||
executeParallel(subtasks, runner, { maxConcurrency: 10 }),
|
||||
);
|
||||
|
||||
expect(result.successCount).toBe(3);
|
||||
expect(result.failureCount).toBe(0);
|
||||
expect(result.rateLimitedCount).toBe(0);
|
||||
expect(result.cancelled).toBe(false);
|
||||
expect(result.results).toHaveLength(3);
|
||||
for (const r of result.results) {
|
||||
expect(r.success).toBe(true);
|
||||
expect(r.rateLimited).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('maps subtaskIds correctly in results', async () => {
|
||||
const subtasks = [makeSubtask('alpha'), makeSubtask('beta')];
|
||||
const runner = vi.fn().mockResolvedValue(makeResult('completed')) as SubtaskSessionRunner;
|
||||
|
||||
const result = await runWithFakeTimers(() =>
|
||||
executeParallel(subtasks, runner, { maxConcurrency: 10 }),
|
||||
);
|
||||
const ids = result.results.map((r) => r.subtaskId);
|
||||
|
||||
expect(ids).toContain('alpha');
|
||||
expect(ids).toContain('beta');
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Partial failure
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('handles partial failure — some succeed, some fail', async () => {
|
||||
const subtasks = [makeSubtask('s1'), makeSubtask('s2'), makeSubtask('s3')];
|
||||
|
||||
const runner = vi.fn()
|
||||
.mockResolvedValueOnce(makeResult('completed'))
|
||||
.mockResolvedValueOnce(makeResult('error'))
|
||||
.mockResolvedValueOnce(makeResult('completed')) as SubtaskSessionRunner;
|
||||
|
||||
const result = await runWithFakeTimers(() =>
|
||||
executeParallel(subtasks, runner, { maxConcurrency: 10 }),
|
||||
);
|
||||
|
||||
expect(result.successCount).toBe(2);
|
||||
expect(result.failureCount).toBe(1);
|
||||
expect(result.rateLimitedCount).toBe(0);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// All fail
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('handles all-fail scenario gracefully', async () => {
|
||||
const subtasks = [makeSubtask('f1'), makeSubtask('f2')];
|
||||
const runner = vi.fn().mockResolvedValue(makeResult('error')) as SubtaskSessionRunner;
|
||||
|
||||
const result = await runWithFakeTimers(() =>
|
||||
executeParallel(subtasks, runner, { maxConcurrency: 10 }),
|
||||
);
|
||||
|
||||
expect(result.successCount).toBe(0);
|
||||
expect(result.failureCount).toBe(2);
|
||||
expect(result.cancelled).toBe(false);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Rate limiting
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('tracks rate-limited subtasks separately', async () => {
|
||||
const subtasks = [makeSubtask('r1'), makeSubtask('r2')];
|
||||
|
||||
const runner = vi.fn()
|
||||
.mockResolvedValueOnce(makeResult('rate_limited'))
|
||||
.mockResolvedValueOnce(makeResult('completed')) as SubtaskSessionRunner;
|
||||
|
||||
const result = await runWithFakeTimers(() =>
|
||||
executeParallel(subtasks, runner, { maxConcurrency: 10 }),
|
||||
);
|
||||
|
||||
expect(result.rateLimitedCount).toBe(1);
|
||||
expect(result.successCount).toBe(1);
|
||||
});
|
||||
|
||||
it('calls onRateLimited callback when rate-limited result is detected in first batch', async () => {
|
||||
// Single-item batches (maxConcurrency=1) so back-off delay fires between batches
|
||||
const subtasks = [makeSubtask('rl1'), makeSubtask('rl2')];
|
||||
|
||||
const runner = vi.fn()
|
||||
.mockResolvedValueOnce(makeResult('rate_limited'))
|
||||
.mockResolvedValueOnce(makeResult('completed')) as SubtaskSessionRunner;
|
||||
|
||||
const onRateLimited = vi.fn();
|
||||
const config: ParallelExecutorConfig = { maxConcurrency: 1, onRateLimited };
|
||||
|
||||
await runWithFakeTimers(() => executeParallel(subtasks, runner, config));
|
||||
|
||||
expect(onRateLimited).toHaveBeenCalledWith(expect.any(Number));
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Concurrency limit batching
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('respects maxConcurrency and processes all tasks in batches', async () => {
|
||||
const subtasks = [
|
||||
makeSubtask('b1'), makeSubtask('b2'), makeSubtask('b3'),
|
||||
makeSubtask('b4'), makeSubtask('b5'),
|
||||
];
|
||||
const runner = vi.fn().mockResolvedValue(makeResult('completed')) as SubtaskSessionRunner;
|
||||
|
||||
const result = await runWithFakeTimers(() =>
|
||||
executeParallel(subtasks, runner, { maxConcurrency: 3 }),
|
||||
);
|
||||
|
||||
expect(result.successCount).toBe(5);
|
||||
expect(result.results).toHaveLength(5);
|
||||
expect(runner).toHaveBeenCalledTimes(5);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Callbacks — onSubtaskStart / onSubtaskComplete / onSubtaskFailed
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('calls onSubtaskStart for each subtask', async () => {
|
||||
const subtasks = [makeSubtask('c1'), makeSubtask('c2')];
|
||||
const runner = vi.fn().mockResolvedValue(makeResult('completed')) as SubtaskSessionRunner;
|
||||
const onSubtaskStart = vi.fn();
|
||||
|
||||
await runWithFakeTimers(() =>
|
||||
executeParallel(subtasks, runner, { maxConcurrency: 10, onSubtaskStart }),
|
||||
);
|
||||
|
||||
expect(onSubtaskStart).toHaveBeenCalledTimes(2);
|
||||
expect(onSubtaskStart).toHaveBeenCalledWith(expect.objectContaining({ id: 'c1' }));
|
||||
expect(onSubtaskStart).toHaveBeenCalledWith(expect.objectContaining({ id: 'c2' }));
|
||||
});
|
||||
|
||||
it('calls onSubtaskComplete for successful subtasks — single task (no stagger)', async () => {
|
||||
const subtasks = [makeSubtask('ok1')];
|
||||
const runner = vi.fn().mockResolvedValue(makeResult('completed')) as SubtaskSessionRunner;
|
||||
const onSubtaskComplete = vi.fn();
|
||||
|
||||
// Single item at index 0 → stagger = 0ms → no fake timers needed
|
||||
const result = await executeParallel(subtasks, runner, { maxConcurrency: 1, onSubtaskComplete });
|
||||
|
||||
expect(onSubtaskComplete).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'ok1' }),
|
||||
expect.objectContaining({ outcome: 'completed' }),
|
||||
);
|
||||
expect(result.successCount).toBe(1);
|
||||
});
|
||||
|
||||
it('calls onSubtaskFailed for error outcomes — single task', async () => {
|
||||
const subtasks = [makeSubtask('fail1')];
|
||||
const runner = vi.fn().mockResolvedValue(makeResult('error')) as SubtaskSessionRunner;
|
||||
const onSubtaskFailed = vi.fn();
|
||||
|
||||
const result = await executeParallel(subtasks, runner, { maxConcurrency: 1, onSubtaskFailed });
|
||||
|
||||
expect(onSubtaskFailed).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'fail1' }),
|
||||
expect.any(Error),
|
||||
);
|
||||
expect(result.failureCount).toBe(1);
|
||||
});
|
||||
|
||||
it('calls onSubtaskFailed when runner throws — single task', async () => {
|
||||
const subtasks = [makeSubtask('throw1')];
|
||||
const runner = vi.fn().mockRejectedValue(new Error('Unexpected crash')) as SubtaskSessionRunner;
|
||||
const onSubtaskFailed = vi.fn();
|
||||
|
||||
const result = await executeParallel(subtasks, runner, { maxConcurrency: 1, onSubtaskFailed });
|
||||
|
||||
expect(result.failureCount).toBe(1);
|
||||
expect(onSubtaskFailed).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'throw1' }),
|
||||
expect.any(Error),
|
||||
);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Cancellation via AbortSignal
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('marks cancelled=true when aborted before execution starts', async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
|
||||
const subtasks = [makeSubtask('x1'), makeSubtask('x2')];
|
||||
const runner = vi.fn().mockResolvedValue(makeResult('completed')) as SubtaskSessionRunner;
|
||||
|
||||
const result = await runWithFakeTimers(() =>
|
||||
executeParallel(subtasks, runner, {
|
||||
maxConcurrency: 10,
|
||||
abortSignal: controller.signal,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.cancelled).toBe(true);
|
||||
});
|
||||
|
||||
it('returns cancelled=true when aborted after first batch completes', async () => {
|
||||
const controller = new AbortController();
|
||||
const subtasks = [makeSubtask('a1'), makeSubtask('a2')];
|
||||
|
||||
const runner = vi.fn().mockImplementation(async (subtask: SubtaskInfo) => {
|
||||
if (subtask.id === 'a1') {
|
||||
controller.abort();
|
||||
}
|
||||
return makeResult('completed');
|
||||
}) as SubtaskSessionRunner;
|
||||
|
||||
const result = await runWithFakeTimers(() =>
|
||||
executeParallel(subtasks, runner, {
|
||||
maxConcurrency: 1,
|
||||
abortSignal: controller.signal,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.cancelled).toBe(true);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Rate-limited error from thrown exception — single task, no stagger
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('marks rateLimited=true when thrown error contains 429', async () => {
|
||||
const subtasks = [makeSubtask('rl-throw')];
|
||||
const runner = vi.fn().mockRejectedValue(new Error('HTTP 429 too many requests')) as SubtaskSessionRunner;
|
||||
|
||||
const result = await executeParallel(subtasks, runner, { maxConcurrency: 1 });
|
||||
|
||||
expect(result.results[0].rateLimited).toBe(true);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Result structure — single task, no stagger
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('includes session result in ParallelSubtaskResult when session ran', async () => {
|
||||
const subtasks = [makeSubtask('struct1')];
|
||||
const sessionResult = makeResult('completed');
|
||||
const runner = vi.fn().mockResolvedValue(sessionResult) as SubtaskSessionRunner;
|
||||
|
||||
const result = await executeParallel(subtasks, runner);
|
||||
|
||||
expect(result.results[0].result).toBeDefined();
|
||||
expect(result.results[0].result?.outcome).toBe('completed');
|
||||
});
|
||||
|
||||
it('includes error string when runner throws', async () => {
|
||||
const subtasks = [makeSubtask('err-str')];
|
||||
const runner = vi.fn().mockRejectedValue(new Error('crash detail')) as SubtaskSessionRunner;
|
||||
|
||||
const result = await executeParallel(subtasks, runner);
|
||||
|
||||
expect(result.results[0].error).toContain('crash detail');
|
||||
expect(result.results[0].success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,451 @@
|
||||
import path from 'node:path';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const mockReadFile = vi.fn();
|
||||
const mockWriteFile = vi.fn();
|
||||
const mockUnlink = vi.fn();
|
||||
|
||||
vi.mock('node:fs/promises', () => ({
|
||||
readFile: (...args: unknown[]) => mockReadFile(...args),
|
||||
writeFile: (...args: unknown[]) => mockWriteFile(...args),
|
||||
unlink: (...args: unknown[]) => mockUnlink(...args),
|
||||
}));
|
||||
|
||||
vi.mock('../../utils/json-repair', () => ({
|
||||
safeParseJson: (raw: string) => {
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../qa-reports', () => ({
|
||||
generateQAReport: vi.fn(() => '# QA Report'),
|
||||
generateEscalationReport: vi.fn(() => '# Escalation Report'),
|
||||
generateManualTestPlan: vi.fn().mockResolvedValue('# Manual Test Plan'),
|
||||
}));
|
||||
|
||||
// qa-loop.ts imports from '../schema' (relative to orchestration/)
|
||||
// which resolves to src/main/ai/schema/index.ts
|
||||
vi.mock('../../schema', () => ({
|
||||
QASignoffSchema: {},
|
||||
validateStructuredOutput: vi.fn((_data: unknown, _schema: unknown) => ({
|
||||
valid: true,
|
||||
data: _data,
|
||||
})),
|
||||
}));
|
||||
|
||||
import { QALoop } from '../qa-loop';
|
||||
import type { QALoopConfig, QASessionRunConfig } from '../qa-loop';
|
||||
import type { SessionResult } from '../../session/types';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SPEC_DIR = '/project/.auto-claude/specs/001-feature';
|
||||
const PROJECT_DIR = '/project';
|
||||
|
||||
function completedPlan(qaStatus?: 'approved' | 'rejected' | 'unknown') {
|
||||
const plan: Record<string, unknown> = {
|
||||
phases: [
|
||||
{ subtasks: [{ status: 'completed' }, { status: 'completed' }] },
|
||||
],
|
||||
};
|
||||
|
||||
if (qaStatus === 'approved') {
|
||||
plan.qa_signoff = { status: 'approved', issues_found: [] };
|
||||
} else if (qaStatus === 'rejected') {
|
||||
plan.qa_signoff = { status: 'rejected', issues_found: [{ title: 'Test failure', type: 'critical' }] };
|
||||
}
|
||||
// qaStatus === 'unknown' → no qa_signoff key
|
||||
|
||||
return JSON.stringify(plan);
|
||||
}
|
||||
|
||||
function makeSessionResult(outcome: SessionResult['outcome']): SessionResult {
|
||||
return {
|
||||
outcome,
|
||||
error: outcome === 'error' ? new Error('session error') : undefined,
|
||||
totalSteps: 1,
|
||||
lastMessage: '',
|
||||
} as unknown as SessionResult;
|
||||
}
|
||||
|
||||
function makeConfig(overrides: Partial<QALoopConfig> = {}): QALoopConfig {
|
||||
return {
|
||||
specDir: SPEC_DIR,
|
||||
projectDir: PROJECT_DIR,
|
||||
maxIterations: 5,
|
||||
generatePrompt: vi.fn().mockResolvedValue('system prompt'),
|
||||
runSession: vi.fn().mockResolvedValue(makeSessionResult('completed')),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('QALoop', () => {
|
||||
beforeEach(() => {
|
||||
mockReadFile.mockReset();
|
||||
mockWriteFile.mockReset().mockResolvedValue(undefined);
|
||||
mockUnlink.mockReset().mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Build completeness guard
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('returns error outcome when build is not complete', async () => {
|
||||
// Plan with a non-completed subtask
|
||||
const plan = JSON.stringify({
|
||||
phases: [{ subtasks: [{ status: 'pending' }] }],
|
||||
});
|
||||
|
||||
// No QA_FIX_REQUEST.md either
|
||||
mockReadFile.mockImplementation((path: string) => {
|
||||
if (path.endsWith('implementation_plan.json')) return Promise.resolve(plan);
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
});
|
||||
|
||||
const config = makeConfig();
|
||||
const loop = new QALoop(config);
|
||||
const outcome = await loop.run();
|
||||
|
||||
expect(outcome.approved).toBe(false);
|
||||
expect(outcome.reason).toBe('error');
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Already approved
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('returns approved immediately when QA signoff is already "approved"', async () => {
|
||||
const plan = completedPlan('approved');
|
||||
|
||||
mockReadFile.mockImplementation((path: string) => {
|
||||
if (path.endsWith('implementation_plan.json')) return Promise.resolve(plan);
|
||||
// QA_FIX_REQUEST.md does not exist
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
});
|
||||
|
||||
const config = makeConfig();
|
||||
const loop = new QALoop(config);
|
||||
const outcome = await loop.run();
|
||||
|
||||
expect(outcome.approved).toBe(true);
|
||||
expect(outcome.totalIterations).toBe(0);
|
||||
// runSession should NOT have been called (short-circuit)
|
||||
expect(config.runSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// QA approved on first iteration
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('approves on the first iteration when reviewer returns approved', async () => {
|
||||
// Let the reviewer run session set the approved state, then all subsequent reads return approved
|
||||
let sessionCallCount = 0;
|
||||
let _planReadCount = 0;
|
||||
|
||||
const runSession = vi.fn().mockImplementation(async () => {
|
||||
sessionCallCount++;
|
||||
return makeSessionResult('completed');
|
||||
});
|
||||
|
||||
mockReadFile.mockImplementation((path: string) => {
|
||||
if (path.endsWith('implementation_plan.json')) {
|
||||
_planReadCount++;
|
||||
// Before the reviewer has run, return no signoff (build complete, no qa yet)
|
||||
if (sessionCallCount === 0) return Promise.resolve(completedPlan());
|
||||
// After the reviewer ran, return approved
|
||||
return Promise.resolve(completedPlan('approved'));
|
||||
}
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
});
|
||||
|
||||
const config = makeConfig({ runSession, maxIterations: 5 });
|
||||
const loop = new QALoop(config);
|
||||
const outcome = await loop.run();
|
||||
|
||||
expect(outcome.approved).toBe(true);
|
||||
// Should have approved within the first few iterations
|
||||
expect(outcome.totalIterations).toBeGreaterThanOrEqual(1);
|
||||
// Only the reviewer should have been called (no fixer needed)
|
||||
const calls = runSession.mock.calls as Array<[QASessionRunConfig]>;
|
||||
expect(calls.every((c) => c[0].agentType === 'qa_reviewer')).toBe(true);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Rejected then approved on retry
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('runs fixer then approves on second iteration', async () => {
|
||||
// Track how many times runSession has been called so we know which "phase" we're in
|
||||
let sessionCallCount = 0;
|
||||
let planReadCount = 0;
|
||||
|
||||
const runSession = vi.fn().mockImplementation(async () => {
|
||||
sessionCallCount++;
|
||||
return makeSessionResult('completed');
|
||||
});
|
||||
|
||||
mockReadFile.mockImplementation((path: string) => {
|
||||
if (path.endsWith('implementation_plan.json')) {
|
||||
planReadCount++;
|
||||
if (planReadCount === 1) return Promise.resolve(completedPlan()); // isBuildComplete
|
||||
// Reviewer on iteration 1 ran when sessionCallCount >= 1
|
||||
// Serve rejected until fixer has run (sessionCallCount >= 2), then approved
|
||||
if (sessionCallCount < 2) {
|
||||
return Promise.resolve(completedPlan('rejected'));
|
||||
}
|
||||
return Promise.resolve(completedPlan('approved'));
|
||||
}
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
});
|
||||
|
||||
const config = makeConfig({ runSession, maxIterations: 5 });
|
||||
const loop = new QALoop(config);
|
||||
const outcome = await loop.run();
|
||||
|
||||
expect(outcome.approved).toBe(true);
|
||||
// At minimum: reviewer (iter 1) + fixer + reviewer (iter 2) = 3
|
||||
expect(sessionCallCount).toBeGreaterThanOrEqual(3);
|
||||
const calls = runSession.mock.calls as Array<[QASessionRunConfig]>;
|
||||
const agentTypes = calls.map((c) => c[0].agentType);
|
||||
expect(agentTypes).toContain('qa_reviewer');
|
||||
expect(agentTypes).toContain('qa_fixer');
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Max iterations reached
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('returns max_iterations when approval is never reached', async () => {
|
||||
// Always return "rejected" status with a unique issue each time
|
||||
// so recurring_issues threshold is never reached within maxIterations=2
|
||||
let planReadCount = 0;
|
||||
|
||||
mockReadFile.mockImplementation((path: string) => {
|
||||
if (path.endsWith('implementation_plan.json')) {
|
||||
planReadCount++;
|
||||
if (planReadCount === 1) return Promise.resolve(completedPlan()); // build complete check
|
||||
|
||||
// Return distinct issues each time to avoid recurring_issues escalation
|
||||
const plan = JSON.stringify({
|
||||
phases: [{ subtasks: [{ status: 'completed' }] }],
|
||||
qa_signoff: {
|
||||
status: 'rejected',
|
||||
issues_found: [{ title: `Unique issue ${planReadCount}`, type: 'warning' }],
|
||||
},
|
||||
});
|
||||
return Promise.resolve(plan);
|
||||
}
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
});
|
||||
|
||||
const config = makeConfig({ maxIterations: 2 });
|
||||
const loop = new QALoop(config);
|
||||
const outcome = await loop.run();
|
||||
|
||||
expect(outcome.approved).toBe(false);
|
||||
expect(outcome.reason).toBe('max_iterations');
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Consecutive error escalation
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('escalates after MAX_CONSECUTIVE_ERRORS (3) consecutive unknown status responses', async () => {
|
||||
let planReadCount = 0;
|
||||
|
||||
mockReadFile.mockImplementation((path: string) => {
|
||||
if (path.endsWith('implementation_plan.json')) {
|
||||
planReadCount++;
|
||||
if (planReadCount === 1) return Promise.resolve(completedPlan()); // build complete
|
||||
// Return a plan with no qa_signoff — "unknown" status
|
||||
const planWithNoSignoff = JSON.stringify({
|
||||
phases: [{ subtasks: [{ status: 'completed' }] }],
|
||||
});
|
||||
return Promise.resolve(planWithNoSignoff);
|
||||
}
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
});
|
||||
|
||||
const config = makeConfig({ maxIterations: 10 });
|
||||
const loop = new QALoop(config);
|
||||
const outcome = await loop.run();
|
||||
|
||||
expect(outcome.approved).toBe(false);
|
||||
expect(outcome.reason).toBe('consecutive_errors');
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Recurring issue detection
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('escalates when the same issue recurs 3 or more times', async () => {
|
||||
const recurringIssue = { title: 'Null pointer exception', type: 'critical' as const };
|
||||
const rejectedPlan = JSON.stringify({
|
||||
phases: [{ subtasks: [{ status: 'completed' }] }],
|
||||
qa_signoff: { status: 'rejected', issues_found: [recurringIssue] },
|
||||
});
|
||||
|
||||
let planReadCount = 0;
|
||||
|
||||
mockReadFile.mockImplementation((path: string) => {
|
||||
if (path.endsWith('implementation_plan.json')) {
|
||||
planReadCount++;
|
||||
if (planReadCount === 1) return Promise.resolve(completedPlan()); // build complete
|
||||
return Promise.resolve(rejectedPlan);
|
||||
}
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
});
|
||||
|
||||
const config = makeConfig({ maxIterations: 10 });
|
||||
const loop = new QALoop(config);
|
||||
const outcome = await loop.run();
|
||||
|
||||
expect(outcome.approved).toBe(false);
|
||||
expect(outcome.reason).toBe('recurring_issues');
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Cancellation via AbortSignal
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('returns cancelled outcome when aborted before first iteration runs', async () => {
|
||||
const controller = new AbortController();
|
||||
|
||||
mockReadFile.mockImplementation((path: string) => {
|
||||
if (path.endsWith('implementation_plan.json')) return Promise.resolve(completedPlan());
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
});
|
||||
|
||||
const config = makeConfig({ abortSignal: controller.signal, maxIterations: 5 });
|
||||
const loop = new QALoop(config);
|
||||
|
||||
// Abort after construction so the event listener fires
|
||||
controller.abort();
|
||||
|
||||
const outcome = await loop.run();
|
||||
|
||||
expect(outcome.approved).toBe(false);
|
||||
expect(outcome.reason).toBe('cancelled');
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Fixer error handling
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('returns error outcome when fixer session fails', async () => {
|
||||
let planReadCount = 0;
|
||||
|
||||
mockReadFile.mockImplementation((path: string) => {
|
||||
if (path.endsWith('implementation_plan.json')) {
|
||||
planReadCount++;
|
||||
if (planReadCount === 1) return Promise.resolve(completedPlan());
|
||||
return Promise.resolve(completedPlan('rejected'));
|
||||
}
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
});
|
||||
|
||||
const runSession = vi.fn()
|
||||
.mockResolvedValueOnce(makeSessionResult('completed')) // reviewer iteration 1
|
||||
.mockResolvedValueOnce(makeSessionResult('error')); // fixer fails
|
||||
|
||||
const config = makeConfig({ runSession, maxIterations: 5 });
|
||||
const loop = new QALoop(config);
|
||||
const outcome = await loop.run();
|
||||
|
||||
expect(outcome.approved).toBe(false);
|
||||
expect(outcome.reason).toBe('error');
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Reviewer cancelled mid-loop
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('returns cancelled when reviewer session is cancelled', async () => {
|
||||
let planReadCount = 0;
|
||||
|
||||
mockReadFile.mockImplementation((path: string) => {
|
||||
if (path.endsWith('implementation_plan.json')) {
|
||||
planReadCount++;
|
||||
if (planReadCount === 1) return Promise.resolve(completedPlan());
|
||||
return Promise.resolve(completedPlan());
|
||||
}
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
});
|
||||
|
||||
const runSession = vi.fn().mockResolvedValueOnce(makeSessionResult('cancelled'));
|
||||
|
||||
const config = makeConfig({ runSession, maxIterations: 5 });
|
||||
const loop = new QALoop(config);
|
||||
const outcome = await loop.run();
|
||||
|
||||
expect(outcome.approved).toBe(false);
|
||||
expect(outcome.reason).toBe('cancelled');
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Human feedback processing
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('processes QA_FIX_REQUEST.md before running the review loop', async () => {
|
||||
// QA_FIX_REQUEST.md exists
|
||||
mockReadFile.mockImplementation((path: string) => {
|
||||
if (path.endsWith('QA_FIX_REQUEST.md')) return Promise.resolve('Fix this please');
|
||||
if (path.endsWith('implementation_plan.json')) return Promise.resolve(completedPlan('approved'));
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
});
|
||||
|
||||
const runSession = vi.fn().mockResolvedValue(makeSessionResult('completed'));
|
||||
const config = makeConfig({ runSession, maxIterations: 5 });
|
||||
const loop = new QALoop(config);
|
||||
const outcome = await loop.run();
|
||||
|
||||
// Fixer should have been invoked for human feedback
|
||||
const calls = runSession.mock.calls as Array<[QASessionRunConfig]>;
|
||||
expect(calls.some((c) => c[0].agentType === 'qa_fixer')).toBe(true);
|
||||
// Fix request file should be deleted
|
||||
expect(mockUnlink).toHaveBeenCalledWith(path.join(SPEC_DIR, 'QA_FIX_REQUEST.md'));
|
||||
// Overall outcome should still reflect the QA result
|
||||
expect(outcome.approved).toBe(true);
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Events
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
it('emits qa-complete event with the final outcome', async () => {
|
||||
let planReadCount = 0;
|
||||
mockReadFile.mockImplementation((path: string) => {
|
||||
if (path.endsWith('implementation_plan.json')) {
|
||||
planReadCount++;
|
||||
if (planReadCount === 1) return Promise.resolve(completedPlan());
|
||||
return Promise.resolve(completedPlan('approved'));
|
||||
}
|
||||
return Promise.reject(new Error('ENOENT'));
|
||||
});
|
||||
|
||||
const config = makeConfig();
|
||||
const loop = new QALoop(config);
|
||||
|
||||
const completedEvents: unknown[] = [];
|
||||
loop.on('qa-complete', (outcome) => completedEvents.push(outcome));
|
||||
|
||||
await loop.run();
|
||||
|
||||
expect(completedEvents).toHaveLength(1);
|
||||
expect((completedEvents[0] as { approved: boolean }).approved).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,364 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const mockReadFile = vi.fn();
|
||||
const mockExistsSync = vi.fn();
|
||||
const mockReaddirSync = vi.fn();
|
||||
|
||||
vi.mock('node:fs/promises', () => ({
|
||||
readFile: (...args: unknown[]) => mockReadFile(...args),
|
||||
}));
|
||||
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: (...args: unknown[]) => mockExistsSync(...args),
|
||||
readdirSync: (...args: unknown[]) => mockReaddirSync(...args),
|
||||
}));
|
||||
|
||||
import {
|
||||
generateQAReport,
|
||||
generateEscalationReport,
|
||||
generateManualTestPlan,
|
||||
issuesSimilar,
|
||||
isNoTestProject,
|
||||
} from '../qa-reports';
|
||||
import type { QAIterationRecord, QAIssue } from '../qa-loop';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makeRecord(
|
||||
iteration: number,
|
||||
status: 'approved' | 'rejected' | 'error',
|
||||
issues: QAIssue[] = [],
|
||||
durationMs = 1000,
|
||||
): QAIterationRecord {
|
||||
return {
|
||||
iteration,
|
||||
status,
|
||||
issues,
|
||||
durationMs,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
function makeIssue(title: string, opts: Partial<QAIssue> = {}): QAIssue {
|
||||
return { title, ...opts };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// generateQAReport
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('generateQAReport', () => {
|
||||
it('produces a report with APPROVED status label', () => {
|
||||
const iterations: QAIterationRecord[] = [
|
||||
makeRecord(1, 'rejected', [makeIssue('Missing test')], 2000),
|
||||
makeRecord(2, 'approved', [], 1500),
|
||||
];
|
||||
|
||||
const report = generateQAReport(iterations, 'approved');
|
||||
|
||||
expect(report).toContain('APPROVED');
|
||||
expect(report).toContain('PASSED');
|
||||
expect(report).toContain('Total Iterations');
|
||||
expect(report).toContain('2');
|
||||
});
|
||||
|
||||
it('produces a report with ESCALATED status label', () => {
|
||||
const iterations: QAIterationRecord[] = [
|
||||
makeRecord(1, 'rejected', [makeIssue('Null pointer')], 500),
|
||||
];
|
||||
|
||||
const report = generateQAReport(iterations, 'escalated');
|
||||
|
||||
expect(report).toContain('ESCALATED');
|
||||
expect(report).toContain('FAILED');
|
||||
expect(report).toContain('escalated to human review');
|
||||
});
|
||||
|
||||
it('produces a report with MAX ITERATIONS REACHED label', () => {
|
||||
const iterations: QAIterationRecord[] = [
|
||||
makeRecord(1, 'rejected', [], 800),
|
||||
makeRecord(2, 'rejected', [], 800),
|
||||
];
|
||||
|
||||
const report = generateQAReport(iterations, 'max_iterations');
|
||||
|
||||
expect(report).toContain('MAX ITERATIONS REACHED');
|
||||
expect(report).toContain('FAILED');
|
||||
expect(report).toContain('maximum');
|
||||
});
|
||||
|
||||
it('handles empty iteration history gracefully', () => {
|
||||
const report = generateQAReport([], 'approved');
|
||||
|
||||
expect(report).toContain('No iterations recorded');
|
||||
expect(report).toContain('Total Iterations');
|
||||
});
|
||||
|
||||
it('includes issue details in iteration history section', () => {
|
||||
const issue = makeIssue('Type error in auth.ts', {
|
||||
type: 'critical',
|
||||
location: 'src/auth.ts:42',
|
||||
description: 'Property does not exist',
|
||||
fix_required: 'Add null check',
|
||||
});
|
||||
|
||||
const report = generateQAReport([makeRecord(1, 'rejected', [issue])], 'escalated');
|
||||
|
||||
expect(report).toContain('Type error in auth.ts');
|
||||
expect(report).toContain('[CRITICAL]');
|
||||
expect(report).toContain('src/auth.ts:42');
|
||||
expect(report).toContain('Property does not exist');
|
||||
expect(report).toContain('Add null check');
|
||||
});
|
||||
|
||||
it('calculates summary counts correctly', () => {
|
||||
const iterations: QAIterationRecord[] = [
|
||||
makeRecord(1, 'rejected', [makeIssue('A'), makeIssue('B')]),
|
||||
makeRecord(2, 'error', [makeIssue('C')]),
|
||||
makeRecord(3, 'approved', []),
|
||||
];
|
||||
|
||||
const report = generateQAReport(iterations, 'approved');
|
||||
|
||||
expect(report).toContain('Approved Iterations');
|
||||
expect(report).toContain('Rejected Iterations');
|
||||
expect(report).toContain('Error Iterations');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// generateEscalationReport
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('generateEscalationReport', () => {
|
||||
it('lists recurring issues by title', () => {
|
||||
const recurringIssues: QAIssue[] = [
|
||||
makeIssue('Database connection leak', {
|
||||
type: 'critical',
|
||||
location: 'src/db.ts',
|
||||
description: 'Connection is never closed',
|
||||
fix_required: 'Use try-finally block',
|
||||
}),
|
||||
];
|
||||
|
||||
const iterations: QAIterationRecord[] = [
|
||||
makeRecord(1, 'rejected', recurringIssues),
|
||||
makeRecord(2, 'rejected', recurringIssues),
|
||||
makeRecord(3, 'rejected', recurringIssues),
|
||||
];
|
||||
|
||||
const report = generateEscalationReport(iterations, recurringIssues);
|
||||
|
||||
expect(report).toContain('Human Intervention Required');
|
||||
expect(report).toContain('Database connection leak');
|
||||
expect(report).toContain('src/db.ts');
|
||||
expect(report).toContain('Connection is never closed');
|
||||
expect(report).toContain('Use try-finally block');
|
||||
});
|
||||
|
||||
it('includes summary statistics', () => {
|
||||
const issue = makeIssue('Error X');
|
||||
const iterations = [
|
||||
makeRecord(1, 'rejected', [issue]),
|
||||
makeRecord(2, 'rejected', [issue]),
|
||||
makeRecord(3, 'rejected', [issue]),
|
||||
];
|
||||
|
||||
const report = generateEscalationReport(iterations, [issue]);
|
||||
|
||||
expect(report).toContain('Total QA Iterations');
|
||||
expect(report).toContain('Total Issues Found');
|
||||
expect(report).toContain('Unique Issues');
|
||||
expect(report).toContain('Fix Success Rate');
|
||||
});
|
||||
|
||||
it('includes recommended actions section', () => {
|
||||
const report = generateEscalationReport([], []);
|
||||
|
||||
expect(report).toContain('Recommended Actions');
|
||||
expect(report).toContain('QA_FIX_REQUEST.md');
|
||||
});
|
||||
|
||||
it('includes most common issues when present', () => {
|
||||
const issue1 = makeIssue('Common bug');
|
||||
const issue2 = makeIssue('Rare bug');
|
||||
|
||||
const iterations = [
|
||||
makeRecord(1, 'rejected', [issue1, issue2]),
|
||||
makeRecord(2, 'rejected', [issue1]),
|
||||
makeRecord(3, 'rejected', [issue1]),
|
||||
];
|
||||
|
||||
const report = generateEscalationReport(iterations, [issue1]);
|
||||
|
||||
expect(report).toContain('Most Common Issues');
|
||||
expect(report).toContain('common bug');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// generateManualTestPlan
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('generateManualTestPlan', () => {
|
||||
const SPEC_DIR = '/project/.auto-claude/specs/001-feature';
|
||||
const PROJECT_DIR = '/project';
|
||||
|
||||
beforeEach(() => {
|
||||
mockReadFile.mockReset();
|
||||
mockExistsSync.mockReset().mockReturnValue(false);
|
||||
mockReaddirSync.mockReset().mockReturnValue([]);
|
||||
});
|
||||
|
||||
it('generates a basic test plan when spec.md is missing', async () => {
|
||||
mockReadFile.mockRejectedValue(new Error('ENOENT'));
|
||||
|
||||
const plan = await generateManualTestPlan(SPEC_DIR, PROJECT_DIR);
|
||||
|
||||
expect(plan).toContain('Manual Test Plan');
|
||||
expect(plan).toContain('Pre-Test Setup');
|
||||
expect(plan).toContain('Functional Tests');
|
||||
expect(plan).toContain('Sign-off');
|
||||
});
|
||||
|
||||
it('extracts acceptance criteria from spec.md when available', async () => {
|
||||
const specContent = `# Feature Spec
|
||||
|
||||
## Overview
|
||||
Some description.
|
||||
|
||||
## Acceptance Criteria
|
||||
- User can log in
|
||||
- User sees dashboard after login
|
||||
- Invalid credentials show error
|
||||
|
||||
## Technical Details
|
||||
Not relevant here.
|
||||
`;
|
||||
|
||||
mockReadFile.mockResolvedValue(specContent);
|
||||
|
||||
const plan = await generateManualTestPlan(SPEC_DIR, PROJECT_DIR);
|
||||
|
||||
expect(plan).toContain('User can log in');
|
||||
expect(plan).toContain('User sees dashboard after login');
|
||||
expect(plan).toContain('Invalid credentials show error');
|
||||
});
|
||||
|
||||
it('notes "no automated test framework" when none is detected', async () => {
|
||||
mockReadFile.mockRejectedValue(new Error('ENOENT'));
|
||||
// existsSync returns false → no test config found
|
||||
|
||||
const plan = await generateManualTestPlan(SPEC_DIR, PROJECT_DIR);
|
||||
|
||||
expect(plan).toContain('No automated test framework detected');
|
||||
});
|
||||
|
||||
it('notes "supplemental manual verification" when a test framework is present', async () => {
|
||||
mockReadFile.mockRejectedValue(new Error('ENOENT'));
|
||||
// Simulate vitest.config.ts existing
|
||||
mockExistsSync.mockImplementation((p: string) => p.endsWith('vitest.config.ts'));
|
||||
|
||||
const plan = await generateManualTestPlan(SPEC_DIR, PROJECT_DIR);
|
||||
|
||||
expect(plan).toContain('supplement to automated tests');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// issuesSimilar
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('issuesSimilar', () => {
|
||||
it('returns true for identical issues', () => {
|
||||
const issue = makeIssue('Null pointer exception', { description: 'Null reference in auth module' });
|
||||
expect(issuesSimilar(issue, issue)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true for issues with high token overlap', () => {
|
||||
const a = makeIssue('null pointer exception in auth module');
|
||||
const b = makeIssue('null pointer exception in auth module');
|
||||
expect(issuesSimilar(a, b)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false for completely different issues', () => {
|
||||
const a = makeIssue('Database connection timeout', { description: 'MySQL connection drops after 30s' });
|
||||
const b = makeIssue('UI button not rendering', { description: 'Submit button disappears on mobile' });
|
||||
expect(issuesSimilar(a, b)).toBe(false);
|
||||
});
|
||||
|
||||
it('strips common prefixes before comparing', () => {
|
||||
const a = makeIssue('error: null pointer exception');
|
||||
const b = makeIssue('bug: null pointer exception');
|
||||
// Both strip to "null pointer exception" — should be considered similar
|
||||
expect(issuesSimilar(a, b)).toBe(true);
|
||||
});
|
||||
|
||||
it('uses custom threshold when provided', () => {
|
||||
const a = makeIssue('Some issue here', { description: 'partial match description' });
|
||||
const b = makeIssue('Some issue here', { description: 'completely different thing' });
|
||||
// At very low threshold, should match on title alone
|
||||
expect(issuesSimilar(a, b, 0.1)).toBe(true);
|
||||
// At very high threshold, partial description overlap may fail
|
||||
expect(issuesSimilar(a, b, 0.99)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// isNoTestProject
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('isNoTestProject', () => {
|
||||
const PROJECT_DIR = '/my-project';
|
||||
|
||||
beforeEach(() => {
|
||||
mockExistsSync.mockReset().mockReturnValue(false);
|
||||
mockReaddirSync.mockReset().mockReturnValue([]);
|
||||
});
|
||||
|
||||
it('returns false when vitest.config.ts exists', () => {
|
||||
mockExistsSync.mockImplementation((p: string) => p.endsWith('vitest.config.ts'));
|
||||
expect(isNoTestProject('/spec', PROJECT_DIR)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when jest.config.js exists', () => {
|
||||
mockExistsSync.mockImplementation((p: string) => p.endsWith('jest.config.js'));
|
||||
expect(isNoTestProject('/spec', PROJECT_DIR)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when pytest.ini exists', () => {
|
||||
mockExistsSync.mockImplementation((p: string) => p.endsWith('pytest.ini'));
|
||||
expect(isNoTestProject('/spec', PROJECT_DIR)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when test files are found in __tests__ directory', () => {
|
||||
mockExistsSync.mockImplementation((p: string) => p.endsWith('__tests__'));
|
||||
mockReaddirSync.mockReturnValue(['auth.test.ts', 'utils.test.ts']);
|
||||
expect(isNoTestProject('/spec', PROJECT_DIR)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true when no test config files and no test directories exist', () => {
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
expect(isNoTestProject('/spec', PROJECT_DIR)).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true when test directories exist but contain no test files', () => {
|
||||
mockExistsSync.mockImplementation((p: string) => p.endsWith('tests'));
|
||||
mockReaddirSync.mockReturnValue(['README.md', 'fixtures.json']);
|
||||
expect(isNoTestProject('/spec', PROJECT_DIR)).toBe(true);
|
||||
});
|
||||
|
||||
it('handles readdir errors gracefully and returns true', () => {
|
||||
mockExistsSync.mockImplementation((p: string) => p.endsWith('tests'));
|
||||
mockReaddirSync.mockImplementation(() => {
|
||||
throw new Error('Permission denied');
|
||||
});
|
||||
expect(isNoTestProject('/spec', PROJECT_DIR)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,500 @@
|
||||
import path from 'node:path';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks — declared before any imports that pull in the mocked modules
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const mockReadFile = vi.fn();
|
||||
const mockWriteFile = vi.fn();
|
||||
const mockMkdir = vi.fn();
|
||||
|
||||
vi.mock('node:fs/promises', () => ({
|
||||
readFile: (...args: unknown[]) => mockReadFile(...args),
|
||||
writeFile: (...args: unknown[]) => mockWriteFile(...args),
|
||||
mkdir: (...args: unknown[]) => mockMkdir(...args),
|
||||
}));
|
||||
|
||||
vi.mock('../../utils/json-repair', () => ({
|
||||
safeParseJson: (raw: string) => {
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
import { RecoveryManager } from '../recovery-manager';
|
||||
import type { BuildCheckpoint, FailureType } from '../recovery-manager';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const PROJECT_DIR = path.join(path.sep, 'project');
|
||||
const SPEC_DIR = path.join(PROJECT_DIR, '.auto-claude', 'specs', '001-feature');
|
||||
const MEMORY_DIR = path.join(SPEC_DIR, 'memory');
|
||||
const ATTEMPT_HISTORY_PATH = path.join(MEMORY_DIR, 'attempt_history.json');
|
||||
|
||||
function makeHistory(
|
||||
subtasks: Record<string, Array<{ timestamp: string; error: string; failureType: FailureType; errorHash: string }>>,
|
||||
stuckSubtasks: string[] = [],
|
||||
) {
|
||||
return JSON.stringify({
|
||||
subtasks,
|
||||
stuckSubtasks,
|
||||
metadata: { createdAt: new Date().toISOString(), lastUpdated: new Date().toISOString() },
|
||||
});
|
||||
}
|
||||
|
||||
function recentTimestamp() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function oldTimestamp() {
|
||||
// 3 hours ago — outside the 2-hour window
|
||||
return new Date(Date.now() - 3 * 60 * 60 * 1_000).toISOString();
|
||||
}
|
||||
|
||||
function createManager() {
|
||||
return new RecoveryManager(SPEC_DIR, PROJECT_DIR);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// classifyFailure
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('RecoveryManager.classifyFailure', () => {
|
||||
let manager: RecoveryManager;
|
||||
|
||||
beforeEach(() => {
|
||||
manager = createManager();
|
||||
});
|
||||
|
||||
const cases: Array<[string, FailureType]> = [
|
||||
['SyntaxError: Unexpected token', 'broken_build'],
|
||||
['Module not found: react', 'broken_build'],
|
||||
['compilation error in main.ts', 'broken_build'],
|
||||
['cannot find module lodash', 'broken_build'],
|
||||
// 'IndentationError' is not in the source's buildErrors list — removed
|
||||
['parse error in config.js', 'broken_build'],
|
||||
|
||||
['verification failed: response mismatch', 'verification_failed'],
|
||||
['AssertionError: expected 1 to equal 2', 'verification_failed'],
|
||||
['test failed: missing element', 'verification_failed'],
|
||||
['status code 404 received', 'verification_failed'],
|
||||
|
||||
['context window exceeded', 'context_exhausted'],
|
||||
['token limit reached', 'context_exhausted'],
|
||||
['maximum length of response reached', 'context_exhausted'],
|
||||
|
||||
['429 too many requests', 'rate_limited'],
|
||||
['rate limit exceeded', 'rate_limited'],
|
||||
['too many requests from your IP', 'rate_limited'],
|
||||
|
||||
['401 unauthorized access', 'auth_failure'],
|
||||
['auth token expired', 'auth_failure'],
|
||||
|
||||
['a totally random and obscure crash', 'unknown'],
|
||||
['', 'unknown'],
|
||||
];
|
||||
|
||||
it.each(cases)('classifies "%s" as %s', (error, expected) => {
|
||||
expect(manager.classifyFailure(error, 'subtask-1')).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Checkpoint save / load round-trip
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('RecoveryManager checkpoint round-trip', () => {
|
||||
let manager: RecoveryManager;
|
||||
|
||||
beforeEach(() => {
|
||||
mockWriteFile.mockReset().mockResolvedValue(undefined);
|
||||
mockReadFile.mockReset();
|
||||
manager = createManager();
|
||||
});
|
||||
|
||||
it('writes a parseable checkpoint and loads it back', async () => {
|
||||
const checkpoint: BuildCheckpoint = {
|
||||
specId: '001',
|
||||
phase: 'coding',
|
||||
lastCompletedSubtaskId: 'subtask-3',
|
||||
totalSubtasks: 5,
|
||||
completedSubtasks: 3,
|
||||
stuckSubtasks: [],
|
||||
timestamp: new Date().toISOString(),
|
||||
isComplete: false,
|
||||
};
|
||||
|
||||
// Save captures what was written
|
||||
let writtenContent = '';
|
||||
mockWriteFile.mockImplementation((_path: string, content: string) => {
|
||||
writtenContent = content;
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
await manager.saveCheckpoint(checkpoint);
|
||||
|
||||
// Verify writeFile was called with the progress file path
|
||||
expect(mockWriteFile).toHaveBeenCalledWith(
|
||||
path.join(SPEC_DIR, 'build-progress.txt'),
|
||||
expect.stringContaining('spec_id: 001'),
|
||||
'utf-8',
|
||||
);
|
||||
|
||||
// Now load the checkpoint from what was written
|
||||
mockReadFile.mockResolvedValueOnce(writtenContent);
|
||||
const loaded = await manager.loadCheckpoint();
|
||||
|
||||
expect(loaded).not.toBeNull();
|
||||
expect(loaded?.specId).toBe('001');
|
||||
expect(loaded?.phase).toBe('coding');
|
||||
expect(loaded?.lastCompletedSubtaskId).toBe('subtask-3');
|
||||
expect(loaded?.totalSubtasks).toBe(5);
|
||||
expect(loaded?.completedSubtasks).toBe(3);
|
||||
expect(loaded?.isComplete).toBe(false);
|
||||
});
|
||||
|
||||
it('saves lastCompletedSubtaskId=null as "none" and reloads as null', async () => {
|
||||
const checkpoint: BuildCheckpoint = {
|
||||
specId: '002',
|
||||
phase: 'planning',
|
||||
lastCompletedSubtaskId: null,
|
||||
totalSubtasks: 3,
|
||||
completedSubtasks: 0,
|
||||
stuckSubtasks: [],
|
||||
timestamp: new Date().toISOString(),
|
||||
isComplete: false,
|
||||
};
|
||||
|
||||
let writtenContent = '';
|
||||
mockWriteFile.mockImplementation((_path: string, content: string) => {
|
||||
writtenContent = content;
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
await manager.saveCheckpoint(checkpoint);
|
||||
expect(writtenContent).toContain('last_completed_subtask: none');
|
||||
|
||||
mockReadFile.mockResolvedValueOnce(writtenContent);
|
||||
const loaded = await manager.loadCheckpoint();
|
||||
expect(loaded?.lastCompletedSubtaskId).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when no checkpoint file exists', async () => {
|
||||
mockReadFile.mockRejectedValueOnce(new Error('ENOENT'));
|
||||
const loaded = await manager.loadCheckpoint();
|
||||
expect(loaded).toBeNull();
|
||||
});
|
||||
|
||||
it('saves stuckSubtasks correctly', async () => {
|
||||
const checkpoint: BuildCheckpoint = {
|
||||
specId: '003',
|
||||
phase: 'coding',
|
||||
lastCompletedSubtaskId: null,
|
||||
totalSubtasks: 4,
|
||||
completedSubtasks: 1,
|
||||
stuckSubtasks: ['subtask-1', 'subtask-2'],
|
||||
timestamp: new Date().toISOString(),
|
||||
isComplete: false,
|
||||
};
|
||||
|
||||
let writtenContent = '';
|
||||
mockWriteFile.mockImplementation((_path: string, content: string) => {
|
||||
writtenContent = content;
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
await manager.saveCheckpoint(checkpoint);
|
||||
|
||||
mockReadFile.mockResolvedValueOnce(writtenContent);
|
||||
const loaded = await manager.loadCheckpoint();
|
||||
expect(loaded?.stuckSubtasks).toEqual(['subtask-1', 'subtask-2']);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Circular fix detection
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('RecoveryManager.isCircularFix', () => {
|
||||
let manager: RecoveryManager;
|
||||
|
||||
beforeEach(() => {
|
||||
mockReadFile.mockReset();
|
||||
mockWriteFile.mockReset().mockResolvedValue(undefined);
|
||||
manager = createManager();
|
||||
});
|
||||
|
||||
it('returns false when fewer than 3 identical errors exist', async () => {
|
||||
// Produce a real hash by calling classifyFailure indirectly
|
||||
// We need the same hash that simpleHash("same error") would produce.
|
||||
// We'll record 2 attempts with the same error, then check.
|
||||
const sameError = 'same error message';
|
||||
|
||||
// Build a history with 2 records that share the same errorHash
|
||||
// We compute the hash the same way the source does: via recordAttempt
|
||||
// Here we mock the file system to return a pre-built history.
|
||||
// For simplicity, we simulate 2 identical hashes manually.
|
||||
const history = {
|
||||
subtasks: {
|
||||
'task-1': [
|
||||
{ timestamp: recentTimestamp(), error: sameError, failureType: 'unknown', errorHash: 'aaa' },
|
||||
{ timestamp: recentTimestamp(), error: sameError, failureType: 'unknown', errorHash: 'aaa' },
|
||||
],
|
||||
},
|
||||
stuckSubtasks: [],
|
||||
metadata: { createdAt: new Date().toISOString(), lastUpdated: new Date().toISOString() },
|
||||
};
|
||||
|
||||
mockReadFile.mockResolvedValue(JSON.stringify(history));
|
||||
const result = await manager.isCircularFix('task-1');
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('returns true when 3 or more identical error hashes exist within the window', async () => {
|
||||
const history = {
|
||||
subtasks: {
|
||||
'task-1': [
|
||||
{ timestamp: recentTimestamp(), error: 'err', failureType: 'unknown', errorHash: 'bbb' },
|
||||
{ timestamp: recentTimestamp(), error: 'err', failureType: 'unknown', errorHash: 'bbb' },
|
||||
{ timestamp: recentTimestamp(), error: 'err', failureType: 'unknown', errorHash: 'bbb' },
|
||||
],
|
||||
},
|
||||
stuckSubtasks: [],
|
||||
metadata: { createdAt: new Date().toISOString(), lastUpdated: new Date().toISOString() },
|
||||
};
|
||||
|
||||
mockReadFile.mockResolvedValue(JSON.stringify(history));
|
||||
const result = await manager.isCircularFix('task-1');
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores attempts outside the 2-hour window', async () => {
|
||||
const history = {
|
||||
subtasks: {
|
||||
'task-1': [
|
||||
// Two old entries — outside window
|
||||
{ timestamp: oldTimestamp(), error: 'err', failureType: 'unknown', errorHash: 'ccc' },
|
||||
{ timestamp: oldTimestamp(), error: 'err', failureType: 'unknown', errorHash: 'ccc' },
|
||||
{ timestamp: oldTimestamp(), error: 'err', failureType: 'unknown', errorHash: 'ccc' },
|
||||
// One recent entry
|
||||
{ timestamp: recentTimestamp(), error: 'err', failureType: 'unknown', errorHash: 'ccc' },
|
||||
],
|
||||
},
|
||||
stuckSubtasks: [],
|
||||
metadata: { createdAt: new Date().toISOString(), lastUpdated: new Date().toISOString() },
|
||||
};
|
||||
|
||||
mockReadFile.mockResolvedValue(JSON.stringify(history));
|
||||
const result = await manager.isCircularFix('task-1');
|
||||
// Only 1 recent entry → not circular
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false for a subtask with no attempt history', async () => {
|
||||
mockReadFile.mockResolvedValue(makeHistory({}));
|
||||
const result = await manager.isCircularFix('no-such-task');
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Attempt window filtering via getAttemptCount
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('RecoveryManager.getAttemptCount', () => {
|
||||
let manager: RecoveryManager;
|
||||
|
||||
beforeEach(() => {
|
||||
mockReadFile.mockReset();
|
||||
mockWriteFile.mockReset().mockResolvedValue(undefined);
|
||||
manager = createManager();
|
||||
});
|
||||
|
||||
it('counts only recent attempts within the 2-hour window', async () => {
|
||||
const history = {
|
||||
subtasks: {
|
||||
'task-x': [
|
||||
{ timestamp: oldTimestamp(), error: 'old error', failureType: 'unknown', errorHash: 'h1' },
|
||||
{ timestamp: recentTimestamp(), error: 'new error 1', failureType: 'unknown', errorHash: 'h2' },
|
||||
{ timestamp: recentTimestamp(), error: 'new error 2', failureType: 'unknown', errorHash: 'h3' },
|
||||
],
|
||||
},
|
||||
stuckSubtasks: [],
|
||||
metadata: { createdAt: new Date().toISOString(), lastUpdated: new Date().toISOString() },
|
||||
};
|
||||
|
||||
mockReadFile.mockResolvedValue(JSON.stringify(history));
|
||||
const count = await manager.getAttemptCount('task-x');
|
||||
expect(count).toBe(2);
|
||||
});
|
||||
|
||||
it('returns 0 for unknown subtask', async () => {
|
||||
mockReadFile.mockResolvedValue(makeHistory({}));
|
||||
const count = await manager.getAttemptCount('ghost-task');
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// determineRecoveryAction
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('RecoveryManager.determineRecoveryAction', () => {
|
||||
let manager: RecoveryManager;
|
||||
|
||||
beforeEach(() => {
|
||||
mockReadFile.mockReset();
|
||||
mockWriteFile.mockReset().mockResolvedValue(undefined);
|
||||
manager = createManager();
|
||||
});
|
||||
|
||||
it('escalates immediately when circular fix detected', async () => {
|
||||
// 3 identical error hashes → circular
|
||||
const history = {
|
||||
subtasks: {
|
||||
'task-circ': [
|
||||
{ timestamp: recentTimestamp(), error: 'err', failureType: 'unknown', errorHash: 'xyz' },
|
||||
{ timestamp: recentTimestamp(), error: 'err', failureType: 'unknown', errorHash: 'xyz' },
|
||||
{ timestamp: recentTimestamp(), error: 'err', failureType: 'unknown', errorHash: 'xyz' },
|
||||
],
|
||||
},
|
||||
stuckSubtasks: [],
|
||||
metadata: { createdAt: new Date().toISOString(), lastUpdated: new Date().toISOString() },
|
||||
};
|
||||
mockReadFile.mockResolvedValue(JSON.stringify(history));
|
||||
|
||||
const action = await manager.determineRecoveryAction('task-circ', 'err', 5);
|
||||
expect(action.action).toBe('escalate');
|
||||
expect(action.reason).toMatch(/circular/i);
|
||||
});
|
||||
|
||||
it('skips when attempt count >= maxRetries', async () => {
|
||||
const history = {
|
||||
subtasks: {
|
||||
'task-skip': [
|
||||
{ timestamp: recentTimestamp(), error: 'fail', failureType: 'unknown', errorHash: 'a1' },
|
||||
{ timestamp: recentTimestamp(), error: 'fail', failureType: 'unknown', errorHash: 'a2' },
|
||||
{ timestamp: recentTimestamp(), error: 'fail', failureType: 'unknown', errorHash: 'a3' },
|
||||
],
|
||||
},
|
||||
stuckSubtasks: [],
|
||||
metadata: { createdAt: new Date().toISOString(), lastUpdated: new Date().toISOString() },
|
||||
};
|
||||
mockReadFile.mockResolvedValue(JSON.stringify(history));
|
||||
|
||||
const action = await manager.determineRecoveryAction('task-skip', 'fail', 3);
|
||||
expect(action.action).toBe('skip');
|
||||
expect(action.reason).toMatch(/max retries/i);
|
||||
});
|
||||
|
||||
it('escalates on auth failure', async () => {
|
||||
mockReadFile.mockResolvedValue(makeHistory({ 'task-auth': [] }));
|
||||
const action = await manager.determineRecoveryAction('task-auth', '401 unauthorized', 5);
|
||||
expect(action.action).toBe('escalate');
|
||||
expect(action.reason).toMatch(/auth/i);
|
||||
});
|
||||
|
||||
it('retries on rate limit', async () => {
|
||||
mockReadFile.mockResolvedValue(makeHistory({ 'task-rl': [] }));
|
||||
const action = await manager.determineRecoveryAction('task-rl', '429 rate limit exceeded', 5);
|
||||
expect(action.action).toBe('retry');
|
||||
expect(action.reason).toMatch(/rate limit/i);
|
||||
});
|
||||
|
||||
it('retries on context exhaustion', async () => {
|
||||
mockReadFile.mockResolvedValue(makeHistory({ 'task-ctx': [] }));
|
||||
const action = await manager.determineRecoveryAction('task-ctx', 'context window exceeded', 5);
|
||||
expect(action.action).toBe('retry');
|
||||
expect(action.reason).toMatch(/context/i);
|
||||
});
|
||||
|
||||
it('defaults to retry for unknown failure types', async () => {
|
||||
mockReadFile.mockResolvedValue(makeHistory({ 'task-unk': [] }));
|
||||
const action = await manager.determineRecoveryAction('task-unk', 'something weird', 5);
|
||||
expect(action.action).toBe('retry');
|
||||
expect(action.target).toBe('task-unk');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// init — directory creation and history bootstrap
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('RecoveryManager.init', () => {
|
||||
let manager: RecoveryManager;
|
||||
|
||||
beforeEach(() => {
|
||||
mockMkdir.mockReset().mockResolvedValue(undefined);
|
||||
mockReadFile.mockReset();
|
||||
mockWriteFile.mockReset().mockResolvedValue(undefined);
|
||||
manager = createManager();
|
||||
});
|
||||
|
||||
it('creates memory directory with recursive flag', async () => {
|
||||
// Simulate history file already existing
|
||||
mockReadFile.mockResolvedValueOnce(makeHistory({}));
|
||||
await manager.init();
|
||||
expect(mockMkdir).toHaveBeenCalledWith(MEMORY_DIR, { recursive: true });
|
||||
});
|
||||
|
||||
it('writes an empty history when no history file exists', async () => {
|
||||
mockReadFile.mockRejectedValueOnce(new Error('ENOENT'));
|
||||
await manager.init();
|
||||
expect(mockWriteFile).toHaveBeenCalledWith(
|
||||
ATTEMPT_HISTORY_PATH,
|
||||
expect.stringContaining('"subtasks"'),
|
||||
'utf-8',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// markStuck / isStuck
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('RecoveryManager stuck tracking', () => {
|
||||
let manager: RecoveryManager;
|
||||
|
||||
beforeEach(() => {
|
||||
mockReadFile.mockReset();
|
||||
mockWriteFile.mockReset().mockResolvedValue(undefined);
|
||||
manager = createManager();
|
||||
});
|
||||
|
||||
it('marks a subtask as stuck and detects it', async () => {
|
||||
let storedHistory = makeHistory({}, []);
|
||||
|
||||
mockReadFile.mockImplementation(() => Promise.resolve(storedHistory));
|
||||
mockWriteFile.mockImplementation((_path: string, content: string) => {
|
||||
storedHistory = content;
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
await manager.markStuck('task-stuck');
|
||||
|
||||
expect(await manager.isStuck('task-stuck')).toBe(true);
|
||||
expect(await manager.isStuck('task-fine')).toBe(false);
|
||||
});
|
||||
|
||||
it('does not duplicate a subtask when marked stuck twice', async () => {
|
||||
let storedHistory = makeHistory({}, []);
|
||||
|
||||
mockReadFile.mockImplementation(() => Promise.resolve(storedHistory));
|
||||
mockWriteFile.mockImplementation((_path: string, content: string) => {
|
||||
storedHistory = content;
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
await manager.markStuck('task-dup');
|
||||
await manager.markStuck('task-dup');
|
||||
|
||||
const parsed = JSON.parse(storedHistory) as { stuckSubtasks: string[] };
|
||||
expect(parsed.stuckSubtasks.filter((id) => id === 'task-dup')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,231 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// =============================================================================
|
||||
// Mocks — must be declared before any imports that use them
|
||||
// =============================================================================
|
||||
|
||||
const mockGenerateText = vi.fn();
|
||||
|
||||
vi.mock('ai', () => ({
|
||||
generateText: (...args: unknown[]) => mockGenerateText(...args),
|
||||
}));
|
||||
|
||||
const mockCreateSimpleClient = vi.fn();
|
||||
|
||||
vi.mock('../../client/factory', () => ({
|
||||
createSimpleClient: (...args: unknown[]) => mockCreateSimpleClient(...args),
|
||||
}));
|
||||
|
||||
// =============================================================================
|
||||
// Import after mocking
|
||||
// =============================================================================
|
||||
|
||||
import { generateChangelog } from '../changelog';
|
||||
import type { ChangelogConfig } from '../changelog';
|
||||
|
||||
// =============================================================================
|
||||
// Helpers
|
||||
// =============================================================================
|
||||
|
||||
/** A fake model object used by the mock client */
|
||||
const fakeModel = { modelId: 'claude-haiku-test' };
|
||||
|
||||
function makeMockClient(systemPrompt = 'You are a technical writer.') {
|
||||
return { model: fakeModel, systemPrompt };
|
||||
}
|
||||
|
||||
function baseConfig(overrides: Partial<ChangelogConfig> = {}): ChangelogConfig {
|
||||
return {
|
||||
projectName: 'TestProject',
|
||||
version: '1.0.0',
|
||||
sourceMode: 'tasks',
|
||||
tasks: [
|
||||
{ title: 'Add dark mode', description: 'Implemented dark mode toggle', category: 'feature' },
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Tests
|
||||
// =============================================================================
|
||||
|
||||
describe('generateChangelog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockCreateSimpleClient.mockResolvedValue(makeMockClient());
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Successful generation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns success with trimmed text when LLM responds', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: ' ## [1.0.0]\n\n### Added\n- Dark mode\n ' });
|
||||
|
||||
const result = await generateChangelog(baseConfig());
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.text).toBe('## [1.0.0]\n\n### Added\n- Dark mode');
|
||||
expect(result.error).toBeUndefined();
|
||||
});
|
||||
|
||||
it('passes project name and version in the prompt to createSimpleClient', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: '## [2.0.0]' });
|
||||
|
||||
await generateChangelog(baseConfig({ projectName: 'MyApp', version: '2.0.0' }));
|
||||
|
||||
// createSimpleClient receives system-level configuration
|
||||
expect(mockCreateSimpleClient).toHaveBeenCalledOnce();
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs).toHaveProperty('modelShorthand');
|
||||
expect(clientArgs).toHaveProperty('thinkingLevel');
|
||||
});
|
||||
|
||||
it('passes model and systemPrompt from client to generateText', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: '## [1.0.0]' });
|
||||
|
||||
await generateChangelog(baseConfig());
|
||||
|
||||
expect(mockGenerateText).toHaveBeenCalledOnce();
|
||||
const callArgs = mockGenerateText.mock.calls[0][0];
|
||||
expect(callArgs.model).toBe(fakeModel);
|
||||
expect(callArgs.system).toBe('You are a technical writer.');
|
||||
expect(callArgs.prompt).toContain('TestProject');
|
||||
expect(callArgs.prompt).toContain('1.0.0');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Task mode — prompt content
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('includes task titles and categories in prompt for tasks mode', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: '## [1.0.0]' });
|
||||
|
||||
const config = baseConfig({
|
||||
tasks: [
|
||||
{ title: 'My feature', description: 'desc', category: 'feature', issueNumber: 42 },
|
||||
],
|
||||
});
|
||||
await generateChangelog(config);
|
||||
|
||||
const prompt = mockGenerateText.mock.calls[0][0].prompt as string;
|
||||
expect(prompt).toContain('My feature');
|
||||
expect(prompt).toContain('feature');
|
||||
expect(prompt).toContain('#42');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Git history / branch-diff modes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('includes commit messages in prompt for git-history mode', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: '## [1.0.0]' });
|
||||
|
||||
await generateChangelog(
|
||||
baseConfig({ sourceMode: 'git-history', commits: 'feat: add login\nfix: bug #5' }),
|
||||
);
|
||||
|
||||
const prompt = mockGenerateText.mock.calls[0][0].prompt as string;
|
||||
expect(prompt).toContain('feat: add login');
|
||||
});
|
||||
|
||||
it('truncates commits to 5000 chars', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: '## [1.0.0]' });
|
||||
const longCommits = 'x'.repeat(10_000);
|
||||
|
||||
await generateChangelog(baseConfig({ sourceMode: 'branch-diff', commits: longCommits }));
|
||||
|
||||
const prompt = mockGenerateText.mock.calls[0][0].prompt as string;
|
||||
// The 'x'.repeat(10000) block should be truncated — prompt must not exceed
|
||||
// 5000 'x' chars plus surrounding text
|
||||
const xCount = (prompt.match(/x/g) ?? []).length;
|
||||
expect(xCount).toBeLessThanOrEqual(5000);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Previous changelog style reference
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('includes previousChangelog when provided', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: '## [1.0.0]' });
|
||||
|
||||
await generateChangelog(
|
||||
baseConfig({ previousChangelog: '## [0.9.0]\n\n### Added\n- Old feature' }),
|
||||
);
|
||||
|
||||
const prompt = mockGenerateText.mock.calls[0][0].prompt as string;
|
||||
expect(prompt).toContain('Previous Changelog');
|
||||
expect(prompt).toContain('0.9.0');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Default model / thinking level
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('uses sonnet model and low thinking level by default', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: '## [1.0.0]' });
|
||||
|
||||
await generateChangelog(baseConfig());
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('sonnet');
|
||||
expect(clientArgs.thinkingLevel).toBe('low');
|
||||
});
|
||||
|
||||
it('accepts custom modelShorthand and thinkingLevel', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: '## [1.0.0]' });
|
||||
|
||||
await generateChangelog(baseConfig({ modelShorthand: 'haiku', thinkingLevel: 'high' }));
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('haiku');
|
||||
expect(clientArgs.thinkingLevel).toBe('high');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Empty response handling
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns failure when LLM returns empty text', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: ' ' });
|
||||
|
||||
const result = await generateChangelog(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.text).toBe('');
|
||||
expect(result.error).toBe('Empty response from AI');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Error handling
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns failure with error message when generateText throws', async () => {
|
||||
mockGenerateText.mockRejectedValue(new Error('Rate limit exceeded'));
|
||||
|
||||
const result = await generateChangelog(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.text).toBe('');
|
||||
expect(result.error).toBe('Rate limit exceeded');
|
||||
});
|
||||
|
||||
it('returns failure with string coercion when non-Error is thrown', async () => {
|
||||
mockGenerateText.mockRejectedValue('timeout');
|
||||
|
||||
const result = await generateChangelog(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('timeout');
|
||||
});
|
||||
|
||||
it('returns failure when createSimpleClient throws', async () => {
|
||||
mockCreateSimpleClient.mockRejectedValue(new Error('No auth available'));
|
||||
|
||||
const result = await generateChangelog(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('No auth available');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,230 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// =============================================================================
|
||||
// Mocks — must be declared before any imports that use them
|
||||
// =============================================================================
|
||||
|
||||
const mockGenerateText = vi.fn();
|
||||
|
||||
vi.mock('ai', () => ({
|
||||
generateText: (...args: unknown[]) => mockGenerateText(...args),
|
||||
}));
|
||||
|
||||
const mockCreateSimpleClient = vi.fn();
|
||||
|
||||
vi.mock('../../client/factory', () => ({
|
||||
createSimpleClient: (...args: unknown[]) => mockCreateSimpleClient(...args),
|
||||
}));
|
||||
|
||||
// Mock filesystem access so tests are hermetic
|
||||
const mockExistsSync = vi.fn();
|
||||
const mockReadFileSync = vi.fn();
|
||||
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: (...args: unknown[]) => mockExistsSync(...args),
|
||||
readFileSync: (...args: unknown[]) => mockReadFileSync(...args),
|
||||
}));
|
||||
|
||||
// json-repair is used by the commit-message runner for safeParseJson
|
||||
vi.mock('../../../utils/json-repair', () => ({
|
||||
safeParseJson: (text: string) => {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
// =============================================================================
|
||||
// Import after mocking
|
||||
// =============================================================================
|
||||
|
||||
import { generateCommitMessage } from '../commit-message';
|
||||
import type { CommitMessageConfig } from '../commit-message';
|
||||
|
||||
// =============================================================================
|
||||
// Helpers
|
||||
// =============================================================================
|
||||
|
||||
const fakeModel = { modelId: 'claude-haiku-test' };
|
||||
|
||||
function makeMockClient(systemPrompt = 'You are a Git expert.') {
|
||||
return { model: fakeModel, systemPrompt };
|
||||
}
|
||||
|
||||
function baseConfig(overrides: Partial<CommitMessageConfig> = {}): CommitMessageConfig {
|
||||
return {
|
||||
projectDir: '/project',
|
||||
specName: '001-add-feature',
|
||||
diffSummary: '+5 -2 src/app.ts',
|
||||
filesChanged: ['src/app.ts', 'src/utils.ts'],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Tests
|
||||
// =============================================================================
|
||||
|
||||
describe('generateCommitMessage', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockCreateSimpleClient.mockResolvedValue(makeMockClient());
|
||||
// By default, spec directory does not exist
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Successful generation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns trimmed AI-generated commit message on success', async () => {
|
||||
mockGenerateText.mockResolvedValue({
|
||||
text: ' feat(app): add authentication flow\n\nImplemented OAuth2.\n ',
|
||||
});
|
||||
|
||||
const result = await generateCommitMessage(baseConfig());
|
||||
|
||||
expect(result).toBe('feat(app): add authentication flow\n\nImplemented OAuth2.');
|
||||
});
|
||||
|
||||
it('passes model and systemPrompt from client to generateText', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'feat: something' });
|
||||
|
||||
await generateCommitMessage(baseConfig());
|
||||
|
||||
expect(mockGenerateText).toHaveBeenCalledOnce();
|
||||
const callArgs = mockGenerateText.mock.calls[0][0];
|
||||
expect(callArgs.model).toBe(fakeModel);
|
||||
expect(callArgs.system).toBe('You are a Git expert.');
|
||||
});
|
||||
|
||||
it('includes diffSummary in the prompt sent to generateText', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'fix: resolve bug' });
|
||||
|
||||
await generateCommitMessage(baseConfig({ diffSummary: 'removed null check in auth.ts' }));
|
||||
|
||||
const prompt = mockGenerateText.mock.calls[0][0].prompt as string;
|
||||
expect(prompt).toContain('removed null check in auth.ts');
|
||||
});
|
||||
|
||||
it('includes filesChanged in the prompt', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'refactor: split utilities' });
|
||||
|
||||
await generateCommitMessage(
|
||||
baseConfig({ filesChanged: ['src/auth.ts', 'src/utils.ts', 'src/index.ts'] }),
|
||||
);
|
||||
|
||||
const prompt = mockGenerateText.mock.calls[0][0].prompt as string;
|
||||
expect(prompt).toContain('src/auth.ts');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Default model / thinking level
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('uses haiku model and low thinking level by default', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'chore: update deps' });
|
||||
|
||||
await generateCommitMessage(baseConfig());
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('haiku');
|
||||
expect(clientArgs.thinkingLevel).toBe('low');
|
||||
});
|
||||
|
||||
it('accepts custom modelShorthand and thinkingLevel', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'feat: new endpoint' });
|
||||
|
||||
await generateCommitMessage(baseConfig({ modelShorthand: 'sonnet', thinkingLevel: 'medium' }));
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('sonnet');
|
||||
expect(clientArgs.thinkingLevel).toBe('medium');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GitHub issue handling
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('includes Fixes reference when githubIssue is provided', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'fix: null pointer\n\nFixes #99' });
|
||||
|
||||
const result = await generateCommitMessage(baseConfig({ githubIssue: 99 }));
|
||||
|
||||
expect(result).toContain('Fixes #99');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Spec file context
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('reads spec.md for title when spec directory exists', async () => {
|
||||
// Spec directory at .auto-claude/specs/001-add-feature
|
||||
mockExistsSync.mockImplementation((p: string) => {
|
||||
const normalized = p.replace(/\\/g, '/');
|
||||
if (normalized.includes('specs/001-add-feature')) return true;
|
||||
return false;
|
||||
});
|
||||
mockReadFileSync.mockImplementation((p: string) => {
|
||||
if (p.includes('spec.md')) return '# Add OAuth Feature\n\n## Overview\nFull OAuth2 support.';
|
||||
return '{}';
|
||||
});
|
||||
mockGenerateText.mockResolvedValue({ text: 'feat(auth): add OAuth2' });
|
||||
|
||||
const result = await generateCommitMessage(baseConfig());
|
||||
|
||||
// Result should come from LLM (title from spec was available for context)
|
||||
expect(result).toBe('feat(auth): add OAuth2');
|
||||
const prompt = mockGenerateText.mock.calls[0][0].prompt as string;
|
||||
expect(prompt).toContain('Add OAuth Feature');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fallback message
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns fallback message when generateText throws', async () => {
|
||||
mockGenerateText.mockRejectedValue(new Error('Network error'));
|
||||
|
||||
const result = await generateCommitMessage(baseConfig({ specName: '001-add-feature' }));
|
||||
|
||||
// Fallback format: "<type>: <title or specName>"
|
||||
expect(result).toMatch(/^(feat|fix|refactor|docs|test|perf|chore|style|ci|build):/);
|
||||
expect(typeof result).toBe('string');
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('includes Fixes in fallback when githubIssue provided and LLM fails', async () => {
|
||||
mockGenerateText.mockRejectedValue(new Error('Timeout'));
|
||||
|
||||
const result = await generateCommitMessage(baseConfig({ githubIssue: 77 }));
|
||||
|
||||
expect(result).toContain('Fixes #77');
|
||||
});
|
||||
|
||||
it('returns fallback when LLM returns empty text', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: ' ' });
|
||||
|
||||
const result = await generateCommitMessage(baseConfig());
|
||||
|
||||
// Should fall through to fallback
|
||||
expect(typeof result).toBe('string');
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Large filesChanged list
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('truncates filesChanged list when more than 20 files', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'refactor: big cleanup' });
|
||||
|
||||
const manyFiles = Array.from({ length: 30 }, (_, i) => `src/file${i}.ts`);
|
||||
await generateCommitMessage(baseConfig({ filesChanged: manyFiles }));
|
||||
|
||||
const prompt = mockGenerateText.mock.calls[0][0].prompt as string;
|
||||
expect(prompt).toContain('and 10 more files');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,306 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// =============================================================================
|
||||
// Mocks — must be declared before any imports that use them
|
||||
// =============================================================================
|
||||
|
||||
const mockStreamText = vi.fn();
|
||||
|
||||
vi.mock('ai', () => ({
|
||||
streamText: (...args: unknown[]) => mockStreamText(...args),
|
||||
stepCountIs: (n: number) => ({ type: 'stepCount', count: n }),
|
||||
}));
|
||||
|
||||
const mockCreateSimpleClient = vi.fn();
|
||||
|
||||
vi.mock('../../client/factory', () => ({
|
||||
createSimpleClient: (...args: unknown[]) => mockCreateSimpleClient(...args),
|
||||
}));
|
||||
|
||||
// Mock filesystem: prompt files exist by default
|
||||
const mockExistsSync = vi.fn();
|
||||
const mockReadFileSync = vi.fn();
|
||||
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: (...args: unknown[]) => mockExistsSync(...args),
|
||||
readFileSync: (...args: unknown[]) => mockReadFileSync(...args),
|
||||
}));
|
||||
|
||||
// Mock the tool registry so we don't need real tool initialization
|
||||
vi.mock('../../tools/build-registry', () => ({
|
||||
buildToolRegistry: () => ({
|
||||
getToolsForAgent: vi.fn().mockReturnValue({}),
|
||||
}),
|
||||
}));
|
||||
|
||||
// =============================================================================
|
||||
// Import after mocking
|
||||
// =============================================================================
|
||||
|
||||
import { runIdeation, IDEATION_TYPES, IDEATION_TYPE_LABELS } from '../ideation';
|
||||
import type { IdeationConfig, IdeationStreamEvent } from '../ideation';
|
||||
|
||||
// =============================================================================
|
||||
// Helpers
|
||||
// =============================================================================
|
||||
|
||||
const fakeModel = { modelId: 'claude-sonnet-test' };
|
||||
|
||||
function makeMockClient() {
|
||||
return {
|
||||
model: fakeModel,
|
||||
systemPrompt: '',
|
||||
tools: {},
|
||||
maxSteps: 30,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an async generator that yields stream parts and then ends.
|
||||
*/
|
||||
function makeStream(parts: Array<Record<string, unknown>>) {
|
||||
return {
|
||||
fullStream: (async function* () {
|
||||
for (const part of parts) {
|
||||
yield part;
|
||||
}
|
||||
})(),
|
||||
};
|
||||
}
|
||||
|
||||
function baseConfig(overrides: Partial<IdeationConfig> = {}): IdeationConfig {
|
||||
return {
|
||||
projectDir: '/project',
|
||||
outputDir: '/project/.auto-claude/ideation',
|
||||
promptsDir: '/app/prompts',
|
||||
ideationType: 'code_improvements',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Tests
|
||||
// =============================================================================
|
||||
|
||||
describe('runIdeation', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockCreateSimpleClient.mockResolvedValue(makeMockClient());
|
||||
// Prompt file exists and has content by default
|
||||
mockExistsSync.mockReturnValue(true);
|
||||
mockReadFileSync.mockReturnValue('Analyze the codebase for improvements.');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('exports all expected IDEATION_TYPES', () => {
|
||||
expect(IDEATION_TYPES).toContain('code_improvements');
|
||||
expect(IDEATION_TYPES).toContain('ui_ux_improvements');
|
||||
expect(IDEATION_TYPES).toContain('documentation_gaps');
|
||||
expect(IDEATION_TYPES).toContain('security_hardening');
|
||||
expect(IDEATION_TYPES).toContain('performance_optimizations');
|
||||
expect(IDEATION_TYPES).toContain('code_quality');
|
||||
expect(IDEATION_TYPES).toHaveLength(6);
|
||||
});
|
||||
|
||||
it('exports human-readable labels for all ideation types', () => {
|
||||
for (const type of IDEATION_TYPES) {
|
||||
expect(IDEATION_TYPE_LABELS[type]).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Successful run
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns success with accumulated text from stream', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([
|
||||
{ type: 'text-delta', text: 'Found ' },
|
||||
{ type: 'text-delta', text: '3 improvements.' },
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await runIdeation(baseConfig());
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.text).toBe('Found 3 improvements.');
|
||||
expect(result.error).toBeUndefined();
|
||||
});
|
||||
|
||||
it('calls createSimpleClient with sonnet and medium thinking by default', async () => {
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runIdeation(baseConfig());
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('sonnet');
|
||||
expect(clientArgs.thinkingLevel).toBe('medium');
|
||||
});
|
||||
|
||||
it('accepts custom modelShorthand and thinkingLevel', async () => {
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runIdeation(baseConfig({ modelShorthand: 'haiku', thinkingLevel: 'low' }));
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('haiku');
|
||||
expect(clientArgs.thinkingLevel).toBe('low');
|
||||
});
|
||||
|
||||
it('passes tools from client to streamText', async () => {
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runIdeation(baseConfig());
|
||||
|
||||
const streamArgs = mockStreamText.mock.calls[0][0];
|
||||
expect(streamArgs).toHaveProperty('tools');
|
||||
expect(streamArgs).toHaveProperty('model');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stream callbacks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('forwards text-delta events to onStream callback', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([
|
||||
{ type: 'text-delta', text: 'hello' },
|
||||
{ type: 'text-delta', text: ' world' },
|
||||
]),
|
||||
);
|
||||
|
||||
const events: IdeationStreamEvent[] = [];
|
||||
await runIdeation(baseConfig(), (e) => events.push(e));
|
||||
|
||||
const textEvents = events.filter((e) => e.type === 'text-delta');
|
||||
expect(textEvents).toHaveLength(2);
|
||||
expect((textEvents[0] as { type: 'text-delta'; text: string }).text).toBe('hello');
|
||||
});
|
||||
|
||||
it('forwards tool-use events from tool-call stream parts', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([{ type: 'tool-call', toolName: 'Glob', toolCallId: 'c1', input: {} }]),
|
||||
);
|
||||
|
||||
const events: IdeationStreamEvent[] = [];
|
||||
await runIdeation(baseConfig(), (e) => events.push(e));
|
||||
|
||||
const toolEvents = events.filter((e) => e.type === 'tool-use');
|
||||
expect(toolEvents).toHaveLength(1);
|
||||
expect((toolEvents[0] as { type: 'tool-use'; name: string }).name).toBe('Glob');
|
||||
});
|
||||
|
||||
it('forwards error events from stream error parts', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([{ type: 'error', error: new Error('stream error') }]),
|
||||
);
|
||||
|
||||
const events: IdeationStreamEvent[] = [];
|
||||
await runIdeation(baseConfig(), (e) => events.push(e));
|
||||
|
||||
const errorEvents = events.filter((e) => e.type === 'error');
|
||||
expect(errorEvents).toHaveLength(1);
|
||||
expect((errorEvents[0] as { type: 'error'; error: string }).error).toBe('stream error');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Prompt file not found
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns failure when prompt file does not exist', async () => {
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
|
||||
const result = await runIdeation(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.text).toBe('');
|
||||
expect(result.error).toContain('Prompt not found');
|
||||
});
|
||||
|
||||
it('returns failure when prompt file cannot be read', async () => {
|
||||
mockExistsSync.mockReturnValue(true);
|
||||
mockReadFileSync.mockImplementation(() => {
|
||||
throw new Error('Permission denied');
|
||||
});
|
||||
|
||||
const result = await runIdeation(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('Permission denied');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Error handling — streamText throws
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns failure when streamText iteration throws', async () => {
|
||||
mockStreamText.mockReturnValue({
|
||||
// biome-ignore lint/correctness/useYield: intentionally throwing before yield to test error path
|
||||
fullStream: (async function* () {
|
||||
throw new Error('API error');
|
||||
})(),
|
||||
});
|
||||
|
||||
const result = await runIdeation(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('API error');
|
||||
});
|
||||
|
||||
it('emits error event to callback when streamText throws', async () => {
|
||||
mockStreamText.mockReturnValue({
|
||||
// biome-ignore lint/correctness/useYield: intentionally throwing before yield to test error path
|
||||
fullStream: (async function* () {
|
||||
throw new Error('network failure');
|
||||
})(),
|
||||
});
|
||||
|
||||
const events: IdeationStreamEvent[] = [];
|
||||
await runIdeation(baseConfig(), (e) => events.push(e));
|
||||
|
||||
expect(events.some((e) => e.type === 'error')).toBe(true);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ideation type routing — checks the correct prompt file is loaded
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it.each(IDEATION_TYPES)('loads the correct prompt file for ideation type: %s', async (type) => {
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runIdeation(baseConfig({ ideationType: type }));
|
||||
|
||||
// The prompt file for each type should have been checked for existence
|
||||
expect(mockExistsSync).toHaveBeenCalledWith(expect.stringContaining('.md'));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Context injection
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('includes projectDir and outputDir in the prompt passed to streamText', async () => {
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runIdeation(
|
||||
baseConfig({ projectDir: '/my/project', outputDir: '/my/project/.auto-claude/ideation' }),
|
||||
);
|
||||
|
||||
// The system prompt passed to streamText should contain the project dir
|
||||
const streamArgs = mockStreamText.mock.calls[0][0];
|
||||
const systemPrompt = streamArgs.system as string;
|
||||
expect(systemPrompt).toContain('/my/project');
|
||||
});
|
||||
|
||||
it('injects maxIdeasPerType into the context', async () => {
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runIdeation(baseConfig({ maxIdeasPerType: 10 }));
|
||||
|
||||
const streamArgs = mockStreamText.mock.calls[0][0];
|
||||
const systemPrompt = streamArgs.system as string;
|
||||
expect(systemPrompt).toContain('10');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,300 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// =============================================================================
|
||||
// Mocks — must be declared before any imports that use them
|
||||
// =============================================================================
|
||||
|
||||
const mockGenerateText = vi.fn();
|
||||
|
||||
vi.mock('ai', () => ({
|
||||
generateText: (...args: unknown[]) => mockGenerateText(...args),
|
||||
Output: {
|
||||
object: ({ schema }: { schema: unknown }) => ({ type: 'object', schema }),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockCreateSimpleClient = vi.fn();
|
||||
|
||||
vi.mock('../../client/factory', () => ({
|
||||
createSimpleClient: (...args: unknown[]) => mockCreateSimpleClient(...args),
|
||||
}));
|
||||
|
||||
// Mock schema/structured-output so we don't need the actual implementation
|
||||
vi.mock('../../schema/structured-output', () => ({
|
||||
parseLLMJson: vi.fn().mockReturnValue(null),
|
||||
}));
|
||||
|
||||
// Mock the Zod schemas used by the runner
|
||||
vi.mock('../../schema/insight-extractor', () => ({
|
||||
ExtractedInsightsSchema: {},
|
||||
}));
|
||||
|
||||
vi.mock('../../schema/output', () => ({
|
||||
ExtractedInsightsOutputSchema: {},
|
||||
}));
|
||||
|
||||
// =============================================================================
|
||||
// Import after mocking
|
||||
// =============================================================================
|
||||
|
||||
import { extractSessionInsights } from '../insight-extractor';
|
||||
import type { InsightExtractionConfig } from '../insight-extractor';
|
||||
import { parseLLMJson } from '../../schema/structured-output';
|
||||
|
||||
// =============================================================================
|
||||
// Helpers
|
||||
// =============================================================================
|
||||
|
||||
const fakeModel = { modelId: 'claude-haiku-test' };
|
||||
|
||||
function makeMockClient() {
|
||||
return { model: fakeModel, systemPrompt: 'You are an expert code analyst.' };
|
||||
}
|
||||
|
||||
function makeValidOutput() {
|
||||
return {
|
||||
file_insights: [{ file: 'src/app.ts', insight: 'Uses singleton pattern', category: 'pattern' }],
|
||||
patterns_discovered: ['Singleton pattern used'],
|
||||
gotchas_discovered: ['Must call init() before use'],
|
||||
approach_outcome: {
|
||||
success: true,
|
||||
approach_used: 'Direct refactor',
|
||||
why_it_worked: 'Simplified the module',
|
||||
why_it_failed: null,
|
||||
alternatives_tried: [],
|
||||
},
|
||||
recommendations: ['Add unit tests for singleton'],
|
||||
};
|
||||
}
|
||||
|
||||
function baseConfig(overrides: Partial<InsightExtractionConfig> = {}): InsightExtractionConfig {
|
||||
return {
|
||||
subtaskId: 'sub-001',
|
||||
subtaskDescription: 'Refactor authentication module',
|
||||
sessionNum: 1,
|
||||
success: true,
|
||||
diff: 'diff --git a/src/auth.ts b/src/auth.ts\n+ return token;',
|
||||
changedFiles: ['src/auth.ts'],
|
||||
commitMessages: 'refactor: simplify auth module',
|
||||
attemptHistory: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Tests
|
||||
// =============================================================================
|
||||
|
||||
describe('extractSessionInsights', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockCreateSimpleClient.mockResolvedValue(makeMockClient());
|
||||
// By default, result.output contains the structured data (constrained decoding path)
|
||||
mockGenerateText.mockResolvedValue({
|
||||
output: makeValidOutput(),
|
||||
text: '',
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Successful extraction via result.output (constrained decoding)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns extracted insights from result.output when available', async () => {
|
||||
const result = await extractSessionInsights(baseConfig());
|
||||
|
||||
expect(result.subtask_id).toBe('sub-001');
|
||||
expect(result.session_num).toBe(1);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.changed_files).toEqual(['src/auth.ts']);
|
||||
expect(result.file_insights).toHaveLength(1);
|
||||
expect(result.file_insights[0].file).toBe('src/app.ts');
|
||||
expect(result.patterns_discovered).toContain('Singleton pattern used');
|
||||
expect(result.gotchas_discovered).toContain('Must call init() before use');
|
||||
expect(result.recommendations).toContain('Add unit tests for singleton');
|
||||
});
|
||||
|
||||
it('populates approach_outcome from result.output', async () => {
|
||||
const result = await extractSessionInsights(baseConfig());
|
||||
|
||||
expect(result.approach_outcome.success).toBe(true);
|
||||
expect(result.approach_outcome.approach_used).toBe('Direct refactor');
|
||||
expect(result.approach_outcome.why_it_worked).toBe('Simplified the module');
|
||||
expect(result.approach_outcome.why_it_failed).toBeNull();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fallback to parseLLMJson when result.output is absent
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('falls back to parseLLMJson when result.output is null/undefined', async () => {
|
||||
mockGenerateText.mockResolvedValue({
|
||||
output: null,
|
||||
text: JSON.stringify({
|
||||
file_insights: [{ file: 'src/login.ts', insight: 'Heavy coupling' }],
|
||||
patterns_discovered: ['MVC'],
|
||||
gotchas_discovered: [],
|
||||
approach_outcome: {
|
||||
success: false,
|
||||
approach_used: 'monkey-patch',
|
||||
why_it_worked: null,
|
||||
why_it_failed: 'Too hacky',
|
||||
alternatives_tried: [],
|
||||
},
|
||||
recommendations: [],
|
||||
}),
|
||||
});
|
||||
|
||||
const parsedData = {
|
||||
file_insights: [{ file: 'src/login.ts', insight: 'Heavy coupling' }],
|
||||
patterns_discovered: ['MVC'],
|
||||
gotchas_discovered: [],
|
||||
approach_outcome: {
|
||||
success: false,
|
||||
approach_used: 'monkey-patch',
|
||||
why_it_worked: null,
|
||||
why_it_failed: 'Too hacky',
|
||||
alternatives_tried: [],
|
||||
},
|
||||
recommendations: [],
|
||||
};
|
||||
|
||||
vi.mocked(parseLLMJson).mockReturnValueOnce(parsedData as unknown as ReturnType<typeof parseLLMJson>);
|
||||
|
||||
const result = await extractSessionInsights(baseConfig({ success: false }));
|
||||
|
||||
expect(result.file_insights[0].file).toBe('src/login.ts');
|
||||
expect(result.patterns_discovered).toContain('MVC');
|
||||
expect(result.approach_outcome.why_it_failed).toBe('Too hacky');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Generic fallback when both paths fail
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns generic insights when result.output is null and parseLLMJson returns null', async () => {
|
||||
mockGenerateText.mockResolvedValue({ output: null, text: 'not valid json' });
|
||||
vi.mocked(parseLLMJson).mockReturnValueOnce(null);
|
||||
|
||||
const result = await extractSessionInsights(baseConfig({ subtaskId: 'sub-fallback', success: false }));
|
||||
|
||||
expect(result.subtask_id).toBe('sub-fallback');
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.file_insights).toEqual([]);
|
||||
expect(result.patterns_discovered).toEqual([]);
|
||||
expect(result.gotchas_discovered).toEqual([]);
|
||||
expect(result.recommendations).toEqual([]);
|
||||
expect(result.approach_outcome.approach_used).toContain('sub-fallback');
|
||||
});
|
||||
|
||||
it('returns generic insights when generateText throws', async () => {
|
||||
mockGenerateText.mockRejectedValue(new Error('API unavailable'));
|
||||
|
||||
const result = await extractSessionInsights(baseConfig({ subtaskId: 'sub-error', success: true }));
|
||||
|
||||
expect(result.subtask_id).toBe('sub-error');
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.file_insights).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns generic insights when createSimpleClient throws', async () => {
|
||||
mockCreateSimpleClient.mockRejectedValue(new Error('No credentials'));
|
||||
|
||||
const result = await extractSessionInsights(baseConfig());
|
||||
|
||||
expect(result.subtask_id).toBe('sub-001');
|
||||
expect(result.file_insights).toEqual([]);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Never throws
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('never throws — always returns a valid InsightResult', async () => {
|
||||
mockGenerateText.mockRejectedValue(new Error('catastrophic failure'));
|
||||
|
||||
await expect(extractSessionInsights(baseConfig())).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Client configuration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('uses haiku model and low thinking level by default', async () => {
|
||||
await extractSessionInsights(baseConfig());
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('haiku');
|
||||
expect(clientArgs.thinkingLevel).toBe('low');
|
||||
});
|
||||
|
||||
it('accepts custom modelShorthand and thinkingLevel', async () => {
|
||||
await extractSessionInsights(
|
||||
baseConfig({ modelShorthand: 'sonnet', thinkingLevel: 'medium' }),
|
||||
);
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('sonnet');
|
||||
expect(clientArgs.thinkingLevel).toBe('medium');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Prompt content validation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('includes subtaskId and description in the prompt', async () => {
|
||||
await extractSessionInsights(
|
||||
baseConfig({
|
||||
subtaskId: 'my-task-42',
|
||||
subtaskDescription: 'Fix login regression',
|
||||
}),
|
||||
);
|
||||
|
||||
const callArgs = mockGenerateText.mock.calls[0][0];
|
||||
expect(callArgs.prompt).toContain('my-task-42');
|
||||
expect(callArgs.prompt).toContain('Fix login regression');
|
||||
});
|
||||
|
||||
it('truncates diff when it exceeds 15000 chars', async () => {
|
||||
const longDiff = '+' + 'a'.repeat(20_000);
|
||||
|
||||
await extractSessionInsights(baseConfig({ diff: longDiff }));
|
||||
|
||||
const callArgs = mockGenerateText.mock.calls[0][0];
|
||||
const prompt = callArgs.prompt as string;
|
||||
// The prompt must mention truncation and not contain all 20k chars of diff
|
||||
expect(prompt).toContain('truncated');
|
||||
});
|
||||
|
||||
it('includes changed files in the prompt', async () => {
|
||||
await extractSessionInsights(
|
||||
baseConfig({ changedFiles: ['src/login.ts', 'src/session.ts'] }),
|
||||
);
|
||||
|
||||
const callArgs = mockGenerateText.mock.calls[0][0];
|
||||
expect(callArgs.prompt).toContain('src/login.ts');
|
||||
});
|
||||
|
||||
it('includes attempt history in the prompt when provided', async () => {
|
||||
await extractSessionInsights(
|
||||
baseConfig({
|
||||
attemptHistory: [
|
||||
{ success: false, approach: 'patch method', error: 'type mismatch' },
|
||||
{ success: true, approach: 'full rewrite' },
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const callArgs = mockGenerateText.mock.calls[0][0];
|
||||
expect(callArgs.prompt).toContain('patch method');
|
||||
expect(callArgs.prompt).toContain('full rewrite');
|
||||
});
|
||||
|
||||
it('passes output schema configuration to generateText', async () => {
|
||||
await extractSessionInsights(baseConfig());
|
||||
|
||||
const callArgs = mockGenerateText.mock.calls[0][0];
|
||||
// The output key should be set (from Output.object())
|
||||
expect(callArgs).toHaveProperty('output');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,382 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// =============================================================================
|
||||
// Mocks — must be declared before any imports that use them
|
||||
// =============================================================================
|
||||
|
||||
const mockStreamText = vi.fn();
|
||||
|
||||
vi.mock('ai', () => ({
|
||||
streamText: (...args: unknown[]) => mockStreamText(...args),
|
||||
stepCountIs: (n: number) => ({ type: 'stepCount', count: n }),
|
||||
}));
|
||||
|
||||
const mockCreateSimpleClient = vi.fn();
|
||||
|
||||
vi.mock('../../client/factory', () => ({
|
||||
createSimpleClient: (...args: unknown[]) => mockCreateSimpleClient(...args),
|
||||
}));
|
||||
|
||||
// Filesystem mocks — project context files are absent by default
|
||||
const mockExistsSync = vi.fn().mockReturnValue(false);
|
||||
const mockReadFileSync = vi.fn();
|
||||
const mockReaddirSync = vi.fn().mockReturnValue([]);
|
||||
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: (...args: unknown[]) => mockExistsSync(...args),
|
||||
readFileSync: (...args: unknown[]) => mockReadFileSync(...args),
|
||||
readdirSync: (...args: unknown[]) => mockReaddirSync(...args),
|
||||
}));
|
||||
|
||||
// Mock tool registry
|
||||
vi.mock('../../tools/build-registry', () => ({
|
||||
buildToolRegistry: () => ({
|
||||
getToolsForAgent: vi.fn().mockReturnValue({}),
|
||||
}),
|
||||
}));
|
||||
|
||||
// json-repair is used for safeParseJson in the insights runner
|
||||
vi.mock('../../../utils/json-repair', () => ({
|
||||
safeParseJson: (text: string) => {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
// parseLLMJson is used for task suggestion extraction
|
||||
vi.mock('../../schema/structured-output', () => ({
|
||||
parseLLMJson: vi.fn().mockReturnValue(null),
|
||||
}));
|
||||
|
||||
vi.mock('../../schema/insight-extractor', () => ({
|
||||
TaskSuggestionSchema: {},
|
||||
}));
|
||||
|
||||
// =============================================================================
|
||||
// Import after mocking
|
||||
// =============================================================================
|
||||
|
||||
import { runInsightsQuery } from '../insights';
|
||||
import type { InsightsConfig, InsightsStreamEvent } from '../insights';
|
||||
import { parseLLMJson } from '../../schema/structured-output';
|
||||
|
||||
// =============================================================================
|
||||
// Helpers
|
||||
// =============================================================================
|
||||
|
||||
const fakeModel = { modelId: 'claude-sonnet-test' };
|
||||
|
||||
function makeMockClient(systemPrompt = 'You are an AI assistant.') {
|
||||
return {
|
||||
model: fakeModel,
|
||||
systemPrompt,
|
||||
tools: {},
|
||||
maxSteps: 30,
|
||||
};
|
||||
}
|
||||
|
||||
function makeStream(parts: Array<Record<string, unknown>>) {
|
||||
return {
|
||||
fullStream: (async function* () {
|
||||
for (const part of parts) {
|
||||
yield part;
|
||||
}
|
||||
})(),
|
||||
};
|
||||
}
|
||||
|
||||
function baseConfig(overrides: Partial<InsightsConfig> = {}): InsightsConfig {
|
||||
return {
|
||||
projectDir: '/project',
|
||||
message: 'How does authentication work?',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Tests
|
||||
// =============================================================================
|
||||
|
||||
describe('runInsightsQuery', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockCreateSimpleClient.mockResolvedValue(makeMockClient());
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
mockReaddirSync.mockReturnValue([]);
|
||||
vi.mocked(parseLLMJson).mockReturnValue(null);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Successful run — no streaming events needed from caller
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns response text accumulated from stream', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([
|
||||
{ type: 'text-delta', text: 'Authentication uses JWT tokens.' },
|
||||
{ type: 'text-delta', text: ' Tokens expire after 1 hour.' },
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await runInsightsQuery(baseConfig());
|
||||
|
||||
expect(result.text).toBe('Authentication uses JWT tokens. Tokens expire after 1 hour.');
|
||||
expect(result.taskSuggestion).toBeNull();
|
||||
expect(result.toolCalls).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns empty text and no task suggestion when stream is empty', async () => {
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
const result = await runInsightsQuery(baseConfig());
|
||||
|
||||
expect(result.text).toBe('');
|
||||
expect(result.taskSuggestion).toBeNull();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Task suggestion extraction
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('extracts task suggestion from response text when marker present', async () => {
|
||||
const suggestion = {
|
||||
title: 'Add rate limiting',
|
||||
description: 'Implement per-user rate limiting on auth endpoints',
|
||||
metadata: { category: 'security', complexity: 'medium', impact: 'high' },
|
||||
};
|
||||
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([
|
||||
{
|
||||
type: 'text-delta',
|
||||
text: `Here is my suggestion.\n__TASK_SUGGESTION__:${JSON.stringify(suggestion)}\n`,
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
vi.mocked(parseLLMJson).mockReturnValueOnce(suggestion as unknown as ReturnType<typeof parseLLMJson>);
|
||||
|
||||
const result = await runInsightsQuery(baseConfig());
|
||||
|
||||
expect(result.taskSuggestion).not.toBeNull();
|
||||
expect(result.taskSuggestion?.title).toBe('Add rate limiting');
|
||||
expect(result.taskSuggestion?.metadata.category).toBe('security');
|
||||
});
|
||||
|
||||
it('returns null taskSuggestion when no marker in response', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([{ type: 'text-delta', text: 'No suggestions here.' }]),
|
||||
);
|
||||
|
||||
const result = await runInsightsQuery(baseConfig());
|
||||
|
||||
expect(result.taskSuggestion).toBeNull();
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tool call tracking
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('tracks tool calls in result.toolCalls', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([
|
||||
{ type: 'tool-call', toolName: 'Read', toolCallId: 'c1', input: { file_path: 'src/auth.ts' } },
|
||||
{ type: 'tool-result', toolCallId: 'c1', toolName: 'Read', output: 'file content' },
|
||||
{ type: 'tool-call', toolName: 'Glob', toolCallId: 'c2', input: { pattern: '**/*.ts' } },
|
||||
{ type: 'tool-result', toolCallId: 'c2', toolName: 'Glob', output: 'src/auth.ts' },
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await runInsightsQuery(baseConfig());
|
||||
|
||||
expect(result.toolCalls).toHaveLength(2);
|
||||
expect(result.toolCalls[0].name).toBe('Read');
|
||||
expect(result.toolCalls[1].name).toBe('Glob');
|
||||
});
|
||||
|
||||
it('extracts file_path from Read tool call input', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([
|
||||
{
|
||||
type: 'tool-call',
|
||||
toolName: 'Read',
|
||||
toolCallId: 'c1',
|
||||
input: { file_path: 'src/auth.ts' },
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await runInsightsQuery(baseConfig());
|
||||
|
||||
expect(result.toolCalls[0].input).toBe('src/auth.ts');
|
||||
});
|
||||
|
||||
it('extracts pattern from Grep/Glob tool call input', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([
|
||||
{
|
||||
type: 'tool-call',
|
||||
toolName: 'Grep',
|
||||
toolCallId: 'c1',
|
||||
input: { pattern: 'useAuth' },
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await runInsightsQuery(baseConfig());
|
||||
|
||||
expect(result.toolCalls[0].input).toBe('pattern: useAuth');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stream callbacks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('forwards text-delta events to onStream callback', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([
|
||||
{ type: 'text-delta', text: 'chunk1' },
|
||||
{ type: 'text-delta', text: 'chunk2' },
|
||||
]),
|
||||
);
|
||||
|
||||
const events: InsightsStreamEvent[] = [];
|
||||
await runInsightsQuery(baseConfig(), (e) => events.push(e));
|
||||
|
||||
const textEvents = events.filter((e) => e.type === 'text-delta');
|
||||
expect(textEvents).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('forwards tool-start events for tool-call stream parts', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([
|
||||
{ type: 'tool-call', toolName: 'Grep', toolCallId: 'c1', input: { pattern: 'login' } },
|
||||
]),
|
||||
);
|
||||
|
||||
const events: InsightsStreamEvent[] = [];
|
||||
await runInsightsQuery(baseConfig(), (e) => events.push(e));
|
||||
|
||||
const toolStartEvents = events.filter((e) => e.type === 'tool-start');
|
||||
expect(toolStartEvents).toHaveLength(1);
|
||||
expect((toolStartEvents[0] as { type: 'tool-start'; name: string }).name).toBe('Grep');
|
||||
});
|
||||
|
||||
it('forwards tool-end events for tool-result stream parts', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([
|
||||
{ type: 'tool-result', toolCallId: 'c1', toolName: 'Read', output: 'content' },
|
||||
]),
|
||||
);
|
||||
|
||||
const events: InsightsStreamEvent[] = [];
|
||||
await runInsightsQuery(baseConfig(), (e) => events.push(e));
|
||||
|
||||
const toolEndEvents = events.filter((e) => e.type === 'tool-end');
|
||||
expect(toolEndEvents).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('forwards error events for error stream parts', async () => {
|
||||
mockStreamText.mockReturnValue(
|
||||
makeStream([{ type: 'error', error: new Error('tool failed') }]),
|
||||
);
|
||||
|
||||
const events: InsightsStreamEvent[] = [];
|
||||
await runInsightsQuery(baseConfig(), (e) => events.push(e));
|
||||
|
||||
const errorEvents = events.filter((e) => e.type === 'error');
|
||||
expect(errorEvents).toHaveLength(1);
|
||||
expect((errorEvents[0] as { type: 'error'; error: string }).error).toBe('tool failed');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Error propagation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('rethrows when streamText iteration throws', async () => {
|
||||
mockStreamText.mockReturnValue({
|
||||
// biome-ignore lint/correctness/useYield: intentionally throwing before yield to test error path
|
||||
fullStream: (async function* () {
|
||||
throw new Error('API timeout');
|
||||
})(),
|
||||
});
|
||||
|
||||
await expect(runInsightsQuery(baseConfig())).rejects.toThrow('API timeout');
|
||||
});
|
||||
|
||||
it('emits error event to callback before rethrowing', async () => {
|
||||
mockStreamText.mockReturnValue({
|
||||
// biome-ignore lint/correctness/useYield: intentionally throwing before yield to test error path
|
||||
fullStream: (async function* () {
|
||||
throw new Error('rate limited');
|
||||
})(),
|
||||
});
|
||||
|
||||
const events: InsightsStreamEvent[] = [];
|
||||
await expect(runInsightsQuery(baseConfig(), (e) => events.push(e))).rejects.toThrow(
|
||||
'rate limited',
|
||||
);
|
||||
|
||||
expect(events.some((e) => e.type === 'error')).toBe(true);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Client configuration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('uses sonnet model and medium thinking level by default', async () => {
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runInsightsQuery(baseConfig());
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('sonnet');
|
||||
expect(clientArgs.thinkingLevel).toBe('medium');
|
||||
});
|
||||
|
||||
it('accepts custom modelShorthand and thinkingLevel', async () => {
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runInsightsQuery(baseConfig({ modelShorthand: 'haiku', thinkingLevel: 'low' }));
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('haiku');
|
||||
expect(clientArgs.thinkingLevel).toBe('low');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// History handling
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('includes conversation history in the prompt when provided', async () => {
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runInsightsQuery(
|
||||
baseConfig({
|
||||
message: 'What about refresh tokens?',
|
||||
history: [
|
||||
{ role: 'user', content: 'How does auth work?' },
|
||||
{ role: 'assistant', content: 'It uses JWT.' },
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const callArgs = mockStreamText.mock.calls[0][0];
|
||||
const prompt = callArgs.prompt as string;
|
||||
expect(prompt).toContain('How does auth work?');
|
||||
expect(prompt).toContain('It uses JWT.');
|
||||
expect(prompt).toContain('What about refresh tokens?');
|
||||
});
|
||||
|
||||
it('uses message directly as prompt when history is empty', async () => {
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runInsightsQuery(baseConfig({ message: 'What is the entry point?' }));
|
||||
|
||||
const callArgs = mockStreamText.mock.calls[0][0];
|
||||
expect(callArgs.prompt).toBe('What is the entry point?');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// =============================================================================
|
||||
// Mocks — must be declared before any imports that use them
|
||||
// =============================================================================
|
||||
|
||||
const mockGenerateText = vi.fn();
|
||||
|
||||
vi.mock('ai', () => ({
|
||||
generateText: (...args: unknown[]) => mockGenerateText(...args),
|
||||
}));
|
||||
|
||||
const mockCreateSimpleClient = vi.fn();
|
||||
|
||||
vi.mock('../../client/factory', () => ({
|
||||
createSimpleClient: (...args: unknown[]) => mockCreateSimpleClient(...args),
|
||||
}));
|
||||
|
||||
// =============================================================================
|
||||
// Import after mocking
|
||||
// =============================================================================
|
||||
|
||||
import { resolveMergeConflict, createMergeResolverFn } from '../merge-resolver';
|
||||
import type { MergeResolverConfig } from '../merge-resolver';
|
||||
|
||||
// =============================================================================
|
||||
// Helpers
|
||||
// =============================================================================
|
||||
|
||||
const fakeModel = { modelId: 'claude-haiku-test' };
|
||||
|
||||
function makeMockClient(systemPrompt = 'Resolve merge conflicts.') {
|
||||
return { model: fakeModel, systemPrompt };
|
||||
}
|
||||
|
||||
function baseConfig(overrides: Partial<MergeResolverConfig> = {}): MergeResolverConfig {
|
||||
return {
|
||||
systemPrompt: 'You are a merge conflict resolver.',
|
||||
userPrompt: '<<<\nHEAD version\n===\nIncoming version\n>>>',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Tests
|
||||
// =============================================================================
|
||||
|
||||
describe('resolveMergeConflict', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockCreateSimpleClient.mockResolvedValue(makeMockClient());
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Successful resolution
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns success with trimmed resolved text', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: ' Resolved: use incoming version. ' });
|
||||
|
||||
const result = await resolveMergeConflict(baseConfig());
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.text).toBe('Resolved: use incoming version.');
|
||||
expect(result.error).toBeUndefined();
|
||||
});
|
||||
|
||||
it('passes model and systemPrompt from client to generateText', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'merged code here' });
|
||||
|
||||
await resolveMergeConflict(baseConfig());
|
||||
|
||||
expect(mockGenerateText).toHaveBeenCalledOnce();
|
||||
const callArgs = mockGenerateText.mock.calls[0][0];
|
||||
expect(callArgs.model).toBe(fakeModel);
|
||||
expect(callArgs.system).toBe('Resolve merge conflicts.');
|
||||
});
|
||||
|
||||
it('passes userPrompt as the prompt parameter to generateText', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'resolved' });
|
||||
|
||||
const conflict = '<<<\nmy change\n===\ntheir change\n>>>';
|
||||
await resolveMergeConflict(baseConfig({ userPrompt: conflict }));
|
||||
|
||||
const callArgs = mockGenerateText.mock.calls[0][0];
|
||||
expect(callArgs.prompt).toBe(conflict);
|
||||
});
|
||||
|
||||
it('passes systemPrompt config to createSimpleClient', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'resolved' });
|
||||
|
||||
const customSystem = 'Custom system prompt.';
|
||||
await resolveMergeConflict(baseConfig({ systemPrompt: customSystem }));
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.systemPrompt).toBe(customSystem);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Default model / thinking level
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('uses haiku model and low thinking level by default', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'resolved' });
|
||||
|
||||
await resolveMergeConflict(baseConfig());
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('haiku');
|
||||
expect(clientArgs.thinkingLevel).toBe('low');
|
||||
});
|
||||
|
||||
it('accepts custom modelShorthand and thinkingLevel', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'resolved' });
|
||||
|
||||
await resolveMergeConflict(
|
||||
baseConfig({ modelShorthand: 'sonnet', thinkingLevel: 'medium' }),
|
||||
);
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('sonnet');
|
||||
expect(clientArgs.thinkingLevel).toBe('medium');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Empty response handling
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns failure when LLM returns empty text', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: ' ' });
|
||||
|
||||
const result = await resolveMergeConflict(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.text).toBe('');
|
||||
expect(result.error).toBe('Empty response from AI');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Error handling
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns failure with error message when generateText throws Error', async () => {
|
||||
mockGenerateText.mockRejectedValue(new Error('API rate limit'));
|
||||
|
||||
const result = await resolveMergeConflict(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.text).toBe('');
|
||||
expect(result.error).toBe('API rate limit');
|
||||
});
|
||||
|
||||
it('returns failure with string coercion when non-Error is thrown', async () => {
|
||||
mockGenerateText.mockRejectedValue('connection refused');
|
||||
|
||||
const result = await resolveMergeConflict(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('connection refused');
|
||||
});
|
||||
|
||||
it('returns failure when createSimpleClient throws', async () => {
|
||||
mockCreateSimpleClient.mockRejectedValue(new Error('No auth token'));
|
||||
|
||||
const result = await resolveMergeConflict(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('No auth token');
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================================================
|
||||
// createMergeResolverFn
|
||||
// =============================================================================
|
||||
|
||||
describe('createMergeResolverFn', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockCreateSimpleClient.mockResolvedValue(makeMockClient());
|
||||
});
|
||||
|
||||
it('returns an async function', () => {
|
||||
const fn = createMergeResolverFn();
|
||||
expect(typeof fn).toBe('function');
|
||||
});
|
||||
|
||||
it('returned function resolves to the resolved text on success', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'merged content' });
|
||||
|
||||
const fn = createMergeResolverFn();
|
||||
const result = await fn('system context', 'conflict block');
|
||||
|
||||
expect(result).toBe('merged content');
|
||||
});
|
||||
|
||||
it('returned function resolves to empty string when LLM returns empty', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: ' ' });
|
||||
|
||||
const fn = createMergeResolverFn();
|
||||
const result = await fn('system', 'conflict');
|
||||
|
||||
expect(result).toBe('');
|
||||
});
|
||||
|
||||
it('returned function resolves to empty string on error (does not throw)', async () => {
|
||||
mockGenerateText.mockRejectedValue(new Error('timeout'));
|
||||
|
||||
const fn = createMergeResolverFn();
|
||||
const result = await fn('system', 'conflict');
|
||||
|
||||
expect(result).toBe('');
|
||||
});
|
||||
|
||||
it('uses provided modelShorthand and thinkingLevel', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'resolved' });
|
||||
|
||||
const fn = createMergeResolverFn('sonnet', 'medium');
|
||||
await fn('sys', 'user');
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('sonnet');
|
||||
expect(clientArgs.thinkingLevel).toBe('medium');
|
||||
});
|
||||
|
||||
it('defaults to haiku and low when no arguments given', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'resolved' });
|
||||
|
||||
const fn = createMergeResolverFn();
|
||||
await fn('sys', 'user');
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('haiku');
|
||||
expect(clientArgs.thinkingLevel).toBe('low');
|
||||
});
|
||||
|
||||
it('passes system and user arguments as systemPrompt and userPrompt', async () => {
|
||||
mockGenerateText.mockResolvedValue({ text: 'resolved' });
|
||||
|
||||
const fn = createMergeResolverFn();
|
||||
await fn('the system prompt', 'the conflict text');
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.systemPrompt).toBe('the system prompt');
|
||||
const generateArgs = mockGenerateText.mock.calls[0][0];
|
||||
expect(generateArgs.prompt).toBe('the conflict text');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,420 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// =============================================================================
|
||||
// Mocks — must be declared before any imports that use them
|
||||
// =============================================================================
|
||||
|
||||
const mockStreamText = vi.fn();
|
||||
|
||||
vi.mock('ai', () => ({
|
||||
streamText: (...args: unknown[]) => mockStreamText(...args),
|
||||
stepCountIs: (n: number) => ({ type: 'stepCount', count: n }),
|
||||
}));
|
||||
|
||||
const mockCreateSimpleClient = vi.fn();
|
||||
|
||||
vi.mock('../../client/factory', () => ({
|
||||
createSimpleClient: (...args: unknown[]) => mockCreateSimpleClient(...args),
|
||||
}));
|
||||
|
||||
// Filesystem mocks
|
||||
const mockExistsSync = vi.fn();
|
||||
const mockReadFileSync = vi.fn();
|
||||
const mockWriteFileSync = vi.fn();
|
||||
const mockMkdirSync = vi.fn();
|
||||
const mockRenameSync = vi.fn();
|
||||
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: (...args: unknown[]) => mockExistsSync(...args),
|
||||
readFileSync: (...args: unknown[]) => mockReadFileSync(...args),
|
||||
writeFileSync: (...args: unknown[]) => mockWriteFileSync(...args),
|
||||
mkdirSync: (...args: unknown[]) => mockMkdirSync(...args),
|
||||
renameSync: (...args: unknown[]) => mockRenameSync(...args),
|
||||
}));
|
||||
|
||||
// Tool registry mock
|
||||
vi.mock('../../tools/build-registry', () => ({
|
||||
buildToolRegistry: () => ({
|
||||
getToolsForAgent: vi.fn().mockReturnValue({}),
|
||||
}),
|
||||
}));
|
||||
|
||||
// json-repair used for safeParseJson
|
||||
vi.mock('../../../utils/json-repair', () => ({
|
||||
safeParseJson: (text: string) => {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
// tryLoadPrompt — return null so inline prompts are used
|
||||
vi.mock('../../prompts/prompt-loader', () => ({
|
||||
tryLoadPrompt: vi.fn().mockReturnValue(null),
|
||||
}));
|
||||
|
||||
// =============================================================================
|
||||
// Import after mocking
|
||||
// =============================================================================
|
||||
|
||||
import { runRoadmapGeneration } from '../roadmap';
|
||||
import type { RoadmapConfig, RoadmapStreamEvent } from '../roadmap';
|
||||
|
||||
// =============================================================================
|
||||
// Helpers
|
||||
// =============================================================================
|
||||
|
||||
const fakeModel = { modelId: 'claude-sonnet-test' };
|
||||
|
||||
function makeMockClient() {
|
||||
return {
|
||||
model: fakeModel,
|
||||
systemPrompt: '',
|
||||
tools: {},
|
||||
maxSteps: 30,
|
||||
};
|
||||
}
|
||||
|
||||
function makeStream(parts: Array<Record<string, unknown>>) {
|
||||
return {
|
||||
fullStream: (async function* () {
|
||||
for (const part of parts) {
|
||||
yield part;
|
||||
}
|
||||
})(),
|
||||
};
|
||||
}
|
||||
|
||||
/** Valid discovery JSON that passes schema validation */
|
||||
const VALID_DISCOVERY_JSON = JSON.stringify({
|
||||
project_name: 'TestProject',
|
||||
target_audience: 'Developers',
|
||||
product_vision: 'Make coding easier',
|
||||
key_features: ['Auth', 'Dashboard'],
|
||||
technical_stack: { language: 'TypeScript' },
|
||||
constraints: [],
|
||||
});
|
||||
|
||||
/** Valid roadmap JSON that passes schema validation (>=3 features, all required keys) */
|
||||
const VALID_ROADMAP_JSON = JSON.stringify({
|
||||
vision: 'Automate everything',
|
||||
target_audience: { primary: 'Developers', secondary: 'QA' },
|
||||
phases: [{ id: 'p1', name: 'MVP' }],
|
||||
features: [
|
||||
{
|
||||
id: 'f1', title: 'Feature A', description: 'Desc A', priority: 'high',
|
||||
complexity: 'medium', impact: 'high', phase_id: 'p1', status: 'planned',
|
||||
acceptance_criteria: [], user_stories: [],
|
||||
},
|
||||
{
|
||||
id: 'f2', title: 'Feature B', description: 'Desc B', priority: 'medium',
|
||||
complexity: 'low', impact: 'medium', phase_id: 'p1', status: 'planned',
|
||||
acceptance_criteria: [], user_stories: [],
|
||||
},
|
||||
{
|
||||
id: 'f3', title: 'Feature C', description: 'Desc C', priority: 'low',
|
||||
complexity: 'high', impact: 'low', phase_id: 'p1', status: 'planned',
|
||||
acceptance_criteria: [], user_stories: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
function baseConfig(overrides: Partial<RoadmapConfig> = {}): RoadmapConfig {
|
||||
return {
|
||||
projectDir: '/project',
|
||||
outputDir: '/project/.auto-claude/roadmap',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Tests
|
||||
// =============================================================================
|
||||
|
||||
describe('runRoadmapGeneration', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockCreateSimpleClient.mockResolvedValue(makeMockClient());
|
||||
// Output dir exists by default (created by mkdirSync is a no-op)
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
mockMkdirSync.mockReturnValue(undefined);
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Successful full pipeline
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns success with roadmapPath when both phases succeed', async () => {
|
||||
// existsSync: outputDir does not exist initially; discovery file created after phase 1
|
||||
let discoveryCreated = false;
|
||||
|
||||
mockExistsSync.mockImplementation((p: string) => {
|
||||
if (p.endsWith('roadmap')) return true; // outputDir exists
|
||||
if (p.endsWith('roadmap_discovery.json') && discoveryCreated) return true;
|
||||
if (p.endsWith('roadmap.json') && discoveryCreated) return false; // not yet
|
||||
return false;
|
||||
});
|
||||
|
||||
// streamText yields nothing — validation happens from file reads
|
||||
mockStreamText.mockImplementation(() => {
|
||||
discoveryCreated = true; // simulate file being written during stream
|
||||
return makeStream([]);
|
||||
});
|
||||
|
||||
// readFileSync returns valid JSON for each file
|
||||
mockReadFileSync.mockImplementation((p: string) => {
|
||||
if (p.endsWith('roadmap_discovery.json')) return VALID_DISCOVERY_JSON;
|
||||
if (p.endsWith('roadmap.json')) return VALID_ROADMAP_JSON;
|
||||
return '{}';
|
||||
});
|
||||
|
||||
// After agent runs, both files exist
|
||||
mockExistsSync.mockImplementation((p: string) => {
|
||||
if (p.endsWith('roadmap_discovery.json')) return true;
|
||||
if (p.endsWith('roadmap.json')) return true;
|
||||
return true; // outputDir, etc.
|
||||
});
|
||||
|
||||
const result = await runRoadmapGeneration(baseConfig());
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.roadmapPath).toContain('roadmap.json');
|
||||
expect(result.phases).toHaveLength(2);
|
||||
expect(result.phases[0].phase).toBe('discovery');
|
||||
expect(result.phases[1].phase).toBe('features');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Discovery phase failure
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns failure when discovery phase fails after all retries', async () => {
|
||||
// Discovery file is never created
|
||||
mockExistsSync.mockImplementation((p: string) => {
|
||||
if (p.endsWith('roadmap')) return true; // outputDir exists
|
||||
return false; // discovery file never appears
|
||||
});
|
||||
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
const result = await runRoadmapGeneration(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('Discovery failed');
|
||||
expect(result.phases).toHaveLength(1);
|
||||
expect(result.phases[0].phase).toBe('discovery');
|
||||
expect(result.phases[0].success).toBe(false);
|
||||
});
|
||||
|
||||
it('does not run features phase when discovery fails', async () => {
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
const result = await runRoadmapGeneration(baseConfig());
|
||||
|
||||
// Only 1 phase in result — features was never attempted
|
||||
expect(result.phases).toHaveLength(1);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Features phase failure
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('returns failure when features phase fails (no roadmap.json created)', async () => {
|
||||
mockExistsSync.mockImplementation((p: string) => {
|
||||
if (p.endsWith('roadmap')) return true;
|
||||
if (p.endsWith('roadmap_discovery.json')) return true; // discovery succeeded
|
||||
if (p.endsWith('project_index.json')) return false;
|
||||
return false; // roadmap.json never created
|
||||
});
|
||||
|
||||
mockReadFileSync.mockImplementation((p: string) => {
|
||||
if (p.endsWith('roadmap_discovery.json')) return VALID_DISCOVERY_JSON;
|
||||
return '{}';
|
||||
});
|
||||
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
const result = await runRoadmapGeneration(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('Feature generation failed');
|
||||
expect(result.phases).toHaveLength(2);
|
||||
expect(result.phases[1].phase).toBe('features');
|
||||
expect(result.phases[1].success).toBe(false);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cache (refresh=false) — skip phases when files already exist
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('skips discovery phase when discovery file already exists and refresh=false', async () => {
|
||||
mockExistsSync.mockImplementation((p: string) => {
|
||||
if (p.endsWith('roadmap')) return true;
|
||||
if (p.endsWith('roadmap_discovery.json')) return true; // already exists
|
||||
if (p.endsWith('roadmap.json')) return true; // also exists
|
||||
return false;
|
||||
});
|
||||
|
||||
const result = await runRoadmapGeneration(baseConfig({ refresh: false }));
|
||||
|
||||
// streamText should not have been called since both files exist
|
||||
expect(mockStreamText).not.toHaveBeenCalled();
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Output directory creation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('creates output directory when it does not exist', async () => {
|
||||
mockExistsSync.mockImplementation((p: string) => {
|
||||
if (p.endsWith('roadmap') && !p.includes('.json')) return false; // dir does not exist
|
||||
return false;
|
||||
});
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runRoadmapGeneration(baseConfig({ outputDir: '/project/.auto-claude/roadmap' }));
|
||||
|
||||
expect(mockMkdirSync).toHaveBeenCalledWith(
|
||||
expect.stringContaining('roadmap'),
|
||||
expect.objectContaining({ recursive: true }),
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Streaming events
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('emits phase-start and phase-complete events for both phases', async () => {
|
||||
// Make discovery succeed via cached file
|
||||
mockExistsSync.mockImplementation((p: string) => {
|
||||
if (p.endsWith('roadmap')) return true;
|
||||
if (p.endsWith('roadmap_discovery.json')) return true;
|
||||
if (p.endsWith('roadmap.json')) return true;
|
||||
return false;
|
||||
});
|
||||
|
||||
const events: RoadmapStreamEvent[] = [];
|
||||
await runRoadmapGeneration(baseConfig({ refresh: false }), (e) => events.push(e));
|
||||
|
||||
const phaseStartEvents = events.filter((e) => e.type === 'phase-start');
|
||||
const phaseCompleteEvents = events.filter((e) => e.type === 'phase-complete');
|
||||
|
||||
expect(phaseStartEvents).toHaveLength(2);
|
||||
expect(phaseCompleteEvents).toHaveLength(2);
|
||||
expect((phaseStartEvents[0] as { type: string; phase: string }).phase).toBe('discovery');
|
||||
expect((phaseStartEvents[1] as { type: string; phase: string }).phase).toBe('features');
|
||||
});
|
||||
|
||||
it('forwards text-delta events from stream to callback', async () => {
|
||||
mockExistsSync.mockImplementation((p: string) => {
|
||||
if (p.endsWith('roadmap_discovery.json')) return true;
|
||||
if (p.endsWith('roadmap.json')) return true;
|
||||
return true;
|
||||
});
|
||||
|
||||
const events: RoadmapStreamEvent[] = [];
|
||||
await runRoadmapGeneration(baseConfig({ refresh: false }), (e) => events.push(e));
|
||||
|
||||
// Since files exist and refresh=false, streamText is never called and no text-delta fires
|
||||
// This confirms the caching path works correctly
|
||||
const textEvents = events.filter((e) => e.type === 'text-delta');
|
||||
expect(textEvents).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('forwards text-delta from active streamText run when discovery must be generated', async () => {
|
||||
// outputDir exists, but discovery file does not (first attempt)
|
||||
// After first streamText run, discovery file appears
|
||||
let callCount = 0;
|
||||
mockExistsSync.mockImplementation((p: string) => {
|
||||
if (p.endsWith('roadmap') && !p.includes('.json')) return true;
|
||||
if (p.endsWith('roadmap_discovery.json')) return callCount > 0;
|
||||
return false;
|
||||
});
|
||||
|
||||
mockReadFileSync.mockReturnValue(VALID_DISCOVERY_JSON);
|
||||
|
||||
mockStreamText.mockImplementation(() => {
|
||||
callCount++;
|
||||
return {
|
||||
fullStream: (async function* () {
|
||||
yield { type: 'text-delta', text: 'Analyzing project...' };
|
||||
})(),
|
||||
};
|
||||
});
|
||||
|
||||
const events: RoadmapStreamEvent[] = [];
|
||||
await runRoadmapGeneration(baseConfig(), (e) => events.push(e));
|
||||
|
||||
const textEvents = events.filter((e) => e.type === 'text-delta');
|
||||
expect(textEvents.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Client configuration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('uses sonnet and medium thinking level by default', async () => {
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runRoadmapGeneration(baseConfig());
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('sonnet');
|
||||
expect(clientArgs.thinkingLevel).toBe('medium');
|
||||
});
|
||||
|
||||
it('accepts custom modelShorthand and thinkingLevel', async () => {
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runRoadmapGeneration(baseConfig({ modelShorthand: 'haiku', thinkingLevel: 'low' }));
|
||||
|
||||
const clientArgs = mockCreateSimpleClient.mock.calls[0][0];
|
||||
expect(clientArgs.modelShorthand).toBe('haiku');
|
||||
expect(clientArgs.thinkingLevel).toBe('low');
|
||||
});
|
||||
|
||||
it('uses default outputDir when not provided', async () => {
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
mockStreamText.mockReturnValue(makeStream([]));
|
||||
|
||||
await runRoadmapGeneration({ projectDir: '/my/project' });
|
||||
|
||||
// mkdirSync should have been called with the default path
|
||||
expect(mockMkdirSync).toHaveBeenCalledWith(
|
||||
expect.stringContaining('.auto-claude'),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Error handling — streamText throws
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
it('records error in phase when streamText throws during discovery', async () => {
|
||||
mockExistsSync.mockImplementation((p: string) => {
|
||||
if (p.endsWith('roadmap') && !p.includes('.json')) return true;
|
||||
return false;
|
||||
});
|
||||
|
||||
mockStreamText.mockImplementation(() => {
|
||||
return {
|
||||
// biome-ignore lint/correctness/useYield: intentionally throwing before yield to test error path
|
||||
fullStream: (async function* () {
|
||||
throw new Error('network failure');
|
||||
})(),
|
||||
};
|
||||
});
|
||||
|
||||
const result = await runRoadmapGeneration(baseConfig());
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.phases[0].errors.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -382,7 +382,7 @@ ${diffContent}
|
||||
}
|
||||
|
||||
lines.push('---');
|
||||
lines.push('_Generated by Auto Claude MR Review_');
|
||||
lines.push('_Generated by Aperant MR Review_');
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ const BLOCKED_PROCESS_NAMES = new Set([
|
||||
'electron',
|
||||
'Electron',
|
||||
'auto-claude',
|
||||
'Auto Claude',
|
||||
'Aperant',
|
||||
]);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
import { bashTool } from '../bash';
|
||||
import type { ToolContext } from '../../types';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const mockExecFile = vi.fn();
|
||||
vi.mock('node:child_process', () => ({
|
||||
execFile: (...args: unknown[]) => mockExecFile(...args),
|
||||
}));
|
||||
|
||||
const mockIsWindows = vi.fn(() => false);
|
||||
const mockFindExecutable = vi.fn(() => null);
|
||||
const mockKillProcessGracefully = vi.fn();
|
||||
|
||||
vi.mock('../../../../platform/index', () => ({
|
||||
isWindows: () => mockIsWindows(),
|
||||
findExecutable: (_name: string, _additionalPaths?: string[]) => mockFindExecutable(),
|
||||
killProcessGracefully: (_childProcess: unknown, _options?: unknown) => mockKillProcessGracefully(),
|
||||
}));
|
||||
|
||||
const mockBashSecurityHook = vi.fn(() => ({}));
|
||||
vi.mock('../../../security/bash-validator', () => ({
|
||||
bashSecurityHook: (_input: unknown, _profile?: unknown) => mockBashSecurityHook(),
|
||||
}));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const baseContext: ToolContext = {
|
||||
cwd: '/test/project',
|
||||
projectDir: '/test/project',
|
||||
specDir: '/test/specs/001',
|
||||
securityProfile: {
|
||||
baseCommands: new Set(),
|
||||
stackCommands: new Set(),
|
||||
scriptCommands: new Set(),
|
||||
customCommands: new Set(),
|
||||
customScripts: { shellScripts: [] },
|
||||
getAllAllowedCommands: () => new Set(),
|
||||
},
|
||||
} as unknown as ToolContext;
|
||||
|
||||
/**
|
||||
* Set up mockExecFile to invoke the callback with the provided values.
|
||||
*/
|
||||
function setupExecFile(stdout: string, stderr: string, exitCode: number) {
|
||||
mockExecFile.mockImplementation(
|
||||
(_shell: unknown, _args: unknown, _opts: unknown, callback: (err: Error | null, stdout: string, stderr: string) => void) => {
|
||||
const err = exitCode !== 0 ? Object.assign(new Error('exit'), { code: exitCode }) : null;
|
||||
callback(err, stdout, stderr);
|
||||
return { pid: 1234 };
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Bash Tool', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockIsWindows.mockReturnValue(false);
|
||||
mockBashSecurityHook.mockReturnValue({});
|
||||
});
|
||||
|
||||
it('should have correct metadata', () => {
|
||||
expect(bashTool.metadata.name).toBe('Bash');
|
||||
expect(bashTool.metadata.permission).toBe('requires_approval');
|
||||
});
|
||||
|
||||
it('should return stdout from successful command', async () => {
|
||||
setupExecFile('hello from bash\n', '', 0);
|
||||
|
||||
const result = await bashTool.config.execute(
|
||||
{ command: 'echo hello from bash' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('hello from bash');
|
||||
});
|
||||
|
||||
it('should include stderr in output when present', async () => {
|
||||
setupExecFile('', 'some warning\n', 0);
|
||||
|
||||
const result = await bashTool.config.execute(
|
||||
{ command: 'cmd-with-stderr' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('STDERR:');
|
||||
expect(result).toContain('some warning');
|
||||
});
|
||||
|
||||
it('should include exit code in output when non-zero', async () => {
|
||||
setupExecFile('', '', 1);
|
||||
|
||||
const result = await bashTool.config.execute(
|
||||
{ command: 'failing-command' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Exit code: 1');
|
||||
});
|
||||
|
||||
it('should return (no output) when stdout and stderr are empty and exit code is 0', async () => {
|
||||
setupExecFile('', '', 0);
|
||||
|
||||
const result = await bashTool.config.execute(
|
||||
{ command: 'silent-command' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
});
|
||||
|
||||
it('should truncate output exceeding MAX_OUTPUT_LENGTH', async () => {
|
||||
const longOutput = 'x'.repeat(31_000);
|
||||
setupExecFile(longOutput, '', 0);
|
||||
|
||||
const result = await bashTool.config.execute(
|
||||
{ command: 'long-output-cmd' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('[Output truncated');
|
||||
expect(result.length).toBeLessThan(longOutput.length);
|
||||
});
|
||||
|
||||
it('should return error message when security hook rejects command', async () => {
|
||||
mockBashSecurityHook.mockReturnValue({
|
||||
hookSpecificOutput: {
|
||||
permissionDecisionReason: 'command is blocked for safety',
|
||||
},
|
||||
});
|
||||
|
||||
const result = await bashTool.config.execute(
|
||||
{ command: 'rm -rf /' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Error: Command not allowed');
|
||||
expect(result).toContain('command is blocked for safety');
|
||||
expect(mockExecFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should start command in background and return immediately', async () => {
|
||||
// In background mode the execute call is fire-and-forget, so mockExecFile
|
||||
// may or may not be called synchronously. The return value is what matters.
|
||||
mockExecFile.mockImplementation(
|
||||
(_shell: unknown, _args: unknown, _opts: unknown, _callback: unknown) => {
|
||||
return { pid: 5678 };
|
||||
},
|
||||
);
|
||||
|
||||
const result = await bashTool.config.execute(
|
||||
{ command: 'sleep 100', run_in_background: true },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Command started in background');
|
||||
expect(result).toContain('sleep 100');
|
||||
});
|
||||
|
||||
it('should pass cwd from context to execFile', async () => {
|
||||
setupExecFile('output', '', 0);
|
||||
|
||||
await bashTool.config.execute(
|
||||
{ command: 'pwd' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(mockExecFile).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.any(Array),
|
||||
expect.objectContaining({ cwd: '/test/project' }),
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
|
||||
it('should cap timeout to MAX_TIMEOUT_MS (600000)', async () => {
|
||||
setupExecFile('output', '', 0);
|
||||
|
||||
await bashTool.config.execute(
|
||||
{ command: 'cmd', timeout: 9_000_000 },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(mockExecFile).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.any(Array),
|
||||
expect.objectContaining({ timeout: 600_000 }),
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
|
||||
it('should use /bin/bash as shell on non-Windows', async () => {
|
||||
mockIsWindows.mockReturnValue(false);
|
||||
setupExecFile('output', '', 0);
|
||||
|
||||
await bashTool.config.execute(
|
||||
{ command: 'echo hi' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(mockExecFile).toHaveBeenCalledWith(
|
||||
'/bin/bash',
|
||||
['-c', 'echo hi'],
|
||||
expect.any(Object),
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
|
||||
it('should use cmd.exe args (/c) on Windows when bash not found', async () => {
|
||||
// The Windows branch uses /c rather than -c for cmd.exe.
|
||||
// We verify the logic by checking that bash uses -c on non-Windows (already tested
|
||||
// above) and that the findExecutable mock would select the right executable.
|
||||
// This test validates the cmd.exe ComSpec fallback resolution path.
|
||||
mockIsWindows.mockReturnValue(true);
|
||||
mockFindExecutable.mockReturnValue(null);
|
||||
|
||||
const origComSpec = process.env.ComSpec;
|
||||
process.env.ComSpec = 'C:\\Windows\\System32\\cmd.exe';
|
||||
|
||||
setupExecFile('output', '', 0);
|
||||
|
||||
await bashTool.config.execute(
|
||||
{ command: 'dir' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
// Verify that on Windows with no bash found, cmd.exe with /c flag is used
|
||||
const callArgs = mockExecFile.mock.calls[0];
|
||||
const shell = callArgs[0] as string;
|
||||
const args = callArgs[1] as string[];
|
||||
|
||||
// The shell should be cmd.exe (via ComSpec) and arg should be /c
|
||||
expect(shell).toBe('C:\\Windows\\System32\\cmd.exe');
|
||||
expect(args[0]).toBe('/c');
|
||||
expect(args[1]).toBe('dir');
|
||||
|
||||
process.env.ComSpec = origComSpec;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
import { editTool } from '../edit';
|
||||
import type { ToolContext } from '../../types';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock('node:fs');
|
||||
vi.mock('../../../security/path-containment', () => ({
|
||||
assertPathContained: vi.fn((_filePath: string, _projectDir: string) => ({
|
||||
contained: true,
|
||||
resolvedPath: _filePath,
|
||||
})),
|
||||
}));
|
||||
|
||||
import * as fs from 'node:fs';
|
||||
import { assertPathContained } from '../../../security/path-containment';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const baseContext: ToolContext = {
|
||||
cwd: '/test/project',
|
||||
projectDir: '/test/project',
|
||||
specDir: '/test/specs/001',
|
||||
securityProfile: {
|
||||
baseCommands: new Set(),
|
||||
stackCommands: new Set(),
|
||||
scriptCommands: new Set(),
|
||||
customCommands: new Set(),
|
||||
customScripts: { shellScripts: [] },
|
||||
getAllAllowedCommands: () => new Set(),
|
||||
},
|
||||
} as unknown as ToolContext;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Edit Tool', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(assertPathContained).mockImplementation((_filePath: string, _projectDir: string) => ({
|
||||
contained: true,
|
||||
resolvedPath: _filePath,
|
||||
}));
|
||||
});
|
||||
|
||||
it('should have correct metadata', () => {
|
||||
expect(editTool.metadata.name).toBe('Edit');
|
||||
expect(editTool.metadata.permission).toBe('requires_approval');
|
||||
});
|
||||
|
||||
it('should successfully replace a single occurrence', async () => {
|
||||
vi.mocked(fs.readFileSync).mockReturnValue('hello world foo bar');
|
||||
vi.mocked(fs.writeFileSync).mockImplementation(() => undefined);
|
||||
|
||||
const result = await editTool.config.execute(
|
||||
{
|
||||
file_path: '/test/project/file.ts',
|
||||
old_string: 'hello world',
|
||||
new_string: 'goodbye world',
|
||||
replace_all: false,
|
||||
},
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Successfully edited');
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(
|
||||
'/test/project/file.ts',
|
||||
'goodbye world foo bar',
|
||||
'utf-8',
|
||||
);
|
||||
});
|
||||
|
||||
it('should replace all occurrences when replace_all is true', async () => {
|
||||
vi.mocked(fs.readFileSync).mockReturnValue('foo bar foo baz foo');
|
||||
vi.mocked(fs.writeFileSync).mockImplementation(() => undefined);
|
||||
|
||||
const result = await editTool.config.execute(
|
||||
{
|
||||
file_path: '/test/project/file.ts',
|
||||
old_string: 'foo',
|
||||
new_string: 'qux',
|
||||
replace_all: true,
|
||||
},
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Successfully replaced 3 occurrence(s)');
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(
|
||||
'/test/project/file.ts',
|
||||
'qux bar qux baz qux',
|
||||
'utf-8',
|
||||
);
|
||||
});
|
||||
|
||||
it('should return error when old_string not found in file', async () => {
|
||||
vi.mocked(fs.readFileSync).mockReturnValue('some other content');
|
||||
|
||||
const result = await editTool.config.execute(
|
||||
{
|
||||
file_path: '/test/project/file.ts',
|
||||
old_string: 'nonexistent text',
|
||||
new_string: 'replacement',
|
||||
replace_all: false,
|
||||
},
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Error: old_string not found');
|
||||
expect(fs.writeFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return error when old_string matches multiple locations without replace_all', async () => {
|
||||
vi.mocked(fs.readFileSync).mockReturnValue('foo foo foo');
|
||||
|
||||
const result = await editTool.config.execute(
|
||||
{
|
||||
file_path: '/test/project/file.ts',
|
||||
old_string: 'foo',
|
||||
new_string: 'bar',
|
||||
replace_all: false,
|
||||
},
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Error: old_string appears 3 times');
|
||||
expect(result).toContain('replace_all: true');
|
||||
expect(fs.writeFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return error when old_string equals new_string', async () => {
|
||||
const result = await editTool.config.execute(
|
||||
{
|
||||
file_path: '/test/project/file.ts',
|
||||
old_string: 'same text',
|
||||
new_string: 'same text',
|
||||
replace_all: false,
|
||||
},
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Error: old_string and new_string are identical');
|
||||
expect(fs.readFileSync).not.toHaveBeenCalled();
|
||||
expect(fs.writeFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return error when file not found', async () => {
|
||||
const enoentError = Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
|
||||
vi.mocked(fs.readFileSync).mockImplementation(() => { throw enoentError; });
|
||||
|
||||
const result = await editTool.config.execute(
|
||||
{
|
||||
file_path: '/test/project/missing.ts',
|
||||
old_string: 'old',
|
||||
new_string: 'new',
|
||||
replace_all: false,
|
||||
},
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Error: File not found');
|
||||
});
|
||||
|
||||
it('should throw non-ENOENT filesystem errors', async () => {
|
||||
const permError = Object.assign(new Error('EACCES'), { code: 'EACCES' });
|
||||
vi.mocked(fs.readFileSync).mockImplementation(() => { throw permError; });
|
||||
|
||||
await expect(
|
||||
editTool.config.execute(
|
||||
{
|
||||
file_path: '/test/project/file.ts',
|
||||
old_string: 'old',
|
||||
new_string: 'new',
|
||||
replace_all: false,
|
||||
},
|
||||
baseContext,
|
||||
),
|
||||
).rejects.toThrow('EACCES');
|
||||
});
|
||||
|
||||
it('should call assertPathContained for path security', async () => {
|
||||
vi.mocked(fs.readFileSync).mockReturnValue('hello world');
|
||||
vi.mocked(fs.writeFileSync).mockImplementation(() => undefined);
|
||||
|
||||
await editTool.config.execute(
|
||||
{
|
||||
file_path: '/test/project/file.ts',
|
||||
old_string: 'hello world',
|
||||
new_string: 'goodbye world',
|
||||
replace_all: false,
|
||||
},
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(assertPathContained).toHaveBeenCalledWith('/test/project/file.ts', '/test/project');
|
||||
});
|
||||
|
||||
it('should throw when path is outside project boundary', async () => {
|
||||
vi.mocked(assertPathContained).mockImplementation(() => {
|
||||
throw new Error("Path '/etc/passwd' is outside the project directory");
|
||||
});
|
||||
|
||||
await expect(
|
||||
editTool.config.execute(
|
||||
{
|
||||
file_path: '/etc/passwd',
|
||||
old_string: 'root',
|
||||
new_string: 'hacked',
|
||||
replace_all: false,
|
||||
},
|
||||
baseContext,
|
||||
),
|
||||
).rejects.toThrow('outside the project directory');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
import path from 'node:path';
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
import { globTool } from '../glob';
|
||||
import type { ToolContext } from '../../types';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock('node:fs');
|
||||
vi.mock('../../../security/path-containment', () => ({
|
||||
assertPathContained: vi.fn((_filePath: string, _projectDir: string) => ({
|
||||
contained: true,
|
||||
resolvedPath: _filePath,
|
||||
})),
|
||||
}));
|
||||
vi.mock('../../truncation', () => ({
|
||||
truncateToolOutput: vi.fn((output: string) => ({
|
||||
content: output,
|
||||
wasTruncated: false,
|
||||
originalSize: Buffer.byteLength(output, 'utf-8'),
|
||||
})),
|
||||
}));
|
||||
|
||||
import * as fs from 'node:fs';
|
||||
import { assertPathContained } from '../../../security/path-containment';
|
||||
import { truncateToolOutput } from '../../truncation';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const baseContext: ToolContext = {
|
||||
cwd: '/test/project',
|
||||
projectDir: '/test/project',
|
||||
specDir: '/test/specs/001',
|
||||
securityProfile: {
|
||||
baseCommands: new Set(),
|
||||
stackCommands: new Set(),
|
||||
scriptCommands: new Set(),
|
||||
customCommands: new Set(),
|
||||
customScripts: { shellScripts: [] },
|
||||
getAllAllowedCommands: () => new Set(),
|
||||
},
|
||||
} as unknown as ToolContext;
|
||||
|
||||
/**
|
||||
* Configure fs mocks for a glob run that returns the given absolute paths.
|
||||
* Each path gets a fake mtime so sorting can be tested.
|
||||
*/
|
||||
function setupGlobMatches(absolutePaths: string[], mtimes?: number[]) {
|
||||
// existsSync for the search dir
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||
|
||||
// globSync returns relative filenames that the tool will resolve
|
||||
const relPaths = absolutePaths.map((p) => p.replace('/test/project/', ''));
|
||||
vi.mocked(fs.globSync).mockReturnValue(relPaths);
|
||||
|
||||
// statSync used twice: once to check isFile, once to get mtime
|
||||
let callIdx = 0;
|
||||
vi.mocked(fs.statSync).mockImplementation((_p) => {
|
||||
const mtime = mtimes ? mtimes[callIdx % mtimes.length] : 1000;
|
||||
callIdx++;
|
||||
return {
|
||||
isFile: () => true,
|
||||
mtimeMs: mtime,
|
||||
} as unknown as fs.Stats;
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Glob Tool', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(assertPathContained).mockImplementation((_filePath: string, _projectDir: string) => ({
|
||||
contained: true,
|
||||
resolvedPath: _filePath,
|
||||
}));
|
||||
vi.mocked(truncateToolOutput).mockImplementation((output: string) => ({
|
||||
content: output,
|
||||
wasTruncated: false,
|
||||
originalSize: Buffer.byteLength(output, 'utf-8'),
|
||||
}));
|
||||
});
|
||||
|
||||
it('should have correct metadata', () => {
|
||||
expect(globTool.metadata.name).toBe('Glob');
|
||||
expect(globTool.metadata.permission).toBe('read_only');
|
||||
});
|
||||
|
||||
it('should return matching file paths', async () => {
|
||||
setupGlobMatches([
|
||||
'/test/project/src/index.ts',
|
||||
'/test/project/src/utils.ts',
|
||||
]);
|
||||
|
||||
const result = await globTool.config.execute(
|
||||
{ pattern: '**/*.ts' },
|
||||
baseContext,
|
||||
) as string;
|
||||
|
||||
expect(result).toContain('index.ts');
|
||||
expect(result).toContain('utils.ts');
|
||||
});
|
||||
|
||||
it('should return "No files found" when pattern matches nothing', async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||
vi.mocked(fs.globSync).mockReturnValue([]);
|
||||
|
||||
const result = await globTool.config.execute(
|
||||
{ pattern: '**/*.nonexistent' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toBe('No files found');
|
||||
});
|
||||
|
||||
it('should return error when search directory does not exist', async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
||||
|
||||
const result = await globTool.config.execute(
|
||||
{ pattern: '*.ts', path: '/test/project/missing-dir' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Error: Directory not found');
|
||||
});
|
||||
|
||||
it('should sort results by mtime (most recent first)', async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||
vi.mocked(fs.globSync).mockReturnValue(['old.ts', 'new.ts', 'middle.ts']);
|
||||
|
||||
// Return different mtimes for isFile check vs mtime check
|
||||
// statSync is called once per file for isFile and once per file for mtime
|
||||
const mtimes: Record<string, number> = {
|
||||
[path.resolve('/test/project', 'old.ts')]: 1000,
|
||||
[path.resolve('/test/project', 'new.ts')]: 3000,
|
||||
[path.resolve('/test/project', 'middle.ts')]: 2000,
|
||||
};
|
||||
|
||||
vi.mocked(fs.statSync).mockImplementation((p) => ({
|
||||
isFile: () => true,
|
||||
mtimeMs: mtimes[p as string] ?? 1000,
|
||||
} as unknown as fs.Stats));
|
||||
|
||||
const result = await globTool.config.execute(
|
||||
{ pattern: '*.ts' },
|
||||
baseContext,
|
||||
) as string;
|
||||
|
||||
const lines = result.split('\n');
|
||||
const newIdx = lines.findIndex((l) => l.includes('new.ts'));
|
||||
const middleIdx = lines.findIndex((l) => l.includes('middle.ts'));
|
||||
const oldIdx = lines.findIndex((l) => l.includes('old.ts'));
|
||||
|
||||
expect(newIdx).toBeLessThan(middleIdx);
|
||||
expect(middleIdx).toBeLessThan(oldIdx);
|
||||
});
|
||||
|
||||
it('should use provided path instead of cwd when given', async () => {
|
||||
setupGlobMatches(['/test/project/sub/file.ts']);
|
||||
|
||||
await globTool.config.execute(
|
||||
{ pattern: '*.ts', path: '/test/project/sub' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(fs.globSync).toHaveBeenCalledWith('*.ts', expect.objectContaining({
|
||||
cwd: '/test/project/sub',
|
||||
}));
|
||||
});
|
||||
|
||||
it('should exclude node_modules and .git from results', async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||
vi.mocked(fs.globSync).mockReturnValue(['src/index.ts']);
|
||||
vi.mocked(fs.statSync).mockReturnValue({
|
||||
isFile: () => true,
|
||||
mtimeMs: 1000,
|
||||
} as unknown as fs.Stats);
|
||||
|
||||
await globTool.config.execute(
|
||||
{ pattern: '**/*.ts' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
// The exclude function passed to globSync should exclude node_modules/.git
|
||||
const globSyncCall = vi.mocked(fs.globSync).mock.calls[0];
|
||||
const opts = globSyncCall[1] as { exclude?: (name: string) => boolean };
|
||||
expect(opts.exclude).toBeDefined();
|
||||
expect(opts.exclude?.('node_modules')).toBe(true);
|
||||
expect(opts.exclude?.('.git')).toBe(true);
|
||||
expect(opts.exclude?.('src')).toBe(false);
|
||||
});
|
||||
|
||||
it('should call assertPathContained for path security', async () => {
|
||||
setupGlobMatches([]);
|
||||
vi.mocked(fs.globSync).mockReturnValue([]);
|
||||
|
||||
await globTool.config.execute(
|
||||
{ pattern: '*.ts' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(assertPathContained).toHaveBeenCalledWith('/test/project', '/test/project');
|
||||
});
|
||||
|
||||
it('should pass output through truncateToolOutput', async () => {
|
||||
setupGlobMatches(['/test/project/a.ts']);
|
||||
|
||||
await globTool.config.execute(
|
||||
{ pattern: '*.ts' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(truncateToolOutput).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,269 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
import { grepTool } from '../grep';
|
||||
import type { ToolContext } from '../../types';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const mockExecFile = vi.fn();
|
||||
vi.mock('node:child_process', () => ({
|
||||
execFile: (...args: unknown[]) => mockExecFile(...args),
|
||||
}));
|
||||
|
||||
const mockFindExecutable = vi.fn(() => '/usr/bin/rg');
|
||||
|
||||
vi.mock('../../../../platform/index', () => ({
|
||||
findExecutable: (_name: string, _additionalPaths?: string[]) => mockFindExecutable(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../security/path-containment', () => ({
|
||||
assertPathContained: vi.fn((_filePath: string, _projectDir: string) => ({
|
||||
contained: true,
|
||||
resolvedPath: _filePath,
|
||||
})),
|
||||
}));
|
||||
|
||||
import { assertPathContained } from '../../../security/path-containment';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const baseContext: ToolContext = {
|
||||
cwd: '/test/project',
|
||||
projectDir: '/test/project',
|
||||
specDir: '/test/specs/001',
|
||||
securityProfile: {
|
||||
baseCommands: new Set(),
|
||||
stackCommands: new Set(),
|
||||
scriptCommands: new Set(),
|
||||
customCommands: new Set(),
|
||||
customScripts: { shellScripts: [] },
|
||||
getAllAllowedCommands: () => new Set(),
|
||||
},
|
||||
} as unknown as ToolContext;
|
||||
|
||||
/**
|
||||
* Set up mockExecFile to invoke the callback with the provided rg output values.
|
||||
*/
|
||||
function setupRg(stdout: string, stderr: string, exitCode: number) {
|
||||
mockExecFile.mockImplementation(
|
||||
(
|
||||
_rgPath: unknown,
|
||||
_args: unknown,
|
||||
_opts: unknown,
|
||||
callback: (err: Error | null, stdout: string, stderr: string) => void,
|
||||
) => {
|
||||
const err = exitCode !== 0 ? Object.assign(new Error('exit'), { code: exitCode }) : null;
|
||||
callback(err, stdout, stderr);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Grep Tool', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Re-set after clearAllMocks wipes the return value
|
||||
mockFindExecutable.mockReturnValue('/usr/bin/rg');
|
||||
vi.mocked(assertPathContained).mockImplementation((_filePath: string, _projectDir: string) => ({
|
||||
contained: true,
|
||||
resolvedPath: _filePath,
|
||||
}));
|
||||
});
|
||||
|
||||
it('should have correct metadata', () => {
|
||||
expect(grepTool.metadata.name).toBe('Grep');
|
||||
expect(grepTool.metadata.permission).toBe('read_only');
|
||||
});
|
||||
|
||||
it('should return matching files in files_with_matches mode (default)', async () => {
|
||||
setupRg('/test/project/src/index.ts\n/test/project/src/utils.ts\n', '', 0);
|
||||
|
||||
const result = await grepTool.config.execute(
|
||||
{ pattern: 'myFunction' },
|
||||
baseContext,
|
||||
) as string;
|
||||
|
||||
expect(result).toContain('/test/project/src/index.ts');
|
||||
expect(result).toContain('/test/project/src/utils.ts');
|
||||
});
|
||||
|
||||
it('should return "No matches found" when rg exits with code 1 and no stderr', async () => {
|
||||
setupRg('', '', 1);
|
||||
|
||||
const result = await grepTool.config.execute(
|
||||
{ pattern: 'nonexistent_pattern_xyz' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toBe('No matches found');
|
||||
});
|
||||
|
||||
it('should return "No matches found" when stdout is empty', async () => {
|
||||
setupRg(' \n', '', 0);
|
||||
|
||||
const result = await grepTool.config.execute(
|
||||
{ pattern: 'something' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toBe('No matches found');
|
||||
});
|
||||
|
||||
it('should return error message when rg exits with code > 1 and stderr', async () => {
|
||||
setupRg('', 'rg: error: unknown file type\n', 2);
|
||||
|
||||
const result = await grepTool.config.execute(
|
||||
{ pattern: 'test', type: 'unknowntype' },
|
||||
baseContext,
|
||||
) as string;
|
||||
|
||||
expect(result).toContain('Error:');
|
||||
expect(result).toContain('unknown file type');
|
||||
});
|
||||
|
||||
it('should return error when ripgrep is not installed', async () => {
|
||||
mockFindExecutable.mockReturnValue(null as unknown as string);
|
||||
|
||||
const result = await grepTool.config.execute(
|
||||
{ pattern: 'test' },
|
||||
baseContext,
|
||||
) as string;
|
||||
|
||||
expect(result).toContain('Error:');
|
||||
expect(result).toContain('ripgrep');
|
||||
});
|
||||
|
||||
it('should include --files-with-matches flag in default mode', async () => {
|
||||
setupRg('/test/project/a.ts\n', '', 0);
|
||||
|
||||
await grepTool.config.execute(
|
||||
{ pattern: 'hello' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
const args = mockExecFile.mock.calls[0][1] as string[];
|
||||
expect(args).toContain('--files-with-matches');
|
||||
});
|
||||
|
||||
it('should include --line-number flag in content mode', async () => {
|
||||
setupRg('src/a.ts:10:const hello = 1;\n', '', 0);
|
||||
|
||||
await grepTool.config.execute(
|
||||
{ pattern: 'hello', output_mode: 'content' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
const args = mockExecFile.mock.calls[0][1] as string[];
|
||||
expect(args).toContain('--line-number');
|
||||
expect(args).not.toContain('--files-with-matches');
|
||||
expect(args).not.toContain('--count');
|
||||
});
|
||||
|
||||
it('should include --count flag in count mode', async () => {
|
||||
setupRg('src/a.ts:5\n', '', 0);
|
||||
|
||||
await grepTool.config.execute(
|
||||
{ pattern: 'hello', output_mode: 'count' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
const args = mockExecFile.mock.calls[0][1] as string[];
|
||||
expect(args).toContain('--count');
|
||||
});
|
||||
|
||||
it('should add -C flag when context lines are specified in content mode', async () => {
|
||||
setupRg('match output\n', '', 0);
|
||||
|
||||
await grepTool.config.execute(
|
||||
{ pattern: 'hello', output_mode: 'content', context: 3 },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
const args = mockExecFile.mock.calls[0][1] as string[];
|
||||
expect(args).toContain('-C');
|
||||
expect(args).toContain('3');
|
||||
});
|
||||
|
||||
it('should add --type flag when type is specified', async () => {
|
||||
setupRg('/test/project/a.ts\n', '', 0);
|
||||
|
||||
await grepTool.config.execute(
|
||||
{ pattern: 'hello', type: 'ts' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
const args = mockExecFile.mock.calls[0][1] as string[];
|
||||
expect(args).toContain('--type');
|
||||
expect(args).toContain('ts');
|
||||
});
|
||||
|
||||
it('should add --glob flag when glob is specified', async () => {
|
||||
setupRg('/test/project/src/a.ts\n', '', 0);
|
||||
|
||||
await grepTool.config.execute(
|
||||
{ pattern: 'hello', glob: '*.{ts,tsx}' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
const args = mockExecFile.mock.calls[0][1] as string[];
|
||||
expect(args).toContain('--glob');
|
||||
expect(args).toContain('*.{ts,tsx}');
|
||||
});
|
||||
|
||||
it('should truncate output exceeding MAX_OUTPUT_LENGTH', async () => {
|
||||
const longOutput = '/test/project/file.ts\n'.repeat(2000);
|
||||
setupRg(longOutput, '', 0);
|
||||
|
||||
const result = await grepTool.config.execute(
|
||||
{ pattern: 'test' },
|
||||
baseContext,
|
||||
) as string;
|
||||
|
||||
expect(result).toContain('[Output truncated');
|
||||
expect(result.length).toBeLessThan(longOutput.length);
|
||||
});
|
||||
|
||||
it('should call assertPathContained for path security', async () => {
|
||||
setupRg('/test/project/a.ts\n', '', 0);
|
||||
|
||||
await grepTool.config.execute(
|
||||
{ pattern: 'hello' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(assertPathContained).toHaveBeenCalledWith('/test/project', '/test/project');
|
||||
});
|
||||
|
||||
it('should throw when search path is outside project boundary', async () => {
|
||||
vi.mocked(assertPathContained).mockImplementation(() => {
|
||||
throw new Error("Path '/etc' is outside the project directory");
|
||||
});
|
||||
|
||||
await expect(
|
||||
grepTool.config.execute(
|
||||
{ pattern: 'root', path: '/etc' },
|
||||
baseContext,
|
||||
),
|
||||
).rejects.toThrow('outside the project directory');
|
||||
});
|
||||
|
||||
it('should use provided path for search instead of cwd', async () => {
|
||||
setupRg('/test/project/sub/a.ts\n', '', 0);
|
||||
|
||||
await grepTool.config.execute(
|
||||
{ pattern: 'hello', path: '/test/project/sub' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
const args = mockExecFile.mock.calls[0][1] as string[];
|
||||
// The resolved search path should be the last argument before the pattern
|
||||
expect(args).toContain('/test/project/sub');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,227 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
import { readTool } from '../read';
|
||||
import type { ToolContext } from '../../types';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock('node:fs');
|
||||
vi.mock('../../../security/path-containment', () => ({
|
||||
assertPathContained: vi.fn((_filePath: string, _projectDir: string) => ({
|
||||
contained: true,
|
||||
resolvedPath: _filePath,
|
||||
})),
|
||||
}));
|
||||
|
||||
import * as fs from 'node:fs';
|
||||
import { assertPathContained } from '../../../security/path-containment';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const baseContext: ToolContext = {
|
||||
cwd: '/test/project',
|
||||
projectDir: '/test/project',
|
||||
specDir: '/test/specs/001',
|
||||
securityProfile: {
|
||||
baseCommands: new Set(),
|
||||
stackCommands: new Set(),
|
||||
scriptCommands: new Set(),
|
||||
customCommands: new Set(),
|
||||
customScripts: { shellScripts: [] },
|
||||
getAllAllowedCommands: () => new Set(),
|
||||
},
|
||||
} as unknown as ToolContext;
|
||||
|
||||
/**
|
||||
* Set up the fs mock sequence for a successful text file read.
|
||||
*
|
||||
* openSync → fd, fstatSync → stat object, readFileSync → content, closeSync → void
|
||||
*/
|
||||
function setupTextFile(content: string, isDir = false) {
|
||||
const fakeFd = 42;
|
||||
vi.mocked(fs.openSync).mockReturnValue(fakeFd as unknown as number);
|
||||
vi.mocked(fs.fstatSync).mockReturnValue({
|
||||
isDirectory: () => isDir,
|
||||
size: Buffer.byteLength(content),
|
||||
} as unknown as fs.Stats);
|
||||
vi.mocked(fs.readFileSync).mockReturnValue(content);
|
||||
vi.mocked(fs.closeSync).mockImplementation(() => undefined);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Read Tool', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(assertPathContained).mockImplementation((_filePath: string, _projectDir: string) => ({
|
||||
contained: true,
|
||||
resolvedPath: _filePath,
|
||||
}));
|
||||
});
|
||||
|
||||
it('should have correct metadata', () => {
|
||||
expect(readTool.metadata.name).toBe('Read');
|
||||
expect(readTool.metadata.permission).toBe('read_only');
|
||||
});
|
||||
|
||||
it('should read an entire file with line numbers', async () => {
|
||||
setupTextFile('line one\nline two\nline three');
|
||||
|
||||
const result = await readTool.config.execute(
|
||||
{ file_path: '/test/project/file.ts' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('line one');
|
||||
expect(result).toContain('line two');
|
||||
expect(result).toContain('line three');
|
||||
// Line numbers should be present (cat -n style)
|
||||
expect(result).toMatch(/\d+\t/);
|
||||
});
|
||||
|
||||
it('should format output with correct line numbers', async () => {
|
||||
setupTextFile('alpha\nbeta\ngamma');
|
||||
|
||||
const result = await readTool.config.execute(
|
||||
{ file_path: '/test/project/file.ts' },
|
||||
baseContext,
|
||||
) as string;
|
||||
|
||||
const lines = result.split('\n');
|
||||
expect(lines[0]).toMatch(/^\s*1\talpha/);
|
||||
expect(lines[1]).toMatch(/^\s*2\tbeta/);
|
||||
expect(lines[2]).toMatch(/^\s*3\tgamma/);
|
||||
});
|
||||
|
||||
it('should respect offset and limit parameters', async () => {
|
||||
const content = 'line1\nline2\nline3\nline4\nline5';
|
||||
setupTextFile(content);
|
||||
|
||||
const result = await readTool.config.execute(
|
||||
{ file_path: '/test/project/file.ts', offset: 1, limit: 2 },
|
||||
baseContext,
|
||||
) as string;
|
||||
|
||||
// offset=1 means start from line index 1 (line2), limit=2 means two lines
|
||||
expect(result).toContain('line2');
|
||||
expect(result).toContain('line3');
|
||||
expect(result).not.toContain('line1');
|
||||
expect(result).not.toContain('line4');
|
||||
});
|
||||
|
||||
it('should show truncation notice when there are more lines beyond limit', async () => {
|
||||
const lines = Array.from({ length: 10 }, (_, i) => `line${i + 1}`);
|
||||
setupTextFile(lines.join('\n'));
|
||||
|
||||
const result = await readTool.config.execute(
|
||||
{ file_path: '/test/project/file.ts', offset: 0, limit: 3 },
|
||||
baseContext,
|
||||
) as string;
|
||||
|
||||
expect(result).toContain('Showing lines 1-3 of 10 total lines');
|
||||
});
|
||||
|
||||
it('should return error when file not found', async () => {
|
||||
const enoentError = Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
|
||||
vi.mocked(fs.openSync).mockImplementation(() => { throw enoentError; });
|
||||
|
||||
const result = await readTool.config.execute(
|
||||
{ file_path: '/test/project/missing.ts' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Error: File not found');
|
||||
});
|
||||
|
||||
it('should return error when path is a directory (EISDIR)', async () => {
|
||||
const eisdirError = Object.assign(new Error('EISDIR'), { code: 'EISDIR' });
|
||||
vi.mocked(fs.openSync).mockImplementation(() => { throw eisdirError; });
|
||||
|
||||
const result = await readTool.config.execute(
|
||||
{ file_path: '/test/project/somedir' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('is a directory');
|
||||
});
|
||||
|
||||
it('should return empty file message when file has no content', async () => {
|
||||
setupTextFile('');
|
||||
|
||||
const result = await readTool.config.execute(
|
||||
{ file_path: '/test/project/empty.ts' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('File exists but is empty');
|
||||
});
|
||||
|
||||
it('should return image file as base64 data URI', async () => {
|
||||
const fakeFd = 42;
|
||||
const imageBuffer = Buffer.from('fake-png-data');
|
||||
vi.mocked(fs.openSync).mockReturnValue(fakeFd as unknown as number);
|
||||
vi.mocked(fs.fstatSync).mockReturnValue({
|
||||
isDirectory: () => false,
|
||||
size: imageBuffer.length,
|
||||
} as unknown as fs.Stats);
|
||||
// readFileSync returns Buffer for image files
|
||||
vi.mocked(fs.readFileSync).mockReturnValue(imageBuffer);
|
||||
vi.mocked(fs.closeSync).mockImplementation(() => undefined);
|
||||
|
||||
const result = await readTool.config.execute(
|
||||
{ file_path: '/test/project/image.png' },
|
||||
baseContext,
|
||||
) as string;
|
||||
|
||||
expect(result).toContain('[Image file:');
|
||||
expect(result).toContain('data:image/png;base64,');
|
||||
});
|
||||
|
||||
it('should return PDF info without pages parameter', async () => {
|
||||
const fakeFd = 42;
|
||||
vi.mocked(fs.openSync).mockReturnValue(fakeFd as unknown as number);
|
||||
vi.mocked(fs.fstatSync).mockReturnValue({
|
||||
isDirectory: () => false,
|
||||
size: 102400,
|
||||
} as unknown as fs.Stats);
|
||||
vi.mocked(fs.closeSync).mockImplementation(() => undefined);
|
||||
|
||||
const result = await readTool.config.execute(
|
||||
{ file_path: '/test/project/doc.pdf' },
|
||||
baseContext,
|
||||
) as string;
|
||||
|
||||
expect(result).toContain('[PDF file:');
|
||||
expect(result).toContain('pages');
|
||||
});
|
||||
|
||||
it('should call assertPathContained for path security', async () => {
|
||||
setupTextFile('content');
|
||||
|
||||
await readTool.config.execute(
|
||||
{ file_path: '/test/project/file.ts' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(assertPathContained).toHaveBeenCalledWith('/test/project/file.ts', '/test/project');
|
||||
});
|
||||
|
||||
it('should throw when path is outside project boundary', async () => {
|
||||
vi.mocked(assertPathContained).mockImplementation(() => {
|
||||
throw new Error("Path '/etc/passwd' is outside the project directory");
|
||||
});
|
||||
|
||||
await expect(
|
||||
readTool.config.execute(
|
||||
{ file_path: '/etc/passwd' },
|
||||
baseContext,
|
||||
),
|
||||
).rejects.toThrow('outside the project directory');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,164 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
import { writeTool } from '../write';
|
||||
import type { ToolContext } from '../../types';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mocks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
vi.mock('node:fs');
|
||||
vi.mock('../../../security/path-containment', () => ({
|
||||
assertPathContained: vi.fn((_filePath: string, _projectDir: string) => ({
|
||||
contained: true,
|
||||
resolvedPath: _filePath,
|
||||
})),
|
||||
}));
|
||||
|
||||
import * as fs from 'node:fs';
|
||||
import { assertPathContained } from '../../../security/path-containment';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const baseContext: ToolContext = {
|
||||
cwd: '/test/project',
|
||||
projectDir: '/test/project',
|
||||
specDir: '/test/specs/001',
|
||||
securityProfile: {
|
||||
baseCommands: new Set(),
|
||||
stackCommands: new Set(),
|
||||
scriptCommands: new Set(),
|
||||
customCommands: new Set(),
|
||||
customScripts: { shellScripts: [] },
|
||||
getAllAllowedCommands: () => new Set(),
|
||||
},
|
||||
} as unknown as ToolContext;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('Write Tool', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(assertPathContained).mockImplementation((_filePath: string, _projectDir: string) => ({
|
||||
contained: true,
|
||||
resolvedPath: _filePath,
|
||||
}));
|
||||
// Parent directory exists by default
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||
vi.mocked(fs.writeFileSync).mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
it('should have correct metadata', () => {
|
||||
expect(writeTool.metadata.name).toBe('Write');
|
||||
expect(writeTool.metadata.permission).toBe('requires_approval');
|
||||
});
|
||||
|
||||
it('should write a new file and report line count', async () => {
|
||||
const content = 'line one\nline two\nline three';
|
||||
|
||||
const result = await writeTool.config.execute(
|
||||
{ file_path: '/test/project/new-file.ts', content },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Successfully wrote 3 lines');
|
||||
expect(result).toContain('/test/project/new-file.ts');
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(
|
||||
'/test/project/new-file.ts',
|
||||
content,
|
||||
'utf-8',
|
||||
);
|
||||
});
|
||||
|
||||
it('should overwrite an existing file', async () => {
|
||||
const content = 'updated content';
|
||||
|
||||
const result = await writeTool.config.execute(
|
||||
{ file_path: '/test/project/existing.ts', content },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Successfully wrote');
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(
|
||||
'/test/project/existing.ts',
|
||||
content,
|
||||
'utf-8',
|
||||
);
|
||||
});
|
||||
|
||||
it('should create parent directories when they do not exist', async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
||||
vi.mocked(fs.mkdirSync).mockImplementation(() => undefined);
|
||||
|
||||
await writeTool.config.execute(
|
||||
{ file_path: '/test/project/new/deep/file.ts', content: 'content' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(fs.mkdirSync).toHaveBeenCalledWith(
|
||||
'/test/project/new/deep',
|
||||
{ recursive: true },
|
||||
);
|
||||
expect(fs.writeFileSync).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not create directories when parent already exists', async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||
|
||||
await writeTool.config.execute(
|
||||
{ file_path: '/test/project/file.ts', content: 'content' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(fs.mkdirSync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should count lines correctly for single-line content', async () => {
|
||||
const result = await writeTool.config.execute(
|
||||
{ file_path: '/test/project/file.ts', content: 'single line' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(result).toContain('Successfully wrote 1 lines');
|
||||
});
|
||||
|
||||
it('should count CRLF lines correctly', async () => {
|
||||
const content = 'line1\r\nline2\r\nline3';
|
||||
|
||||
const result = await writeTool.config.execute(
|
||||
{ file_path: '/test/project/file.ts', content },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
// split(/\r?\n/) yields 3 parts
|
||||
expect(result).toContain('Successfully wrote 3 lines');
|
||||
});
|
||||
|
||||
it('should call assertPathContained for path security', async () => {
|
||||
await writeTool.config.execute(
|
||||
{ file_path: '/test/project/file.ts', content: 'hello' },
|
||||
baseContext,
|
||||
);
|
||||
|
||||
expect(assertPathContained).toHaveBeenCalledWith('/test/project/file.ts', '/test/project');
|
||||
});
|
||||
|
||||
it('should throw when path is outside project boundary', async () => {
|
||||
vi.mocked(assertPathContained).mockImplementation(() => {
|
||||
throw new Error("Path '/etc/hosts' is outside the project directory");
|
||||
});
|
||||
|
||||
await expect(
|
||||
writeTool.config.execute(
|
||||
{ file_path: '/etc/hosts', content: 'malicious' },
|
||||
baseContext,
|
||||
),
|
||||
).rejects.toThrow('outside the project directory');
|
||||
|
||||
expect(fs.writeFileSync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -149,7 +149,7 @@ export function generateDebugReport(): string {
|
||||
const recentErrors = getRecentErrors(10);
|
||||
|
||||
const lines = [
|
||||
'=== Auto Claude Debug Report ===',
|
||||
'=== Aperant Debug Report ===',
|
||||
`Generated: ${new Date().toISOString()}`,
|
||||
'',
|
||||
'--- System Information ---',
|
||||
|
||||
@@ -30,7 +30,7 @@ import { isMacOS } from './platform';
|
||||
|
||||
// GitHub repo info for API calls
|
||||
const GITHUB_OWNER = 'AndyMik90';
|
||||
const GITHUB_REPO = 'Auto-Claude';
|
||||
const GITHUB_REPO = 'Aperant';
|
||||
|
||||
// Debug mode - DEBUG_UPDATER=true or development mode
|
||||
const DEBUG_UPDATER = process.env.DEBUG_UPDATER === 'true' || process.env.NODE_ENV === 'development';
|
||||
@@ -488,7 +488,7 @@ async function fetchLatestStableRelease(): Promise<AppUpdateInfo | null> {
|
||||
});
|
||||
|
||||
request.setHeader('Accept', 'application/vnd.github.v3+json');
|
||||
request.setHeader('User-Agent', `Auto-Claude/${getCurrentVersion()}`);
|
||||
request.setHeader('User-Agent', `Aperant/${getCurrentVersion()}`);
|
||||
|
||||
let data = '';
|
||||
|
||||
|
||||
@@ -499,7 +499,6 @@ export class ChangelogService extends EventEmitter {
|
||||
this.debug('Error in AI version suggestion, falling back to patch bump', error);
|
||||
// Fallback to patch bump if AI fails
|
||||
// currentVersion is guaranteed non-empty: the try block returns early if falsy or invalid
|
||||
// biome-ignore lint/style/noNonNullAssertion: guarded by early returns in try block
|
||||
const [major, minor, patch] = currentVersion!.split('.').map(Number);
|
||||
return {
|
||||
version: `${major}.${minor}.${patch + 1}`,
|
||||
|
||||
@@ -3,11 +3,24 @@
|
||||
// require-in-the-middle hooks. Sentry's hooks expect require.cache to exist,
|
||||
// which is only available in CommonJS. Without this, node-pty native module
|
||||
// loading fails with "ReferenceError: require is not defined".
|
||||
import { createRequire } from 'module';
|
||||
import Module, { createRequire } from 'module';
|
||||
const require = createRequire(import.meta.url);
|
||||
// Make require globally available for Sentry's require-in-the-middle hooks
|
||||
globalThis.require = require;
|
||||
|
||||
// In packaged Electron apps, native modules (e.g. @libsql/client) are placed in
|
||||
// Resources/node_modules/ via extraResources. Add that path to CJS resolution so
|
||||
// globalThis.require() can find them at runtime.
|
||||
if (process.resourcesPath) {
|
||||
const nativeModulesPath = require('path').join(process.resourcesPath, 'node_modules');
|
||||
// Module.globalPaths is an undocumented but stable Node.js internal used for
|
||||
// CJS module resolution. It's not in @types/node, hence the cast.
|
||||
const globalPaths = (Module as unknown as { globalPaths: string[] }).globalPaths;
|
||||
if (!globalPaths.includes(nativeModulesPath)) {
|
||||
globalPaths.push(nativeModulesPath);
|
||||
}
|
||||
}
|
||||
|
||||
// Load .env file FIRST before any other imports that might use process.env
|
||||
import { config } from 'dotenv';
|
||||
import { resolve, dirname } from 'path';
|
||||
@@ -37,7 +50,7 @@ for (const envPath of possibleEnvPaths) {
|
||||
|
||||
import { app, BrowserWindow, shell, nativeImage, session, screen, Menu, MenuItem } from 'electron';
|
||||
import { join } from 'path';
|
||||
import { accessSync, readFileSync, writeFileSync, rmSync } from 'fs';
|
||||
import { accessSync, readFileSync, writeFileSync, rmSync, cpSync } from 'fs';
|
||||
import { electronApp, optimizer, is } from '@electron-toolkit/utils';
|
||||
import { setupIpcHandlers } from './ipc-setup';
|
||||
import { AgentManager } from './agent';
|
||||
@@ -58,6 +71,26 @@ import { isMacOS, isWindows } from './platform';
|
||||
import { ptyDaemonClient } from './terminal/pty-daemon-client';
|
||||
import type { AppSettings, AuthFailureInfo } from '../shared/types';
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Migrate userData from old app name (auto-claude-ui → aperant)
|
||||
// Must run before any code accesses app.getPath('userData')
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
{
|
||||
const newUserData = app.getPath('userData');
|
||||
const oldUserData = join(dirname(newUserData), 'auto-claude-ui');
|
||||
if (existsSync(oldUserData) && !existsSync(join(newUserData, '.migrated'))) {
|
||||
try {
|
||||
// Copy all files from old location to new (don't move — keeps old as backup)
|
||||
cpSync(oldUserData, newUserData, { recursive: true, force: false, errorOnExist: false });
|
||||
// Mark as migrated so we don't repeat
|
||||
writeFileSync(join(newUserData, '.migrated'), new Date().toISOString());
|
||||
console.warn('[main] Migrated userData from auto-claude-ui to aperant');
|
||||
} catch (err) {
|
||||
console.warn('[main] userData migration failed (non-fatal):', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Window sizing constants
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
@@ -352,6 +385,16 @@ function createWindow(): void {
|
||||
agentManager?.killAll?.()?.catch((err: unknown) => {
|
||||
console.warn('[main] Error killing agents on window close:', err);
|
||||
});
|
||||
// Clear GitLab MR polling intervals for all projects
|
||||
import('./ipc-handlers/gitlab/mr-review-handlers').then(({ clearPollingForProject }) => {
|
||||
const { projectStore } = require('./project-store');
|
||||
const projects = projectStore.getProjects();
|
||||
for (const project of projects) {
|
||||
clearPollingForProject(project.id);
|
||||
}
|
||||
}).catch((err: unknown) => {
|
||||
console.warn('[main] Error clearing GitLab polling on window close:', err);
|
||||
});
|
||||
mainWindow = null;
|
||||
});
|
||||
}
|
||||
@@ -373,7 +416,7 @@ if (isWindows()) {
|
||||
// Initialize the application
|
||||
app.whenReady().then(() => {
|
||||
// Set app user model id for Windows
|
||||
electronApp.setAppUserModelId('com.autoclaude.ui');
|
||||
electronApp.setAppUserModelId('com.aperant.app');
|
||||
|
||||
// Clear cache on Windows to prevent permission errors from stale cache
|
||||
if (isWindows()) {
|
||||
|
||||
@@ -129,7 +129,7 @@ async function githubGraphQL<T>(
|
||||
headers: {
|
||||
"Authorization": `Bearer ${safeToken}`,
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": "Auto-Claude-UI",
|
||||
"User-Agent": "Aperant",
|
||||
},
|
||||
body: JSON.stringify({ query, variables }),
|
||||
});
|
||||
@@ -2275,7 +2275,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
|
||||
|
||||
if (options?.forceApprove) {
|
||||
// Auto-approve format: clean approval message with optional suggestions
|
||||
body = `## ✅ Auto Claude Review - APPROVED\n\n`;
|
||||
body = `## ✅ Aperant Review - APPROVED\n\n`;
|
||||
body += `**Status:** Ready to Merge\n\n`;
|
||||
body += `**Summary:** ${result.summary}\n\n`;
|
||||
|
||||
@@ -2298,10 +2298,10 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
|
||||
}
|
||||
|
||||
body += `---\n*This automated review found no blocking issues. The PR can be safely merged.*\n\n`;
|
||||
body += `*Generated by Auto Claude*`;
|
||||
body += `*Generated by Aperant*`;
|
||||
} else {
|
||||
// Standard review format
|
||||
body = `## 🤖 Auto Claude PR Review\n\n${result.summary}\n\n`;
|
||||
body = `## 🤖 Aperant PR Review\n\n${result.summary}\n\n`;
|
||||
|
||||
if (findings.length > 0) {
|
||||
// Show selected count vs total if filtered
|
||||
@@ -2326,7 +2326,7 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
|
||||
body += `*No findings selected for this review.*\n\n`;
|
||||
}
|
||||
|
||||
body += `---\n*This review was generated by Auto Claude.*`;
|
||||
body += `---\n*This review was generated by Aperant.*`;
|
||||
}
|
||||
|
||||
// Determine review status based on selected findings (or force approve)
|
||||
|
||||
@@ -267,7 +267,7 @@ export async function githubFetch(
|
||||
headers: {
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Authorization': `Bearer ${safeToken}`,
|
||||
'User-Agent': 'Auto-Claude-UI',
|
||||
'User-Agent': 'Aperant',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
@@ -298,7 +298,7 @@ export async function githubFetchWithETag(
|
||||
const headers: Record<string, string> = {
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'User-Agent': 'Auto-Claude-UI'
|
||||
'User-Agent': 'Aperant'
|
||||
};
|
||||
|
||||
// Add If-None-Match header if we have a cached ETag
|
||||
|
||||
@@ -108,7 +108,7 @@ function formatReviewBody(result: MRReviewResult, selectedFindingIds?: string[])
|
||||
? result.findings.filter(f => selectedSet.has(f.id))
|
||||
: result.findings;
|
||||
|
||||
let body = `## Auto Claude MR Review\n\n${result.summary}\n\n`;
|
||||
let body = `## Aperant MR Review\n\n${result.summary}\n\n`;
|
||||
|
||||
if (findings.length > 0) {
|
||||
const countText = selectedSet
|
||||
@@ -130,7 +130,7 @@ function formatReviewBody(result: MRReviewResult, selectedFindingIds?: string[])
|
||||
body += `*No findings selected for this review.*\n\n`;
|
||||
}
|
||||
|
||||
body += `---\n*This review was generated by Auto Claude.*`;
|
||||
body += `---\n*This review was generated by Aperant.*`;
|
||||
|
||||
return body;
|
||||
}
|
||||
@@ -335,7 +335,7 @@ describe('GitLab MR Review Handlers', () => {
|
||||
it('should format review header', () => {
|
||||
const body = formatReviewBody(baseResult);
|
||||
|
||||
expect(body).toContain('## Auto Claude MR Review');
|
||||
expect(body).toContain('## Aperant MR Review');
|
||||
expect(body).toContain('Found 2 issues that need attention');
|
||||
});
|
||||
|
||||
@@ -410,7 +410,7 @@ describe('GitLab MR Review Handlers', () => {
|
||||
const body = formatReviewBody(baseResult);
|
||||
|
||||
expect(body).toContain('---');
|
||||
expect(body).toContain('*This review was generated by Auto Claude.*');
|
||||
expect(body).toContain('*This review was generated by Aperant.*');
|
||||
});
|
||||
|
||||
it('should format finding descriptions', () => {
|
||||
|
||||
@@ -304,9 +304,10 @@ function sendProgress(
|
||||
function sendError(
|
||||
mainWindow: BrowserWindow,
|
||||
projectId: string,
|
||||
issueIid: number,
|
||||
error: string
|
||||
): void {
|
||||
mainWindow.webContents.send(IPC_CHANNELS.GITLAB_AUTOFIX_ERROR, projectId, error);
|
||||
mainWindow.webContents.send(IPC_CHANNELS.GITLAB_AUTOFIX_ERROR, projectId, issueIid, error);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -498,7 +499,7 @@ export function registerAutoFixHandlers(
|
||||
});
|
||||
} catch (error) {
|
||||
debugLog('Auto-fix failed', { issueIid, error: error instanceof Error ? error.message : error });
|
||||
sendError(mainWindow, projectId, error instanceof Error ? error.message : 'Failed to start auto-fix');
|
||||
sendError(mainWindow, projectId, issueIid, error instanceof Error ? error.message : 'Failed to start auto-fix');
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
@@ -10,15 +10,14 @@
|
||||
* 6. Approve MR
|
||||
*/
|
||||
|
||||
import { ipcMain } from 'electron';
|
||||
import type { BrowserWindow } from 'electron';
|
||||
import { ipcMain, BrowserWindow } from 'electron';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { IPC_CHANNELS, MODEL_ID_MAP, DEFAULT_FEATURE_MODELS, DEFAULT_FEATURE_THINKING } from '../../../shared/constants';
|
||||
import { getGitLabConfig, gitlabFetch, encodeProjectPath } from './utils';
|
||||
import { readSettingsFile } from '../../settings-utils';
|
||||
import type { Project, AppSettings } from '../../../shared/types';
|
||||
import type { Project, AppSettings, IPCResult, GitLabMergeRequest } from '../../../shared/types';
|
||||
import type {
|
||||
MRReviewResult,
|
||||
MRReviewProgress,
|
||||
@@ -26,6 +25,7 @@ import type {
|
||||
} from './types';
|
||||
import { createContextLogger } from '../github/utils/logger';
|
||||
import { withProjectOrNull } from '../github/utils/project-middleware';
|
||||
import { projectStore } from '../../project-store';
|
||||
import { createIPCCommunicators } from '../github/utils/ipc-communicator';
|
||||
import {
|
||||
MRReviewEngine,
|
||||
@@ -47,6 +47,27 @@ const REBASE_POLL_INTERVAL_MS = 1000;
|
||||
// Default rebase timeout (60 seconds). Can be overridden via GITLAB_REBASE_TIMEOUT_MS env var
|
||||
const REBASE_TIMEOUT_MS = parseInt(process.env.GITLAB_REBASE_TIMEOUT_MS || '60000', 10);
|
||||
|
||||
/**
|
||||
* Registry of status polling intervals for MR updates
|
||||
* Key format: `${projectId}:${mrIid}`
|
||||
*/
|
||||
const statusPollingIntervals = new Map<string, NodeJS.Timeout>();
|
||||
const pollingInProgress = new Set<string>();
|
||||
|
||||
/**
|
||||
* Clear all polling intervals for a specific project
|
||||
* Called when a project is deleted to prevent memory leaks
|
||||
*/
|
||||
function clearPollingForProject(projectId: string): void {
|
||||
const keysToDelete = Array.from(statusPollingIntervals.keys())
|
||||
.filter(key => key.startsWith(`${projectId}:`));
|
||||
keysToDelete.forEach(key => {
|
||||
clearInterval(statusPollingIntervals.get(key)!);
|
||||
statusPollingIntervals.delete(key);
|
||||
pollingInProgress.delete(key);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the registry key for an MR review
|
||||
*/
|
||||
@@ -520,7 +541,7 @@ export function registerMRReviewHandlers(
|
||||
debugLog('Posting findings', { total: result.findings.length, selected: findings.length });
|
||||
|
||||
// Build note body
|
||||
let body = `## Auto Claude MR Review\n\n${result.summary}\n\n`;
|
||||
let body = `## Aperant MR Review\n\n${result.summary}\n\n`;
|
||||
|
||||
if (findings.length > 0) {
|
||||
const countText = selectedSet
|
||||
@@ -542,7 +563,7 @@ export function registerMRReviewHandlers(
|
||||
body += `*No findings selected for this review.*\n\n`;
|
||||
}
|
||||
|
||||
body += `---\n*This review was generated by Auto Claude.*`;
|
||||
body += `---\n*This review was generated by Aperant.*`;
|
||||
|
||||
const encodedProject = encodeProjectPath(config.project);
|
||||
|
||||
@@ -790,6 +811,7 @@ export function registerMRReviewHandlers(
|
||||
}
|
||||
|
||||
const reviewedCommitSha = review.reviewedCommitSha || (review as any).reviewed_commit_sha;
|
||||
const reviewedAt = review.reviewedAt || (review as any).reviewed_at;
|
||||
if (!reviewedCommitSha) {
|
||||
debugLog('No reviewedCommitSha in review', { mrIid });
|
||||
return { hasNewCommits: false };
|
||||
@@ -813,27 +835,40 @@ export function registerMRReviewHandlers(
|
||||
if (reviewedCommitSha === currentHeadSha) {
|
||||
return {
|
||||
hasNewCommits: false,
|
||||
hasCommitsAfterPosting: false,
|
||||
currentSha: currentHeadSha,
|
||||
reviewedSha: reviewedCommitSha,
|
||||
};
|
||||
}
|
||||
|
||||
// Get commits to count new ones
|
||||
// Get commits to count new ones and check for commits after review posting
|
||||
const commits = await gitlabFetch(
|
||||
config.token,
|
||||
config.instanceUrl,
|
||||
`/projects/${encodedProject}/merge_requests/${mrIid}/commits`
|
||||
) as Array<{ id: string }>;
|
||||
) as Array<{ id: string; created_at: string }>;
|
||||
|
||||
// Find how many commits are after the reviewed one
|
||||
let newCommitCount = 0;
|
||||
// Check if any commits were added AFTER the review was posted
|
||||
let hasCommitsAfterPosting = false;
|
||||
const reviewTime = reviewedAt ? new Date(reviewedAt).getTime() : 0;
|
||||
|
||||
for (const commit of commits) {
|
||||
if (commit.id === reviewedCommitSha) break;
|
||||
newCommitCount++;
|
||||
// If commit was created after the review was posted, it's a true follow-up commit
|
||||
if (reviewTime > 0 && commit.created_at) {
|
||||
const commitTime = new Date(commit.created_at).getTime();
|
||||
if (commitTime > reviewTime) {
|
||||
hasCommitsAfterPosting = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
hasNewCommits: true,
|
||||
hasCommitsAfterPosting,
|
||||
currentSha: currentHeadSha,
|
||||
reviewedSha: reviewedCommitSha,
|
||||
newCommitCount: newCommitCount || 1,
|
||||
@@ -973,4 +1008,431 @@ export function registerMRReviewHandlers(
|
||||
);
|
||||
|
||||
debugLog('MR review handlers registered');
|
||||
|
||||
// ============================================
|
||||
// NEW: Additional handlers for feature parity
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Delete a posted MR review (note)
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITLAB_MR_DELETE_REVIEW,
|
||||
async (_event, projectId: string, mrIid: number, noteId: number): Promise<IPCResult<{ deleted: boolean }>> => {
|
||||
debugLog('deleteReview handler called', { projectId, mrIid, noteId });
|
||||
|
||||
const result = await withProjectOrNull(projectId, async (project) => {
|
||||
const config = await getGitLabConfig(project);
|
||||
if (!config) return { success: false, error: 'GitLab not configured' };
|
||||
|
||||
const { token, instanceUrl } = config;
|
||||
const encodedProject = encodeProjectPath(config.project);
|
||||
|
||||
try {
|
||||
await gitlabFetch(
|
||||
token,
|
||||
instanceUrl,
|
||||
`/projects/${encodedProject}/merge_requests/${mrIid}/notes/${noteId}`,
|
||||
{ method: 'DELETE' }
|
||||
);
|
||||
|
||||
// Clear the posted findings cache since the review note was deleted
|
||||
const reviewPath = path.join(getGitLabDir(project), 'mr', `review_${mrIid}.json`);
|
||||
const tempPath = `${reviewPath}.tmp.${randomUUID()}`;
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(reviewPath, 'utf-8'));
|
||||
data.has_posted_findings = false;
|
||||
data.posted_finding_ids = [];
|
||||
// Write to temp file first, then rename atomically
|
||||
fs.writeFileSync(tempPath, JSON.stringify(data, null, 2), 'utf-8');
|
||||
fs.renameSync(tempPath, reviewPath);
|
||||
debugLog('Cleared posted findings cache after note deletion', { mrIid, noteId });
|
||||
} catch (cacheError) {
|
||||
// Clean up temp file if it exists
|
||||
try { fs.unlinkSync(tempPath); } catch { /* ignore cleanup errors */ }
|
||||
debugLog('Failed to clear posted findings cache', { error: cacheError instanceof Error ? cacheError.message : cacheError });
|
||||
// Continue anyway - the deletion succeeded even if cache update failed
|
||||
}
|
||||
|
||||
return { success: true, data: { deleted: true } };
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
debugLog('Failed to delete review note', { mrIid, noteId, error: errorMessage });
|
||||
return { success: false, error: errorMessage };
|
||||
}
|
||||
});
|
||||
|
||||
if (result === null) {
|
||||
return { success: false, error: 'Project not found' };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Check MR merge readiness
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITLAB_MR_CHECK_MERGE_READINESS,
|
||||
async (_event, projectId: string, mrIid: number): Promise<IPCResult<{
|
||||
canMerge: boolean;
|
||||
hasConflicts: boolean;
|
||||
needsDiscussion: boolean;
|
||||
pipelineStatus?: string;
|
||||
}>> => {
|
||||
debugLog('checkMergeReadiness handler called', { projectId, mrIid });
|
||||
|
||||
const result = await withProjectOrNull(projectId, async (project) => {
|
||||
const config = await getGitLabConfig(project);
|
||||
if (!config) return { success: false, error: 'GitLab not configured' };
|
||||
|
||||
const { token, instanceUrl } = config;
|
||||
const encodedProject = encodeProjectPath(config.project);
|
||||
|
||||
try {
|
||||
const mrData = await gitlabFetch(
|
||||
token,
|
||||
instanceUrl,
|
||||
`/projects/${encodedProject}/merge_requests/${mrIid}`
|
||||
) as {
|
||||
merge_status?: string;
|
||||
detailed_merge_status?: string;
|
||||
has_conflicts?: boolean;
|
||||
blocking_discussions_resolved?: boolean;
|
||||
pipeline?: { status?: string };
|
||||
};
|
||||
|
||||
const detailedStatus = mrData.detailed_merge_status || mrData.merge_status || 'cannot_be_merged';
|
||||
const canMerge = detailedStatus === 'can_be_merged' || detailedStatus === 'mergeable';
|
||||
const hasConflicts = mrData.has_conflicts || false;
|
||||
const needsDiscussion = detailedStatus === 'discussions_not_resolved' || mrData.blocking_discussions_resolved === false;
|
||||
const pipelineStatus = mrData.pipeline?.status;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
canMerge,
|
||||
hasConflicts,
|
||||
needsDiscussion,
|
||||
pipelineStatus
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
debugLog('Failed to check merge readiness', { mrIid, error: errorMessage });
|
||||
return { success: false, error: errorMessage };
|
||||
}
|
||||
});
|
||||
|
||||
if (result === null) {
|
||||
return { success: false, error: 'Project not found' };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Get AI review logs for an MR
|
||||
* TODO: Return structured PRLogs type instead of string[] to match MRLogs component expectations
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITLAB_MR_GET_LOGS,
|
||||
async (_event, projectId: string, mrIid: number): Promise<IPCResult<string[]>> => {
|
||||
debugLog('getLogs handler called', { projectId, mrIid });
|
||||
|
||||
const result = await withProjectOrNull(projectId, async (project) => {
|
||||
const reviewPath = path.join(getGitLabDir(project), 'mr', `review_${mrIid}.json`);
|
||||
const logsPath = path.join(getGitLabDir(project), 'mr', `logs_${mrIid}.json`);
|
||||
|
||||
try {
|
||||
let logs: string[] = [];
|
||||
|
||||
if (fs.existsSync(logsPath)) {
|
||||
const logsData = JSON.parse(fs.readFileSync(logsPath, 'utf-8'));
|
||||
logs = logsData.entries || [];
|
||||
} else if (fs.existsSync(reviewPath)) {
|
||||
// If no separate log file, return basic info from review
|
||||
const reviewData = JSON.parse(fs.readFileSync(reviewPath, 'utf-8'));
|
||||
logs = [`Review completed at ${reviewData.reviewed_at || 'unknown'}`];
|
||||
}
|
||||
|
||||
return { success: true, data: logs };
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
debugLog('Failed to get logs', { mrIid, error: errorMessage });
|
||||
return { success: false, error: errorMessage };
|
||||
}
|
||||
});
|
||||
|
||||
if (result === null) {
|
||||
return { success: false, error: 'Project not found' };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Start status polling for MR updates
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITLAB_MR_STATUS_POLL_START,
|
||||
async (event, projectId: string, mrIid: number, intervalMs: number = 5000): Promise<IPCResult<{ polling: boolean }>> => {
|
||||
debugLog('statusPollStart handler called', { projectId, mrIid, intervalMs });
|
||||
|
||||
const result = await withProjectOrNull(projectId, async (_project) => {
|
||||
const pollKey = `${projectId}:${mrIid}`;
|
||||
|
||||
// Clear existing interval if any
|
||||
if (statusPollingIntervals.has(pollKey)) {
|
||||
clearInterval(statusPollingIntervals.get(pollKey)!);
|
||||
}
|
||||
|
||||
// Get the window that initiated this polling - more robust than getAllWindows()[0]
|
||||
const callingWindow = BrowserWindow.fromWebContents(event.sender);
|
||||
if (!callingWindow) {
|
||||
return { success: false, error: 'Could not identify calling window' };
|
||||
}
|
||||
|
||||
// Clamp interval to safe range (1s to 60s)
|
||||
const safeIntervalMs = Number.isFinite(intervalMs)
|
||||
? Math.min(60_000, Math.max(1_000, intervalMs))
|
||||
: 5_000;
|
||||
|
||||
// Start new polling interval
|
||||
const interval = setInterval(async () => {
|
||||
const pollKey = `${projectId}:${mrIid}`;
|
||||
|
||||
// Stop polling if window is destroyed
|
||||
if (!callingWindow || callingWindow.isDestroyed()) {
|
||||
clearInterval(interval);
|
||||
statusPollingIntervals.delete(pollKey);
|
||||
pollingInProgress.delete(pollKey);
|
||||
return;
|
||||
}
|
||||
|
||||
// Prevent concurrent polls
|
||||
if (pollingInProgress.has(pollKey)) {
|
||||
return;
|
||||
}
|
||||
|
||||
pollingInProgress.add(pollKey);
|
||||
|
||||
try {
|
||||
// Fetch current project to avoid stale config from closure
|
||||
const currentProject = projectStore.getProject(projectId);
|
||||
if (!currentProject) {
|
||||
debugLog('Project not found during poll - stopping poller', { projectId });
|
||||
clearInterval(interval);
|
||||
statusPollingIntervals.delete(pollKey);
|
||||
pollingInProgress.delete(pollKey);
|
||||
return;
|
||||
}
|
||||
|
||||
// Emit status update to renderer
|
||||
if (callingWindow && !callingWindow.isDestroyed()) {
|
||||
|
||||
const config = await getGitLabConfig(currentProject);
|
||||
if (!config) return;
|
||||
|
||||
const { token, instanceUrl } = config;
|
||||
const encodedProject = encodeProjectPath(config.project);
|
||||
|
||||
const mrData = await gitlabFetch(
|
||||
token,
|
||||
instanceUrl,
|
||||
`/projects/${encodedProject}/merge_requests/${mrIid}`
|
||||
) as {
|
||||
state?: string;
|
||||
merge_status?: string;
|
||||
updated_at?: string;
|
||||
};
|
||||
|
||||
callingWindow.webContents.send(IPC_CHANNELS.GITLAB_MR_STATUS_UPDATE, {
|
||||
projectId,
|
||||
mrIid,
|
||||
state: mrData.state,
|
||||
mergeStatus: mrData.merge_status,
|
||||
updatedAt: mrData.updated_at
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
debugLog('Status poll error', { mrIid, error });
|
||||
} finally {
|
||||
pollingInProgress.delete(pollKey);
|
||||
}
|
||||
}, safeIntervalMs);
|
||||
|
||||
statusPollingIntervals.set(pollKey, interval);
|
||||
|
||||
return { success: true, data: { polling: true } };
|
||||
});
|
||||
|
||||
if (result === null) {
|
||||
return { success: false, error: 'Project not found' };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
);
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITLAB_MR_STATUS_POLL_STOP,
|
||||
async (_event, projectId: string, mrIid: number): Promise<IPCResult<{ stopped: boolean }>> => {
|
||||
debugLog('statusPollStop handler called', { projectId, mrIid });
|
||||
|
||||
const pollKey = `${projectId}:${mrIid}`;
|
||||
|
||||
if (statusPollingIntervals.has(pollKey)) {
|
||||
clearInterval(statusPollingIntervals.get(pollKey)!);
|
||||
statusPollingIntervals.delete(pollKey);
|
||||
pollingInProgress.delete(pollKey);
|
||||
return { success: true, data: { stopped: true } };
|
||||
}
|
||||
|
||||
return { success: true, data: { stopped: false } };
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Get MR review memories
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITLAB_MR_MEMORY_GET,
|
||||
async (_event, projectId: string, mrIid: number): Promise<IPCResult<unknown[]>> => {
|
||||
debugLog('memoryGet handler called', { projectId, mrIid });
|
||||
|
||||
// TODO: Implement memory retrieval from Graphiti memory system
|
||||
return {
|
||||
success: false,
|
||||
error: 'Memory feature not yet implemented',
|
||||
code: 'NOT_IMPLEMENTED'
|
||||
} as IPCResult<unknown[]>;
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Search MR review memories
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITLAB_MR_MEMORY_SEARCH,
|
||||
async (_event, projectId: string, query: string): Promise<IPCResult<unknown[]>> => {
|
||||
debugLog('memorySearch handler called', { projectId, query });
|
||||
|
||||
// TODO: Implement memory search from Graphiti memory system
|
||||
return {
|
||||
success: false,
|
||||
error: 'Memory feature not yet implemented',
|
||||
code: 'NOT_IMPLEMENTED'
|
||||
} as IPCResult<unknown[]>;
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Auto-fix issues in MR
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITLAB_MR_FIX,
|
||||
async (_event, projectId: string, mrIid: number, findings: string[]): Promise<IPCResult<{ fixed: number }>> => {
|
||||
debugLog('autoFix handler called', { projectId, mrIid, findingsCount: findings.length });
|
||||
|
||||
// TODO: Implement auto-fix functionality
|
||||
// This will integrate with the existing autofix handlers
|
||||
return {
|
||||
success: false,
|
||||
error: 'Auto-fix not yet implemented - use GITLAB_AUTOFIX_START instead'
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Batch load reviews for multiple MRs
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITLAB_MR_GET_REVIEWS_BATCH,
|
||||
async (_event, projectId: string, mrIids: number[]): Promise<IPCResult<Record<number, MRReviewResult | null>>> => {
|
||||
debugLog('getReviewsBatch handler called', { projectId, mrIids });
|
||||
|
||||
const result = await withProjectOrNull(projectId, async (project) => {
|
||||
const results: Record<number, MRReviewResult | null> = {};
|
||||
|
||||
for (const mrIid of mrIids) {
|
||||
const review = getReviewResult(project, mrIid);
|
||||
results[mrIid] = review;
|
||||
}
|
||||
|
||||
return { success: true, data: results };
|
||||
});
|
||||
|
||||
if (result === null) {
|
||||
return { success: false, error: 'Project not found' };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Load more MRs (pagination)
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.GITLAB_MR_LIST_MORE,
|
||||
async (
|
||||
_event,
|
||||
projectId: string,
|
||||
state?: 'opened' | 'closed' | 'merged' | 'all',
|
||||
page: number = 2
|
||||
): Promise<IPCResult<{ mrs: GitLabMergeRequest[]; hasMore: boolean }>> => {
|
||||
debugLog('listMore handler called', { projectId, state, page });
|
||||
|
||||
const result = await withProjectOrNull(projectId, async (project) => {
|
||||
const config = await getGitLabConfig(project);
|
||||
if (!config) {
|
||||
return { success: false, error: 'GitLab not configured' };
|
||||
}
|
||||
|
||||
const { token, instanceUrl } = config;
|
||||
const encodedProject = encodeProjectPath(config.project);
|
||||
|
||||
try {
|
||||
const stateParam = state === 'all' ? undefined : state;
|
||||
// Over-fetch by 1 to reliably determine if there are more pages
|
||||
const queryParams = new URLSearchParams({
|
||||
per_page: '21',
|
||||
page: String(page),
|
||||
...(stateParam && { state: stateParam })
|
||||
});
|
||||
|
||||
const mrs = await gitlabFetch(
|
||||
token,
|
||||
instanceUrl,
|
||||
`/projects/${encodedProject}/merge_requests?${queryParams.toString()}`
|
||||
) as GitLabMergeRequest[];
|
||||
|
||||
// If we got 21 items, there's definitely more. Otherwise we're at the end.
|
||||
const hasMore = mrs.length > 20;
|
||||
// Only return the requested page size (20 items)
|
||||
const returnMrs = hasMore ? mrs.slice(0, 20) : mrs;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
mrs: returnMrs,
|
||||
hasMore
|
||||
}
|
||||
};
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
debugLog('Failed to load more MRs', { projectId, page, error: errorMessage });
|
||||
return { success: false, error: errorMessage };
|
||||
}
|
||||
});
|
||||
|
||||
if (result === null) {
|
||||
return { success: false, error: 'Project not found' };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
);
|
||||
|
||||
debugLog('Additional MR handlers registered');
|
||||
}
|
||||
|
||||
export { clearPollingForProject };
|
||||
|
||||
@@ -133,7 +133,7 @@ export function registerInsightsHandlers(getMainWindow: () => BrowserWindow | nu
|
||||
}
|
||||
|
||||
if (!project.autoBuildPath) {
|
||||
return { success: false, error: "Auto Claude not initialized for this project" };
|
||||
return { success: false, error: "Aperant not initialized for this project" };
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -12,8 +12,12 @@ import { getOllamaExecutablePaths, getOllamaInstallCommand as getPlatformOllamaI
|
||||
import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import type {
|
||||
IPCResult,
|
||||
InfrastructureStatus,
|
||||
MemoryValidationResult,
|
||||
} from '../../shared/types';
|
||||
import { openTerminalWithCommand } from './claude-code-handlers';
|
||||
import { getEmbeddingProvider } from './context/memory-service-factory';
|
||||
const { join } = path;
|
||||
|
||||
/**
|
||||
* Ollama Service Status
|
||||
@@ -547,6 +551,154 @@ export function registerMemoryHandlers(): void {
|
||||
}
|
||||
);
|
||||
|
||||
// ============================================
|
||||
// Memory Infrastructure Handlers (LadybugDB - libSQL)
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Get memory infrastructure status.
|
||||
* Checks if the local libSQL database is available and returns status.
|
||||
*
|
||||
* @async
|
||||
* @param {string} [dbPath] - Optional custom database path (for testing)
|
||||
* @returns {Promise<IPCResult<InfrastructureStatus>>} Status with memory database info
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.INFRASTRUCTURE_GET_STATUS,
|
||||
async (_, dbPath?: string): Promise<IPCResult<InfrastructureStatus>> => {
|
||||
try {
|
||||
const { getMemoryClient } = await import('../ai/memory/db');
|
||||
const { existsSync } = await import('fs');
|
||||
|
||||
// Get default memory.db path from userData
|
||||
const { app } = await import('electron');
|
||||
const defaultPath = join(app.getPath('userData'), 'memory.db');
|
||||
const checkPath = dbPath || defaultPath;
|
||||
|
||||
// Check if database file exists
|
||||
const dbExists = existsSync(checkPath);
|
||||
|
||||
// Try to initialize the client to verify it's functional
|
||||
await getMemoryClient();
|
||||
const embeddingProvider = getEmbeddingProvider();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
memory: {
|
||||
kuzuInstalled: false, // Kuzu is no longer used, libSQL only
|
||||
databasePath: checkPath,
|
||||
databaseExists: dbExists,
|
||||
databases: dbExists ? ['memory'] : [],
|
||||
error: dbExists ? undefined : 'Database file not found',
|
||||
},
|
||||
ready: dbExists && embeddingProvider !== null,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to get infrastructure status',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* List available memory databases.
|
||||
* Returns a list of database names available in the system.
|
||||
*
|
||||
* @async
|
||||
* @param {string} [dbPath] - Optional custom database path (for testing)
|
||||
* @returns {Promise<IPCResult<string[]>>} Array of database names
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.INFRASTRUCTURE_LIST_DATABASES,
|
||||
async (_, dbPath?: string): Promise<IPCResult<string[]>> => {
|
||||
try {
|
||||
const { existsSync } = await import('fs');
|
||||
const { app } = await import('electron');
|
||||
const { join } = await import('path');
|
||||
|
||||
const defaultPath = join(app.getPath('userData'), 'memory.db');
|
||||
const checkPath = dbPath || defaultPath;
|
||||
|
||||
const databases: string[] = [];
|
||||
if (existsSync(checkPath)) {
|
||||
databases.push('memory');
|
||||
}
|
||||
|
||||
return { success: true, data: databases };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to list databases',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Test memory database connection.
|
||||
* Verifies that a specific database can be connected to and queried.
|
||||
*
|
||||
* @async
|
||||
* @param {string} [dbPath] - Optional custom database path
|
||||
* @param {string} [database] - Database name to test (default: 'memory')
|
||||
* @returns {Promise<IPCResult<MemoryValidationResult>>} Connection test result
|
||||
*/
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.INFRASTRUCTURE_TEST_CONNECTION,
|
||||
async (_, dbPath?: string, database?: string): Promise<IPCResult<MemoryValidationResult>> => {
|
||||
try {
|
||||
const { getMemoryClient } = await import('../ai/memory/db');
|
||||
const { existsSync } = await import('fs');
|
||||
const { app } = await import('electron');
|
||||
const { join } = await import('path');
|
||||
|
||||
const defaultPath = join(app.getPath('userData'), 'memory.db');
|
||||
const checkPath = dbPath || defaultPath;
|
||||
const dbName = database || 'memory';
|
||||
|
||||
// Check if database file exists
|
||||
if (!existsSync(checkPath)) {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
success: false,
|
||||
message: `Database '${dbName}' not found at ${checkPath}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Try to connect and run a simple query
|
||||
const client = await getMemoryClient();
|
||||
await client.execute('SELECT 1');
|
||||
|
||||
const embeddingProvider = getEmbeddingProvider();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
success: true,
|
||||
message: `Successfully connected to ${dbName} database`,
|
||||
details: {
|
||||
provider: embeddingProvider || 'none',
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: true, // Return success with failure details in data
|
||||
data: {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Connection test failed',
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// ============================================
|
||||
// Memory System (libSQL-backed) Handlers
|
||||
// ============================================
|
||||
|
||||
@@ -266,6 +266,9 @@ export function registerProjectHandlers(
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.PROJECT_REMOVE,
|
||||
async (_, projectId: string): Promise<IPCResult> => {
|
||||
// Clear GitLab MR polling for this project to prevent memory leaks
|
||||
const { clearPollingForProject } = await import('./gitlab/mr-review-handlers');
|
||||
clearPollingForProject(projectId);
|
||||
const success = projectStore.removeProject(projectId);
|
||||
return { success };
|
||||
}
|
||||
|
||||
@@ -264,7 +264,7 @@ const detectAutoBuildSourcePath = (): string | null => {
|
||||
}
|
||||
}
|
||||
|
||||
console.warn('[detectAutoBuildSourcePath] Could not auto-detect Auto Claude prompts path. Please configure manually in settings.');
|
||||
console.warn('[detectAutoBuildSourcePath] Could not auto-detect Aperant prompts path. Please configure manually in settings.');
|
||||
console.warn('[detectAutoBuildSourcePath] Set DEBUG=1 environment variable for detailed path checking.');
|
||||
return null;
|
||||
};
|
||||
@@ -933,6 +933,20 @@ export function registerSettingsHandlers(
|
||||
try {
|
||||
const settings = readSettingsFile() ?? {};
|
||||
const accounts: ProviderAccount[] = (settings.providerAccounts as ProviderAccount[] | undefined) ?? [];
|
||||
|
||||
// Prevent duplicate: same email + provider already registered
|
||||
if (account.email) {
|
||||
const duplicate = accounts.find(
|
||||
(a) => a.provider === account.provider && a.email?.toLowerCase() === account.email!.toLowerCase()
|
||||
);
|
||||
if (duplicate) {
|
||||
return {
|
||||
success: false,
|
||||
error: `DUPLICATE_EMAIL:${duplicate.name}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const newAccount: ProviderAccount = {
|
||||
...account,
|
||||
|
||||
@@ -177,7 +177,7 @@ export function registerTaskExecutionHandlers(
|
||||
mainWindow.webContents.send(
|
||||
IPC_CHANNELS.TASK_ERROR,
|
||||
taskId,
|
||||
'Git repository required. Please run "git init" in your project directory. Auto Claude uses git worktrees for isolated builds.'
|
||||
'Git repository required. Please run "git init" in your project directory. Aperant uses git worktrees for isolated builds.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { debugLog, } from '../../shared/utils/debug-logger';
|
||||
import { migrateSession } from '../claude-profile/session-utils';
|
||||
import { createProfileDirectory } from '../claude-profile/profile-utils';
|
||||
import { isValidConfigDir } from '../utils/config-path-validator';
|
||||
import { sessionPersistence } from '../terminal/session-persistence';
|
||||
|
||||
|
||||
/**
|
||||
@@ -115,6 +116,22 @@ export function registerTerminalHandlers(
|
||||
}
|
||||
);
|
||||
|
||||
// Save terminal buffer (serialized xterm.js content)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.TERMINAL_SAVE_BUFFER,
|
||||
async (_, terminalId: string, serializedBuffer: string): Promise<IPCResult> => {
|
||||
try {
|
||||
sessionPersistence.saveBuffer(terminalId, serializedBuffer);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to save terminal buffer',
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Claude profile management (multi-account support)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.CLAUDE_PROFILES_GET,
|
||||
|
||||
@@ -205,14 +205,14 @@ function ensureGitignoreEntries(projectPath: string, entries: string[]): void {
|
||||
appendContent += '\n';
|
||||
}
|
||||
|
||||
appendContent += '\n# Auto Claude data directory\n';
|
||||
appendContent += '\n# Aperant data directory\n';
|
||||
for (const entry of entriesToAdd) {
|
||||
appendContent += entry + '\n';
|
||||
}
|
||||
|
||||
appendFileSync(gitignorePath, appendContent);
|
||||
} else {
|
||||
writeFileSync(gitignorePath, '# Auto Claude data directory\n' + entriesToAdd.join('\n') + '\n', 'utf-8');
|
||||
writeFileSync(gitignorePath, '# Aperant data directory\n' + entriesToAdd.join('\n') + '\n', 'utf-8');
|
||||
}
|
||||
|
||||
debug('Added entries to .gitignore', { entries: entriesToAdd });
|
||||
@@ -288,13 +288,13 @@ export function initializeProject(projectPath: string): InitializationResult {
|
||||
};
|
||||
}
|
||||
|
||||
// Check git status - Auto Claude requires git for worktree-based builds
|
||||
// Check git status - Aperant requires git for worktree-based builds
|
||||
const gitStatus = checkGitStatus(projectPath);
|
||||
if (!gitStatus.isGitRepo || !gitStatus.hasCommits) {
|
||||
debug('Git check failed', { gitStatus });
|
||||
return {
|
||||
success: false,
|
||||
error: gitStatus.error || 'Git repository required. Auto Claude uses git worktrees for isolated builds.'
|
||||
error: gitStatus.error || 'Git repository required. Aperant uses git worktrees for isolated builds.'
|
||||
};
|
||||
}
|
||||
|
||||
@@ -375,7 +375,7 @@ export function ensureDataDirectories(projectPath: string): InitializationResult
|
||||
*
|
||||
* IMPORTANT: Only .auto-claude/ is considered a valid "installed" auto-claude.
|
||||
* The auto-claude/ folder (if it exists) is the SOURCE CODE being developed,
|
||||
* not an installation. This allows Auto Claude to be used to develop itself.
|
||||
* not an installation. This allows Aperant to be used to develop itself.
|
||||
*/
|
||||
export function getAutoBuildPath(projectPath: string): string | null {
|
||||
const dotAutoBuildPath = path.join(projectPath, '.auto-claude');
|
||||
|
||||
@@ -27,8 +27,7 @@ import type {
|
||||
TerminalProcess,
|
||||
WindowGetter,
|
||||
RateLimitEvent,
|
||||
OAuthTokenEvent,
|
||||
OnboardingCompleteEvent
|
||||
OAuthTokenEvent
|
||||
} from './types';
|
||||
|
||||
// ============================================================================
|
||||
@@ -564,17 +563,17 @@ export function handleOAuthToken(
|
||||
|
||||
console.warn('[ClaudeIntegration] Profile credentials verified via Keychain (not caching token):', profileId);
|
||||
|
||||
// Set flag to watch for Claude's ready state (onboarding complete)
|
||||
terminal.awaitingOnboardingComplete = true;
|
||||
// Mark onboarding complete so future `claude` invocations skip the wizard.
|
||||
// `claude auth login` creates .claude.json but doesn't set this flag.
|
||||
if (profile.configDir) {
|
||||
ensureOnboardingComplete(profile.configDir);
|
||||
}
|
||||
|
||||
// needsOnboarding: true tells the UI to show "complete setup" message
|
||||
// instead of "success" - user should finish Claude's onboarding before closing
|
||||
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
|
||||
terminalId: terminal.id,
|
||||
profileId,
|
||||
email: emailFromOutput || keychainCreds.email || profile?.email,
|
||||
success: true,
|
||||
needsOnboarding: true,
|
||||
detectedAt: new Date().toISOString()
|
||||
} as OAuthTokenEvent);
|
||||
} else {
|
||||
@@ -585,17 +584,16 @@ export function handleOAuthToken(
|
||||
if (hasCredentials) {
|
||||
console.warn('[ClaudeIntegration] Profile credentials verified (no Keychain token):', profileId);
|
||||
|
||||
// Set flag to watch for Claude's ready state (onboarding complete)
|
||||
terminal.awaitingOnboardingComplete = true;
|
||||
// Mark onboarding complete so future `claude` invocations skip the wizard
|
||||
if (profile.configDir) {
|
||||
ensureOnboardingComplete(profile.configDir);
|
||||
}
|
||||
|
||||
// needsOnboarding: true tells the UI to show "complete setup" message
|
||||
// instead of "success" - user should finish Claude's onboarding before closing
|
||||
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_OAUTH_TOKEN, {
|
||||
terminalId: terminal.id,
|
||||
profileId,
|
||||
email: emailFromOutput || profile?.email,
|
||||
success: true,
|
||||
needsOnboarding: true,
|
||||
detectedAt: new Date().toISOString()
|
||||
} as OAuthTokenEvent);
|
||||
} else {
|
||||
@@ -718,130 +716,19 @@ export function handleOAuthToken(
|
||||
|
||||
/**
|
||||
* Handle onboarding complete detection
|
||||
* Called when terminal output indicates Claude Code is ready after login/onboarding
|
||||
* Called when terminal output indicates Claude Code is ready after login/onboarding.
|
||||
*
|
||||
* This detects the Claude Code welcome screen that appears after successful login,
|
||||
* which includes patterns like "Welcome back", "Claude Code v2.x", or subscription
|
||||
* tier info like "Claude Max". When detected, it notifies the frontend to auto-close
|
||||
* the auth terminal.
|
||||
* Note: This is now a no-op. The onboarding flag is set proactively via
|
||||
* ensureOnboardingComplete() in handleOAuthToken() and executeProfileCommand(),
|
||||
* so awaitingOnboardingComplete is never set and this path is never reached.
|
||||
* Kept as a stub to satisfy the terminal-event-handler callback interface.
|
||||
*/
|
||||
export function handleOnboardingComplete(
|
||||
terminal: TerminalProcess,
|
||||
data: string,
|
||||
getWindow: WindowGetter
|
||||
_terminal: TerminalProcess,
|
||||
_data: string,
|
||||
_getWindow: WindowGetter
|
||||
): void {
|
||||
// Only check if we're waiting for onboarding to complete
|
||||
if (!terminal.awaitingOnboardingComplete) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if output shows Claude Code welcome screen (onboarding complete indicators)
|
||||
if (!OutputParser.isOnboardingCompleteOutput(data)) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.warn('[ClaudeIntegration] Onboarding complete detected for terminal:', terminal.id);
|
||||
|
||||
// Clear the flag
|
||||
terminal.awaitingOnboardingComplete = false;
|
||||
|
||||
// Extract profile ID from terminal ID pattern (claude-login-{profileId}-*)
|
||||
const profileId = extractProfileIdFromAuthTerminalId(terminal.id) || undefined;
|
||||
|
||||
// Try to extract email from the welcome screen (e.g., "user@example.com's Organization")
|
||||
// Note: extractEmail automatically strips ANSI escape codes internally
|
||||
let email = OutputParser.extractEmail(data);
|
||||
if (!email) {
|
||||
email = OutputParser.extractEmail(terminal.outputBuffer);
|
||||
}
|
||||
|
||||
// Fallback: If terminal extraction failed or might be corrupt, read directly from Claude's config file
|
||||
// This is the authoritative source and doesn't suffer from ANSI escape code issues
|
||||
const profileManager = getClaudeProfileManager();
|
||||
const profile = profileId ? profileManager.getProfile(profileId) : null;
|
||||
|
||||
if (!email && profile?.configDir) {
|
||||
const configEmail = getEmailFromConfigDir(profile.configDir);
|
||||
if (configEmail) {
|
||||
console.warn('[ClaudeIntegration] Email not found in terminal output, using config file:', maskEmail(configEmail));
|
||||
email = configEmail;
|
||||
}
|
||||
}
|
||||
|
||||
// Validate email looks correct (basic sanity check)
|
||||
// If terminal extraction gave us a truncated email but config file has the correct one, prefer config
|
||||
if (email && profile?.configDir) {
|
||||
const configEmail = getEmailFromConfigDir(profile.configDir);
|
||||
if (configEmail && configEmail !== email) {
|
||||
// Config file email is different - it's more authoritative
|
||||
console.warn('[ClaudeIntegration] Terminal email differs from config file, using config file:', {
|
||||
terminalEmail: maskEmail(email),
|
||||
configEmail: maskEmail(configEmail)
|
||||
});
|
||||
email = configEmail;
|
||||
}
|
||||
}
|
||||
|
||||
console.warn('[ClaudeIntegration] Email extraction attempt:', {
|
||||
profileId,
|
||||
foundEmail: maskEmail(email),
|
||||
dataLength: data.length,
|
||||
bufferLength: terminal.outputBuffer.length
|
||||
});
|
||||
|
||||
// Update profile with email and subscription metadata if found and profile exists
|
||||
// Always update - the newly extracted email from re-authentication should overwrite any stale/truncated email
|
||||
if (profileId && email && profile) {
|
||||
const previousEmail = profile.email;
|
||||
profile.email = email;
|
||||
// Also update subscription metadata from Keychain credentials
|
||||
updateProfileSubscriptionMetadata(profile, profile.configDir);
|
||||
profileManager.saveProfile(profile);
|
||||
if (previousEmail !== email) {
|
||||
console.warn('[ClaudeIntegration] Updated profile email from welcome screen:', profileId, maskEmail(email), '(was:', maskEmail(previousEmail), ')');
|
||||
}
|
||||
}
|
||||
|
||||
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_ONBOARDING_COMPLETE, {
|
||||
terminalId: terminal.id,
|
||||
profileId,
|
||||
detectedAt: new Date().toISOString()
|
||||
} as OnboardingCompleteEvent);
|
||||
|
||||
// Trigger immediate usage fetch after successful re-authentication
|
||||
// This gives the user immediate feedback that their account is working
|
||||
if (profileId) {
|
||||
try {
|
||||
const usageMonitor = getUsageMonitor();
|
||||
if (usageMonitor) {
|
||||
// Clear any auth failure status for this profile since they just re-authenticated
|
||||
usageMonitor.clearAuthFailedProfile(profileId);
|
||||
|
||||
console.warn('[ClaudeIntegration] Triggering immediate usage fetch after re-authentication:', profileId);
|
||||
|
||||
// Switch to this profile if it's not already active, then fetch usage
|
||||
const profileManager = getClaudeProfileManager();
|
||||
|
||||
// Also clear the migration flag if this profile was migrated to an isolated directory
|
||||
// This prevents the auth failure modal from showing again on next startup
|
||||
if (profileManager.isProfileMigrated(profileId)) {
|
||||
profileManager.clearMigratedProfile(profileId);
|
||||
console.warn('[ClaudeIntegration] Cleared migration flag for re-authenticated profile:', profileId);
|
||||
}
|
||||
const activeProfile = profileManager.getActiveProfile();
|
||||
if (activeProfile?.id !== profileId) {
|
||||
profileManager.setActiveProfile(profileId);
|
||||
}
|
||||
|
||||
// Small delay to allow profile switch to settle, then trigger usage fetch
|
||||
setTimeout(() => {
|
||||
usageMonitor.checkNow();
|
||||
}, 500);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[ClaudeIntegration] Failed to trigger post-auth usage fetch:', error);
|
||||
}
|
||||
}
|
||||
// No-op — onboarding is handled proactively in handleOAuthToken()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -893,6 +780,54 @@ export function handleClaudeExit(
|
||||
safeSendToRenderer(getWindow, IPC_CHANNELS.TERMINAL_CLAUDE_EXIT, terminal.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure hasCompletedOnboarding is set in profile's .claude.json.
|
||||
* When CLAUDE_CONFIG_DIR is set, Claude Code reads .claude.json from that directory.
|
||||
* Without this flag, it triggers the onboarding wizard even for authenticated profiles.
|
||||
*/
|
||||
export function ensureOnboardingComplete(configDir: string): void {
|
||||
try {
|
||||
const expandedDir = path.resolve(
|
||||
configDir.startsWith('~') ? configDir.replace(/^~/, os.homedir()) : configDir
|
||||
);
|
||||
const claudeJsonPath = path.join(expandedDir, '.claude.json');
|
||||
|
||||
// Read directly instead of existsSync + readFileSync to avoid TOCTOU race (CodeQL js/file-system-race)
|
||||
let content: string;
|
||||
try {
|
||||
content = fs.readFileSync(claudeJsonPath, 'utf-8');
|
||||
} catch (readErr) {
|
||||
if ((readErr as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return; // No .claude.json yet — Claude Code will create it during auth
|
||||
}
|
||||
throw readErr;
|
||||
}
|
||||
|
||||
const config = JSON.parse(content);
|
||||
|
||||
if (typeof config !== 'object' || config === null || Array.isArray(config)) {
|
||||
return; // Not a valid config object
|
||||
}
|
||||
|
||||
if (config.hasCompletedOnboarding === true) {
|
||||
return; // Already set
|
||||
}
|
||||
|
||||
config.hasCompletedOnboarding = true;
|
||||
const updatedContent = JSON.stringify(config, null, 2);
|
||||
|
||||
// Write atomically via temp file + rename to avoid partial writes and satisfy CodeQL js/insecure-temporary-file.
|
||||
// crypto.randomUUID() ensures no collisions; mode 0o600 restricts to owner-only.
|
||||
const tmpPath = `${claudeJsonPath}.${crypto.randomUUID()}.tmp`;
|
||||
fs.writeFileSync(tmpPath, updatedContent, { encoding: 'utf-8', mode: 0o600 });
|
||||
fs.renameSync(tmpPath, claudeJsonPath);
|
||||
debugLog(`[ClaudeIntegration] Set hasCompletedOnboarding in ${claudeJsonPath}`);
|
||||
} catch (error) {
|
||||
// Non-fatal — worst case the user sees onboarding once
|
||||
debugError('[ClaudeIntegration] Failed to set hasCompletedOnboarding:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared command execution logic for profile-based invocation
|
||||
* Returns true if command was executed via configDir or temp-file method
|
||||
@@ -938,6 +873,9 @@ function executeProfileCommand(options: ExecuteProfileCommandOptions): boolean {
|
||||
// read full Keychain credentials including subscriptionType ("max") and rateLimitTier.
|
||||
// Using CLAUDE_CODE_OAUTH_TOKEN alone lacks tier info, causing "Claude API" display.
|
||||
if (activeProfile.configDir) {
|
||||
// Ensure Claude Code skips onboarding for authenticated profiles
|
||||
ensureOnboardingComplete(activeProfile.configDir);
|
||||
|
||||
const command = buildClaudeShellCommand(
|
||||
cwdCommand,
|
||||
pathPrefix,
|
||||
@@ -1016,6 +954,9 @@ async function executeProfileCommandAsync(options: ExecuteProfileCommandOptions)
|
||||
// read full Keychain credentials including subscriptionType ("max") and rateLimitTier.
|
||||
// Using CLAUDE_CODE_OAUTH_TOKEN alone lacks tier info, causing "Claude API" display.
|
||||
if (activeProfile.configDir) {
|
||||
// Ensure Claude Code skips onboarding for authenticated profiles
|
||||
ensureOnboardingComplete(activeProfile.configDir);
|
||||
|
||||
const command = buildClaudeShellCommand(
|
||||
cwdCommand,
|
||||
pathPrefix,
|
||||
|
||||
@@ -14,8 +14,23 @@ import type {
|
||||
TerminalRecoveryInfo,
|
||||
} from '../../shared/types/terminal-session';
|
||||
|
||||
const SESSIONS_FILE = path.join(app.getPath('userData'), 'terminal-sessions.json');
|
||||
const BUFFERS_DIR = path.join(app.getPath('userData'), 'terminal-buffers');
|
||||
// Helper to get app data path safely (works in tests where app might not be fully mocked)
|
||||
function getUserDataPath(): string {
|
||||
try {
|
||||
if (app && typeof app.getPath === 'function') {
|
||||
return app.getPath('userData');
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors in test environment
|
||||
}
|
||||
// Fallback for test environment - use home directory instead of /tmp for security
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
return path.join(os.homedir(), '.aperant-test-data');
|
||||
}
|
||||
|
||||
const SESSIONS_FILE = path.join(getUserDataPath(), 'terminal-sessions.json');
|
||||
const BUFFERS_DIR = path.join(getUserDataPath(), 'terminal-buffers');
|
||||
|
||||
// Session age limit: 7 days
|
||||
const MAX_SESSION_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
@@ -307,19 +322,31 @@ class SessionPersistence {
|
||||
// Singleton instance
|
||||
export const sessionPersistence = new SessionPersistence();
|
||||
|
||||
// Hook into app lifecycle
|
||||
app.on('before-quit', () => {
|
||||
console.warn('[SessionPersistence] App quitting, saving sessions...');
|
||||
sessionPersistence.saveNow();
|
||||
});
|
||||
// Hook into app lifecycle (only if running in real Electron environment, not tests)
|
||||
try {
|
||||
if (app && typeof app.on === 'function') {
|
||||
app.on('before-quit', () => {
|
||||
console.warn('[SessionPersistence] App quitting, saving sessions...');
|
||||
sessionPersistence.saveNow();
|
||||
});
|
||||
|
||||
app.on('will-quit', () => {
|
||||
sessionPersistence.saveNow();
|
||||
});
|
||||
app.on('will-quit', () => {
|
||||
sessionPersistence.saveNow();
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors in test environment
|
||||
}
|
||||
|
||||
// Cleanup orphaned buffers on startup (after initial load)
|
||||
app.whenReady().then(() => {
|
||||
setTimeout(() => {
|
||||
sessionPersistence.cleanupOrphanedBuffers();
|
||||
}, 5000); // Wait 5 seconds after app ready
|
||||
});
|
||||
try {
|
||||
if (app && typeof app.whenReady === 'function') {
|
||||
app.whenReady().then(() => {
|
||||
setTimeout(() => {
|
||||
sessionPersistence.cleanupOrphanedBuffers();
|
||||
}, 5000); // Wait 5 seconds after app ready
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Ignore errors in test environment
|
||||
}
|
||||
|
||||
@@ -26,8 +26,6 @@ export interface TerminalProcess {
|
||||
dangerouslySkipPermissions?: boolean;
|
||||
/** Shell type for Windows (affects command chaining syntax) */
|
||||
shellType?: WindowsShellType;
|
||||
/** Whether this terminal is waiting for Claude onboarding to complete (login flow) */
|
||||
awaitingOnboardingComplete?: boolean;
|
||||
/** Whether PTY has emitted exit; used to avoid writes/resizes on dead PTYs */
|
||||
hasExited?: boolean;
|
||||
}
|
||||
@@ -55,19 +53,8 @@ export interface OAuthTokenEvent {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
detectedAt: string;
|
||||
/** If true, user should complete onboarding in terminal before closing */
|
||||
needsOnboarding?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Onboarding complete event data
|
||||
* Sent when Claude Code shows its ready state after login/onboarding
|
||||
*/
|
||||
export interface OnboardingCompleteEvent {
|
||||
terminalId: string;
|
||||
profileId?: string;
|
||||
detectedAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Session capture result
|
||||
|
||||
@@ -178,10 +178,28 @@ export interface GitHubAPI {
|
||||
/** AI-powered version suggestion based on commits since last release */
|
||||
suggestReleaseVersion: (projectId: string) => Promise<IPCResult<VersionSuggestion>>;
|
||||
|
||||
// Release operations (changelog-based)
|
||||
getReleaseableVersions: (projectId: string) => Promise<IPCResult<unknown>>;
|
||||
runReleasePreflightCheck: (projectId: string, version: string) => Promise<IPCResult<unknown>>;
|
||||
createRelease: (options: {
|
||||
projectId: string;
|
||||
version: string;
|
||||
body: string;
|
||||
draft?: boolean;
|
||||
prerelease?: boolean;
|
||||
}) => Promise<IPCResult<unknown>>;
|
||||
|
||||
// OAuth operations (gh CLI)
|
||||
checkGitHubCli: () => Promise<IPCResult<{ installed: boolean; version?: string }>>;
|
||||
checkGitHubAuth: () => Promise<IPCResult<{ authenticated: boolean; username?: string }>>;
|
||||
startGitHubAuth: () => Promise<IPCResult<{ success: boolean; message?: string }>>;
|
||||
startGitHubAuth: () => Promise<IPCResult<{
|
||||
success: boolean;
|
||||
message?: string;
|
||||
deviceCode?: string;
|
||||
authUrl?: string;
|
||||
browserOpened?: boolean;
|
||||
fallbackUrl?: string;
|
||||
}>>;
|
||||
getGitHubToken: () => Promise<IPCResult<{ token: string }>>;
|
||||
getGitHubUser: () => Promise<IPCResult<{ username: string; name?: string }>>;
|
||||
listGitHubUserRepos: () => Promise<IPCResult<{ repos: Array<{ fullName: string; description: string | null; isPrivate: boolean }> }>>;
|
||||
@@ -571,6 +589,22 @@ export const createGitHubAPI = (): GitHubAPI => ({
|
||||
suggestReleaseVersion: (projectId: string): Promise<IPCResult<VersionSuggestion>> =>
|
||||
invokeIpc(IPC_CHANNELS.RELEASE_SUGGEST_VERSION, projectId),
|
||||
|
||||
// Release operations (changelog-based)
|
||||
getReleaseableVersions: (projectId: string): Promise<IPCResult<unknown>> =>
|
||||
invokeIpc(IPC_CHANNELS.RELEASE_GET_VERSIONS, projectId),
|
||||
|
||||
runReleasePreflightCheck: (projectId: string, version: string): Promise<IPCResult<unknown>> =>
|
||||
invokeIpc(IPC_CHANNELS.RELEASE_PREFLIGHT, projectId, version),
|
||||
|
||||
createRelease: (options: {
|
||||
projectId: string;
|
||||
version: string;
|
||||
body: string;
|
||||
draft?: boolean;
|
||||
prerelease?: boolean;
|
||||
}): Promise<IPCResult<unknown>> =>
|
||||
invokeIpc(IPC_CHANNELS.RELEASE_CREATE, options),
|
||||
|
||||
// OAuth operations (gh CLI)
|
||||
checkGitHubCli: (): Promise<IPCResult<{ installed: boolean; version?: string }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_CHECK_CLI),
|
||||
@@ -578,7 +612,14 @@ export const createGitHubAPI = (): GitHubAPI => ({
|
||||
checkGitHubAuth: (): Promise<IPCResult<{ authenticated: boolean; username?: string }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_CHECK_AUTH),
|
||||
|
||||
startGitHubAuth: (): Promise<IPCResult<{ success: boolean; message?: string }>> =>
|
||||
startGitHubAuth: (): Promise<IPCResult<{
|
||||
success: boolean;
|
||||
message?: string;
|
||||
deviceCode?: string;
|
||||
authUrl?: string;
|
||||
browserOpened?: boolean;
|
||||
fallbackUrl?: string;
|
||||
}>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITHUB_START_AUTH),
|
||||
|
||||
getGitHubToken: (): Promise<IPCResult<{ token: string }>> =>
|
||||
|
||||
@@ -18,6 +18,7 @@ import type {
|
||||
GitLabAnalyzePreviewResult,
|
||||
GitLabTriageConfig,
|
||||
GitLabTriageResult,
|
||||
GitLabMRStatusUpdate,
|
||||
GitLabGroup,
|
||||
IPCResult
|
||||
} from '../../../shared/types';
|
||||
@@ -79,6 +80,30 @@ export interface GitLabAPI {
|
||||
cancelGitLabMRReview: (projectId: string, mrIid: number) => Promise<boolean>;
|
||||
checkGitLabMRNewCommits: (projectId: string, mrIid: number) => Promise<GitLabNewCommitsCheck>;
|
||||
|
||||
// NEW: Additional MR operations for feature parity
|
||||
listMoreGitLabMRs: (
|
||||
projectId: string,
|
||||
state?: 'opened' | 'closed' | 'merged' | 'all',
|
||||
page?: number
|
||||
) => Promise<IPCResult<{ mrs: GitLabMergeRequest[]; hasMore: boolean }>>;
|
||||
getGitLabMRReviewsBatch: (projectId: string, mrIids: number[]) => Promise<IPCResult<Record<number, GitLabMRReviewResult | null>>>;
|
||||
deleteGitLabMRReview: (projectId: string, mrIid: number, noteId: number) => Promise<IPCResult<{ deleted: boolean }>>;
|
||||
fixGitLabMR: (projectId: string, mrIid: number, findings: string[]) => Promise<IPCResult<{ fixed: number }>>;
|
||||
startGitLabMRStatusPoll: (projectId: string, mrIid: number, intervalMs?: number) => Promise<IPCResult<{ polling: boolean }>>;
|
||||
stopGitLabMRStatusPoll: (projectId: string, mrIid: number) => Promise<IPCResult<{ stopped: boolean }>>;
|
||||
getGitLabMRLogs: (projectId: string, mrIid: number) => Promise<IPCResult<string[]>>;
|
||||
getGitLabMRMemory: (projectId: string, mrIid: number) => Promise<IPCResult<unknown[]>>;
|
||||
searchGitLabMRMemory: (projectId: string, query: string) => Promise<IPCResult<unknown[]>>;
|
||||
checkGitLabMRMergeReadiness: (
|
||||
projectId: string,
|
||||
mrIid: number
|
||||
) => Promise<IPCResult<{
|
||||
canMerge: boolean;
|
||||
hasConflicts: boolean;
|
||||
needsDiscussion: boolean;
|
||||
pipelineStatus?: string;
|
||||
}>>;
|
||||
|
||||
// MR Review Event Listeners
|
||||
onGitLabMRReviewProgress: (
|
||||
callback: (projectId: string, progress: GitLabMRReviewProgress) => void
|
||||
@@ -89,6 +114,9 @@ export interface GitLabAPI {
|
||||
onGitLabMRReviewError: (
|
||||
callback: (projectId: string, data: { mrIid: number; error: string }) => void
|
||||
) => IpcListenerCleanup;
|
||||
onGitLabMRStatusUpdate: (
|
||||
callback: (update: GitLabMRStatusUpdate) => void
|
||||
) => IpcListenerCleanup;
|
||||
|
||||
// GitLab Auto-Fix operations
|
||||
getGitLabAutoFixConfig: (projectId: string) => Promise<GitLabAutoFixConfig | null>;
|
||||
@@ -109,7 +137,7 @@ export interface GitLabAPI {
|
||||
callback: (projectId: string, result: GitLabAutoFixQueueItem) => void
|
||||
) => IpcListenerCleanup;
|
||||
onGitLabAutoFixError: (
|
||||
callback: (projectId: string, error: string) => void
|
||||
callback: (projectId: string, issueIid: number, error: string) => void
|
||||
) => IpcListenerCleanup;
|
||||
onGitLabAutoFixAnalyzePreviewProgress: (
|
||||
callback: (projectId: string, progress: { phase: string; progress: number; message: string }) => void
|
||||
@@ -278,6 +306,56 @@ export const createGitLabAPI = (): GitLabAPI => ({
|
||||
checkGitLabMRNewCommits: (projectId: string, mrIid: number): Promise<GitLabNewCommitsCheck> =>
|
||||
invokeIpc(IPC_CHANNELS.GITLAB_MR_CHECK_NEW_COMMITS, projectId, mrIid),
|
||||
|
||||
// NEW: Additional MR operations for feature parity
|
||||
listMoreGitLabMRs: (
|
||||
projectId: string,
|
||||
state?: 'opened' | 'closed' | 'merged' | 'all',
|
||||
page?: number
|
||||
): Promise<IPCResult<{ mrs: GitLabMergeRequest[]; hasMore: boolean }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITLAB_MR_LIST_MORE, projectId, state, page),
|
||||
|
||||
getGitLabMRReviewsBatch: (
|
||||
projectId: string,
|
||||
mrIids: number[]
|
||||
): Promise<IPCResult<Record<number, GitLabMRReviewResult | null>>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITLAB_MR_GET_REVIEWS_BATCH, projectId, mrIids),
|
||||
|
||||
deleteGitLabMRReview: (projectId: string, mrIid: number, noteId: number): Promise<IPCResult<{ deleted: boolean }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITLAB_MR_DELETE_REVIEW, projectId, mrIid, noteId),
|
||||
|
||||
fixGitLabMR: (projectId: string, mrIid: number, findings: string[]): Promise<IPCResult<{ fixed: number }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITLAB_MR_FIX, projectId, mrIid, findings),
|
||||
|
||||
startGitLabMRStatusPoll: (
|
||||
projectId: string,
|
||||
mrIid: number,
|
||||
intervalMs?: number
|
||||
): Promise<IPCResult<{ polling: boolean }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITLAB_MR_STATUS_POLL_START, projectId, mrIid, intervalMs),
|
||||
|
||||
stopGitLabMRStatusPoll: (projectId: string, mrIid: number): Promise<IPCResult<{ stopped: boolean }>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITLAB_MR_STATUS_POLL_STOP, projectId, mrIid),
|
||||
|
||||
getGitLabMRLogs: (projectId: string, mrIid: number): Promise<IPCResult<string[]>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITLAB_MR_GET_LOGS, projectId, mrIid),
|
||||
|
||||
getGitLabMRMemory: (projectId: string, mrIid: number): Promise<IPCResult<unknown[]>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITLAB_MR_MEMORY_GET, projectId, mrIid),
|
||||
|
||||
searchGitLabMRMemory: (projectId: string, query: string): Promise<IPCResult<unknown[]>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITLAB_MR_MEMORY_SEARCH, projectId, query),
|
||||
|
||||
checkGitLabMRMergeReadiness: (
|
||||
projectId: string,
|
||||
mrIid: number
|
||||
): Promise<IPCResult<{
|
||||
canMerge: boolean;
|
||||
hasConflicts: boolean;
|
||||
needsDiscussion: boolean;
|
||||
pipelineStatus?: string;
|
||||
}>> =>
|
||||
invokeIpc(IPC_CHANNELS.GITLAB_MR_CHECK_MERGE_READINESS, projectId, mrIid),
|
||||
|
||||
// MR Review Event Listeners
|
||||
onGitLabMRReviewProgress: (
|
||||
callback: (projectId: string, progress: GitLabMRReviewProgress) => void
|
||||
@@ -294,6 +372,11 @@ export const createGitLabAPI = (): GitLabAPI => ({
|
||||
): IpcListenerCleanup =>
|
||||
createIpcListener(IPC_CHANNELS.GITLAB_MR_REVIEW_ERROR, callback),
|
||||
|
||||
onGitLabMRStatusUpdate: (
|
||||
callback: (update: GitLabMRStatusUpdate) => void
|
||||
): IpcListenerCleanup =>
|
||||
createIpcListener(IPC_CHANNELS.GITLAB_MR_STATUS_UPDATE, callback),
|
||||
|
||||
// GitLab Auto-Fix operations
|
||||
getGitLabAutoFixConfig: (projectId: string): Promise<GitLabAutoFixConfig | null> =>
|
||||
invokeIpc(IPC_CHANNELS.GITLAB_AUTOFIX_GET_CONFIG, projectId),
|
||||
@@ -334,7 +417,7 @@ export const createGitLabAPI = (): GitLabAPI => ({
|
||||
createIpcListener(IPC_CHANNELS.GITLAB_AUTOFIX_COMPLETE, callback),
|
||||
|
||||
onGitLabAutoFixError: (
|
||||
callback: (projectId: string, error: string) => void
|
||||
callback: (projectId: string, issueIid: number, error: string) => void
|
||||
): IpcListenerCleanup =>
|
||||
createIpcListener(IPC_CHANNELS.GITLAB_AUTOFIX_ERROR, callback),
|
||||
|
||||
|
||||
@@ -11,5 +11,6 @@ export * from './insights-api';
|
||||
export * from './changelog-api';
|
||||
export * from './linear-api';
|
||||
export * from './github-api';
|
||||
export * from './gitlab-api';
|
||||
export * from './shell-api';
|
||||
export * from './debug-api';
|
||||
|
||||
@@ -9,7 +9,9 @@ import type {
|
||||
ProjectEnvConfig,
|
||||
GitStatus,
|
||||
KanbanPreferences,
|
||||
GitBranchDetail
|
||||
GitBranchDetail,
|
||||
InfrastructureStatus,
|
||||
MemoryValidationResult
|
||||
} from '../../shared/types';
|
||||
|
||||
// Tab state interface (persisted in main process)
|
||||
@@ -46,6 +48,11 @@ export interface ProjectAPI {
|
||||
searchMemories: (projectId: string, query: string) => Promise<IPCResult<unknown>>;
|
||||
getRecentMemories: (projectId: string, limit?: number) => Promise<IPCResult<unknown>>;
|
||||
|
||||
// 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<MemoryValidationResult>>;
|
||||
|
||||
// Memory Management
|
||||
verifyMemory: (memoryId: string) => Promise<IPCResult<void>>;
|
||||
pinMemory: (memoryId: string, pinned: boolean) => Promise<IPCResult<void>>;
|
||||
@@ -284,5 +291,15 @@ export const createProjectAPI = (): ProjectAPI => ({
|
||||
ipcRenderer.invoke(IPC_CHANNELS.OLLAMA_LIST_EMBEDDING_MODELS, baseUrl),
|
||||
|
||||
pullOllamaModel: (modelName: string, baseUrl?: string) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.OLLAMA_PULL_MODEL, modelName, baseUrl)
|
||||
ipcRenderer.invoke(IPC_CHANNELS.OLLAMA_PULL_MODEL, modelName, baseUrl),
|
||||
|
||||
// Memory Infrastructure operations (LadybugDB - no Docker required)
|
||||
getMemoryInfrastructureStatus: (dbPath?: string) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.INFRASTRUCTURE_GET_STATUS, dbPath),
|
||||
|
||||
listMemoryDatabases: (dbPath?: string) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.INFRASTRUCTURE_LIST_DATABASES, dbPath),
|
||||
|
||||
testMemoryConnection: (dbPath?: string, database?: string) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.INFRASTRUCTURE_TEST_CONNECTION, dbPath, database)
|
||||
});
|
||||
|
||||
@@ -17,6 +17,7 @@ export interface SettingsAPI {
|
||||
python: ToolDetectionResult;
|
||||
git: ToolDetectionResult;
|
||||
gh: ToolDetectionResult;
|
||||
glab: ToolDetectionResult;
|
||||
claude: ToolDetectionResult;
|
||||
}>>;
|
||||
|
||||
@@ -64,6 +65,7 @@ export const createSettingsAPI = (): SettingsAPI => ({
|
||||
python: ToolDetectionResult;
|
||||
git: ToolDetectionResult;
|
||||
gh: ToolDetectionResult;
|
||||
glab: ToolDetectionResult;
|
||||
claude: ToolDetectionResult;
|
||||
}>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.SETTINGS_GET_CLI_TOOLS_INFO),
|
||||
|
||||
@@ -72,6 +72,9 @@ export interface TerminalAPI {
|
||||
removeTerminalWorktree: (projectPath: string, name: string, deleteBranch?: boolean) => Promise<IPCResult>;
|
||||
listOtherWorktrees: (projectPath: string) => Promise<IPCResult<OtherWorktreeInfo[]>>;
|
||||
|
||||
// Terminal Buffer Persistence
|
||||
saveTerminalBuffer: (terminalId: string, serializedBuffer: string) => Promise<IPCResult>;
|
||||
|
||||
// Terminal Event Listeners
|
||||
onTerminalOutput: (callback: (id: string, data: string) => void) => () => void;
|
||||
onTerminalExit: (callback: (id: string, exitCode: number) => void) => () => void;
|
||||
@@ -80,7 +83,7 @@ export interface TerminalAPI {
|
||||
onTerminalClaudeSession: (callback: (id: string, sessionId: string) => void) => () => void;
|
||||
onTerminalRateLimit: (callback: (info: RateLimitInfo) => void) => () => void;
|
||||
onTerminalOAuthToken: (
|
||||
callback: (info: { terminalId: string; profileId?: string; email?: string; success: boolean; message?: string; detectedAt: string; needsOnboarding?: boolean }) => void
|
||||
callback: (info: { terminalId: string; profileId?: string; email?: string; success: boolean; message?: string; detectedAt: string }) => void
|
||||
) => () => void;
|
||||
onTerminalAuthCreated: (
|
||||
callback: (info: { terminalId: string; profileId: string; profileName: string }) => void
|
||||
@@ -91,9 +94,6 @@ export interface TerminalAPI {
|
||||
submitOAuthCode: (terminalId: string, code: string) => Promise<IPCResult>;
|
||||
onTerminalClaudeBusy: (callback: (id: string, isBusy: boolean) => void) => () => void;
|
||||
onTerminalClaudeExit: (callback: (id: string) => void) => () => void;
|
||||
onTerminalOnboardingComplete: (
|
||||
callback: (info: { terminalId: string; profileId?: string; detectedAt: string }) => void
|
||||
) => () => void;
|
||||
onTerminalPendingResume: (callback: (id: string, sessionId?: string) => void) => () => void;
|
||||
onTerminalProfileChanged: (callback: (event: TerminalProfileChangedEvent) => void) => () => void;
|
||||
|
||||
@@ -213,6 +213,10 @@ export const createTerminalAPI = (): TerminalAPI => ({
|
||||
listOtherWorktrees: (projectPath: string): Promise<IPCResult<OtherWorktreeInfo[]>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.TERMINAL_WORKTREE_LIST_OTHER, projectPath),
|
||||
|
||||
// Terminal Buffer Persistence
|
||||
saveTerminalBuffer: (terminalId: string, serializedBuffer: string): Promise<IPCResult> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.TERMINAL_SAVE_BUFFER, terminalId, serializedBuffer),
|
||||
|
||||
// Terminal Event Listeners
|
||||
onTerminalOutput: (
|
||||
callback: (id: string, data: string) => void
|
||||
@@ -388,21 +392,6 @@ export const createTerminalAPI = (): TerminalAPI => ({
|
||||
};
|
||||
},
|
||||
|
||||
onTerminalOnboardingComplete: (
|
||||
callback: (info: { terminalId: string; profileId?: string; detectedAt: string }) => void
|
||||
): (() => void) => {
|
||||
const handler = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
info: { terminalId: string; profileId?: string; detectedAt: string }
|
||||
): void => {
|
||||
callback(info);
|
||||
};
|
||||
ipcRenderer.on(IPC_CHANNELS.TERMINAL_ONBOARDING_COMPLETE, handler);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(IPC_CHANNELS.TERMINAL_ONBOARDING_COMPLETE, handler);
|
||||
};
|
||||
},
|
||||
|
||||
onTerminalPendingResume: (
|
||||
callback: (id: string, sessionId?: string) => void
|
||||
): (() => void) => {
|
||||
|
||||
@@ -747,7 +747,7 @@ export function App() {
|
||||
} else {
|
||||
// Initialization failed - show error but keep dialog open
|
||||
console.warn('[InitDialog] Initialization failed, showing error');
|
||||
const errorMessage = result?.error || 'Failed to initialize Auto Claude. Please try again.';
|
||||
const errorMessage = result?.error || 'Failed to initialize Aperant. Please try again.';
|
||||
setInitError(errorMessage);
|
||||
setIsInitializing(false);
|
||||
}
|
||||
|
||||
@@ -287,7 +287,7 @@ const MCP_SERVERS: Record<string, { name: string; description: string; icon: Rea
|
||||
],
|
||||
},
|
||||
'auto-claude': {
|
||||
name: 'Auto-Claude Tools',
|
||||
name: 'Aperant Tools',
|
||||
description: 'Build progress tracking, session context, discoveries & gotchas recording',
|
||||
icon: ListChecks,
|
||||
tools: [
|
||||
|
||||
@@ -180,7 +180,7 @@ export function AppUpdateNotification() {
|
||||
<DialogDescription>
|
||||
{t(
|
||||
"dialogs:appUpdate.description",
|
||||
"A new version of Auto Claude is ready to download"
|
||||
"A new version of Aperant is ready to download"
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
@@ -277,7 +277,7 @@ export function AppUpdateNotification() {
|
||||
{t("dialogs:appUpdate.readOnlyVolumeTitle", "Cannot install from disk image")}
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
{t("dialogs:appUpdate.readOnlyVolumeDescription", "Please move Auto Claude to your Applications folder before updating.")}
|
||||
{t("dialogs:appUpdate.readOnlyVolumeDescription", "Please move Aperant to your Applications folder before updating.")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -76,7 +76,7 @@ export function AuthFailureModal({ onOpenSettings }: AuthFailureModalProps) {
|
||||
{failureMessage}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('auth.failure.description', 'Please re-authenticate your Claude profile to continue using Auto Claude.')}
|
||||
{t('auth.failure.description', 'Please re-authenticate your Claude profile to continue using Aperant.')}
|
||||
</p>
|
||||
|
||||
{authFailureInfo.taskId && (
|
||||
|
||||
@@ -744,7 +744,7 @@ export function GitHubSetupModal({
|
||||
Select Base Branch
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Choose which branch Auto Claude should use as the base for creating task branches.
|
||||
Choose which branch Aperant should use as the base for creating task branches.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -811,7 +811,7 @@ export function GitHubSetupModal({
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<p className="font-medium text-foreground">Why select a branch?</p>
|
||||
<p className="mt-1">
|
||||
Auto Claude creates isolated workspaces for each task. Selecting the right base branch ensures
|
||||
Aperant creates isolated workspaces for each task. Selecting the right base branch ensures
|
||||
your tasks start with the latest code from your main development line.
|
||||
</p>
|
||||
</div>
|
||||
@@ -857,7 +857,7 @@ export function GitHubSetupModal({
|
||||
<CheckCircle2 className="h-8 w-8 text-success" />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground text-center">
|
||||
Auto Claude is ready to use! You can now create tasks that will be
|
||||
Aperant is ready to use! You can now create tasks that will be
|
||||
automatically based on <code className="px-1 bg-muted rounded">{selectedBranch}</code>.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -33,11 +33,15 @@ export function ProjectTabBar({
|
||||
// Keyboard shortcuts for tab navigation
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
// Skip if in input fields
|
||||
// Skip if in input fields (but NOT xterm's hidden textarea —
|
||||
// xterm already passes through Cmd/Ctrl+1-9 via attachCustomKeyEventHandler)
|
||||
const target = e.target as HTMLElement;
|
||||
const isXtermTextarea = target.classList?.contains('xterm-helper-textarea');
|
||||
if (
|
||||
e.target instanceof HTMLInputElement ||
|
||||
!isXtermTextarea &&
|
||||
(e.target instanceof HTMLInputElement ||
|
||||
e.target instanceof HTMLTextAreaElement ||
|
||||
(e.target as HTMLElement)?.isContentEditable
|
||||
target?.isContentEditable)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -480,7 +480,7 @@ export function Worktrees({ projectId }: WorktreesProps) {
|
||||
Worktrees
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Manage isolated workspaces for your Auto Claude tasks
|
||||
Manage isolated workspaces for your Aperant tasks
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -569,7 +569,7 @@ export function Worktrees({ projectId }: WorktreesProps) {
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold text-foreground">No Worktrees</h3>
|
||||
<p className="text-sm text-muted-foreground mt-2 max-w-md">
|
||||
Worktrees are created automatically when Auto Claude builds features.
|
||||
Worktrees are created automatically when Aperant builds features.
|
||||
You can also create terminal worktrees from the Agent Terminals tab.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -921,7 +921,7 @@ export function PRDetail({
|
||||
try {
|
||||
// Auto-assign current user (you can get from GitHub config)
|
||||
// For now, we'll just post the comment
|
||||
const approvalMessage = `## ✅ Auto Claude PR Review - APPROVED\n\n${reviewResult.summary}\n\n---\n*This approval was generated by Auto Claude.*`;
|
||||
const approvalMessage = `## ✅ Aperant PR Review - APPROVED\n\n${reviewResult.summary}\n\n---\n*This approval was generated by Aperant.*`;
|
||||
await Promise.resolve(onPostComment(approvalMessage));
|
||||
} finally {
|
||||
// Clear loading state if PR hasn't changed
|
||||
|
||||
@@ -23,7 +23,6 @@ function CIStatusIcon({ status, className }: CIStatusIconProps) {
|
||||
return <Loader2 className={cn(baseClasses, 'text-amber-400 animate-spin', className)} />;
|
||||
case 'failure':
|
||||
return <XCircle className={cn(baseClasses, 'text-red-400', className)} />;
|
||||
case 'none':
|
||||
default:
|
||||
return <Circle className={cn(baseClasses, 'text-muted-foreground/50', className)} />;
|
||||
}
|
||||
@@ -63,7 +62,6 @@ function ReviewStatusBadge({ status, className }: ReviewStatusBadgeProps) {
|
||||
{t('prStatus.review.pending')}
|
||||
</Badge>
|
||||
);
|
||||
case 'none':
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
@@ -88,7 +86,6 @@ function MergeReadinessIcon({ state, className }: MergeReadinessIconProps) {
|
||||
return <AlertTriangle className={cn(baseClasses, 'text-amber-400', className)} />;
|
||||
case 'blocked':
|
||||
return <Ban className={cn(baseClasses, 'text-red-400', className)} />;
|
||||
case 'unknown':
|
||||
default:
|
||||
return <HelpCircle className={cn(baseClasses, 'text-muted-foreground/50', className)} />;
|
||||
}
|
||||
@@ -169,9 +166,9 @@ export function StatusIndicator({
|
||||
)}
|
||||
|
||||
{/* Merge Readiness */}
|
||||
{showMergeStatus && mergeKey && (
|
||||
{showMergeStatus && mergeKey && mergeableState && (
|
||||
<div className="flex items-center gap-1" title={t(`prStatus.merge.${mergeKey}`)}>
|
||||
<MergeReadinessIcon state={mergeableState!} />
|
||||
<MergeReadinessIcon state={mergeableState} />
|
||||
{!compact && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t(`prStatus.merge.${mergeKey}`)}
|
||||
|
||||
@@ -395,7 +395,7 @@ describe('PRDetail Clean Review Functionality', () => {
|
||||
summary: 'All code passes review. No issues found.'
|
||||
});
|
||||
|
||||
const cleanReviewMessage = `## ✅ Auto Claude PR Review - PASSED
|
||||
const cleanReviewMessage = `## ✅ Aperant PR Review - PASSED
|
||||
|
||||
**Status:** All code is good
|
||||
|
||||
@@ -403,12 +403,12 @@ ${reviewResult.summary}
|
||||
|
||||
---
|
||||
|
||||
*This automated review found no issues. Generated by Auto Claude.*`;
|
||||
*This automated review found no issues. Generated by Aperant.*`;
|
||||
|
||||
expect(cleanReviewMessage).toContain('## ✅ Auto Claude PR Review - PASSED');
|
||||
expect(cleanReviewMessage).toContain('## ✅ Aperant PR Review - PASSED');
|
||||
expect(cleanReviewMessage).toContain('**Status:** All code is good');
|
||||
expect(cleanReviewMessage).toContain(reviewResult.summary);
|
||||
expect(cleanReviewMessage).toContain('*This automated review found no issues. Generated by Auto Claude.*');
|
||||
expect(cleanReviewMessage).toContain('*This automated review found no issues. Generated by Aperant.*');
|
||||
});
|
||||
|
||||
it('should include custom summary in clean review comment', () => {
|
||||
@@ -417,7 +417,7 @@ ${reviewResult.summary}
|
||||
summary: customSummary
|
||||
});
|
||||
|
||||
const cleanReviewMessage = `## ✅ Auto Claude PR Review - PASSED
|
||||
const cleanReviewMessage = `## ✅ Aperant PR Review - PASSED
|
||||
|
||||
**Status:** All code is good
|
||||
|
||||
@@ -425,7 +425,7 @@ ${reviewResult.summary}
|
||||
|
||||
---
|
||||
|
||||
*This automated review found no issues. Generated by Auto Claude.*`;
|
||||
*This automated review found no issues. Generated by Aperant.*`;
|
||||
|
||||
expect(cleanReviewMessage).toContain(customSummary);
|
||||
});
|
||||
@@ -435,7 +435,7 @@ ${reviewResult.summary}
|
||||
summary: ''
|
||||
});
|
||||
|
||||
const cleanReviewMessage = `## ✅ Auto Claude PR Review - PASSED
|
||||
const cleanReviewMessage = `## ✅ Aperant PR Review - PASSED
|
||||
|
||||
**Status:** All code is good
|
||||
|
||||
@@ -443,7 +443,7 @@ ${reviewResult.summary}
|
||||
|
||||
---
|
||||
|
||||
*This automated review found no issues. Generated by Auto Claude.*`;
|
||||
*This automated review found no issues. Generated by Aperant.*`;
|
||||
|
||||
expect(cleanReviewMessage).toBeDefined();
|
||||
expect(cleanReviewMessage).toContain('All code is good');
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* AutoFixButton Component for GitLab Issues
|
||||
*
|
||||
* Stub component - implements the same pattern as GitHub's AutoFixButton
|
||||
* adapted for GitLab issues.
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Wand2, Loader2, AlertCircle, CheckCircle2 } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import type { GitLabIssue, GitLabAutoFixConfig, GitLabAutoFixProgress, GitLabAutoFixQueueItem } from '@shared/types';
|
||||
|
||||
interface GitLabAutoFixButtonProps {
|
||||
issue: GitLabIssue;
|
||||
projectId: string;
|
||||
config: GitLabAutoFixConfig | null;
|
||||
queueItem: GitLabAutoFixQueueItem | null;
|
||||
onStartAutoFix?: (projectId: string, issueIid: number) => void;
|
||||
}
|
||||
|
||||
export function GitLabAutoFixButton({
|
||||
issue,
|
||||
projectId,
|
||||
config,
|
||||
queueItem,
|
||||
onStartAutoFix,
|
||||
}: GitLabAutoFixButtonProps) {
|
||||
const { t } = useTranslation(['gitlab']);
|
||||
const [isStarting, setIsStarting] = useState(false);
|
||||
const [progress, setProgress] = useState<GitLabAutoFixProgress | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [completed, setCompleted] = useState(false);
|
||||
|
||||
// Check if the issue has an auto-fix label
|
||||
const hasAutoFixLabel = useCallback(() => {
|
||||
if (!config || !config.enabled || !config.labels.length) return false;
|
||||
const issueLabels = issue.labels.map(l => l.toLowerCase());
|
||||
return config.labels.some(label => issueLabels.includes(label.toLowerCase()));
|
||||
}, [config, issue.labels]);
|
||||
|
||||
// Listen for progress events
|
||||
useEffect(() => {
|
||||
const cleanupProgress = window.electronAPI.onGitLabAutoFixProgress?.(
|
||||
(eventProjectId: string, progressData: GitLabAutoFixProgress) => {
|
||||
if (eventProjectId === projectId && progressData.issueIid === issue.iid) {
|
||||
setProgress(progressData);
|
||||
setIsStarting(false);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const cleanupComplete = window.electronAPI.onGitLabAutoFixComplete?.(
|
||||
(eventProjectId: string, result: GitLabAutoFixQueueItem) => {
|
||||
if (eventProjectId === projectId && result.issueIid === issue.iid) {
|
||||
setCompleted(true);
|
||||
setProgress(null);
|
||||
setIsStarting(false);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const cleanupError = window.electronAPI.onGitLabAutoFixError?.(
|
||||
(eventProjectId: string, issueIid: number, error: string) => {
|
||||
if (eventProjectId === projectId && issueIid === issue.iid) {
|
||||
setError(error);
|
||||
setProgress(null);
|
||||
setIsStarting(false);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return () => {
|
||||
cleanupProgress?.();
|
||||
cleanupComplete?.();
|
||||
cleanupError?.();
|
||||
};
|
||||
}, [projectId, issue.iid]);
|
||||
|
||||
// Check if already in queue
|
||||
const isInQueue = queueItem && queueItem.status !== 'completed' && queueItem.status !== 'failed';
|
||||
const isProcessing = isStarting || progress !== null || isInQueue;
|
||||
|
||||
const handleStartAutoFix = useCallback(() => {
|
||||
setIsStarting(true);
|
||||
setError(null);
|
||||
setCompleted(false);
|
||||
if (onStartAutoFix) {
|
||||
onStartAutoFix(projectId, issue.iid);
|
||||
} else if (window.electronAPI.startGitLabAutoFix) {
|
||||
window.electronAPI.startGitLabAutoFix(projectId, issue.iid);
|
||||
}
|
||||
}, [projectId, issue.iid, onStartAutoFix]);
|
||||
|
||||
// Don't render if auto-fix is disabled or issue doesn't have the right label
|
||||
if (!config?.enabled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Show completed state
|
||||
if (completed || queueItem?.status === 'completed') {
|
||||
return (
|
||||
<div className="flex items-center gap-2 text-success text-sm">
|
||||
<CheckCircle2 className="h-4 w-4" />
|
||||
<span>{t('gitlab:autoFix.specCreated')}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Show error state
|
||||
if (error || queueItem?.status === 'failed') {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-destructive text-sm">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<span>{error || queueItem?.error || t('gitlab:autoFix.autoFixFailed')}</span>
|
||||
</div>
|
||||
<Button size="sm" variant="outline" onClick={handleStartAutoFix}>
|
||||
<Wand2 className="h-4 w-4 mr-2" />
|
||||
{t('gitlab:autoFix.retryAutoFix')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Show progress state
|
||||
if (isProcessing) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span>{progress?.message || t('gitlab:autoFix.processing')}</span>
|
||||
</div>
|
||||
{progress && (
|
||||
<Progress value={progress.progress} className="h-1" />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Show button - either highlighted if has auto-fix label, or normal
|
||||
return (
|
||||
<Button
|
||||
size="sm"
|
||||
variant={hasAutoFixLabel() ? 'default' : 'outline'}
|
||||
onClick={handleStartAutoFix}
|
||||
>
|
||||
<Wand2 className="h-4 w-4 mr-2" />
|
||||
{t('gitlab:autoFix.autoFix')}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
/**
|
||||
* BatchReviewWizard Component for GitLab Issues
|
||||
*
|
||||
* Stub component - implements the same pattern as GitHub's BatchReviewWizard
|
||||
* adapted for GitLab issues (using iid instead of issueNumber).
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
Layers,
|
||||
CheckCircle2,
|
||||
Loader2,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Users,
|
||||
Play,
|
||||
AlertTriangle,
|
||||
} from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible';
|
||||
import type {
|
||||
GitLabAnalyzePreviewResult,
|
||||
GitLabAnalyzePreviewProgress,
|
||||
GitLabProposedBatch,
|
||||
} from '@shared/types';
|
||||
|
||||
interface GitLabBatchReviewWizardProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onStartAnalysis: () => void;
|
||||
onApproveBatches: (batches: GitLabProposedBatch[]) => Promise<void>;
|
||||
analysisProgress: GitLabAnalyzePreviewProgress | null;
|
||||
analysisResult: GitLabAnalyzePreviewResult | null;
|
||||
analysisError: string | null;
|
||||
isAnalyzing: boolean;
|
||||
isApproving: boolean;
|
||||
}
|
||||
|
||||
export function GitLabBatchReviewWizard({
|
||||
isOpen,
|
||||
onClose,
|
||||
onStartAnalysis,
|
||||
onApproveBatches,
|
||||
analysisProgress,
|
||||
analysisResult,
|
||||
analysisError,
|
||||
isAnalyzing,
|
||||
isApproving,
|
||||
}: GitLabBatchReviewWizardProps) {
|
||||
const { t } = useTranslation(['gitlab']);
|
||||
// Track which batches are selected for approval
|
||||
const [selectedBatchIds, setSelectedBatchIds] = useState<Set<number>>(new Set());
|
||||
// Track which single issues are selected for approval
|
||||
const [selectedSingleIids, setSelectedSingleIids] = useState<Set<number>>(new Set());
|
||||
// Track which batches are expanded
|
||||
const [expandedBatchIds, setExpandedBatchIds] = useState<Set<number>>(new Set());
|
||||
// Current wizard step
|
||||
const [step, setStep] = useState<'intro' | 'analyzing' | 'review' | 'approving' | 'done'>('intro');
|
||||
// Local error state for approval failures
|
||||
const [approvalError, setApprovalError] = useState<string | null>(null);
|
||||
|
||||
// Reset state when dialog opens
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setSelectedBatchIds(new Set());
|
||||
setSelectedSingleIids(new Set());
|
||||
setExpandedBatchIds(new Set());
|
||||
setStep('intro');
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
// Update step based on analysis state
|
||||
useEffect(() => {
|
||||
if (isAnalyzing) {
|
||||
setStep('analyzing');
|
||||
} else if (analysisResult) {
|
||||
setStep('review');
|
||||
// Select all validated batches by default
|
||||
const validatedIds = new Set(
|
||||
analysisResult.proposedBatches
|
||||
.map((b, idx) => b.validated ? idx : -1)
|
||||
.filter(idx => idx !== -1)
|
||||
);
|
||||
setSelectedBatchIds(validatedIds);
|
||||
// If no batches, auto-select all single issues
|
||||
if (analysisResult.proposedBatches.length === 0 && analysisResult.singleIssues.length > 0) {
|
||||
const singleIssueIids = new Set(
|
||||
analysisResult.singleIssues.map(issue => issue.iid)
|
||||
);
|
||||
setSelectedSingleIids(singleIssueIids);
|
||||
}
|
||||
} else if (analysisError) {
|
||||
setStep('intro');
|
||||
}
|
||||
}, [isAnalyzing, analysisResult, analysisError]);
|
||||
|
||||
// Update step when approving
|
||||
useEffect(() => {
|
||||
if (isApproving) {
|
||||
setStep('approving');
|
||||
}
|
||||
}, [isApproving]);
|
||||
|
||||
const toggleBatchSelection = useCallback((batchIndex: number) => {
|
||||
setSelectedBatchIds(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(batchIndex)) {
|
||||
next.delete(batchIndex);
|
||||
} else {
|
||||
next.add(batchIndex);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const toggleSingleIssueSelection = useCallback((iid: number) => {
|
||||
setSelectedSingleIids(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(iid)) {
|
||||
next.delete(iid);
|
||||
} else {
|
||||
next.add(iid);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const toggleBatchExpanded = useCallback((batchIndex: number) => {
|
||||
setExpandedBatchIds(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(batchIndex)) {
|
||||
next.delete(batchIndex);
|
||||
} else {
|
||||
next.add(batchIndex);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const selectAllBatches = useCallback(() => {
|
||||
if (!analysisResult) return;
|
||||
const allIds = new Set(analysisResult.proposedBatches.map((_, idx) => idx));
|
||||
setSelectedBatchIds(allIds);
|
||||
const allSingleIssues = new Set(analysisResult.singleIssues.map(issue => issue.iid));
|
||||
setSelectedSingleIids(allSingleIssues);
|
||||
}, [analysisResult]);
|
||||
|
||||
const deselectAllBatches = useCallback(() => {
|
||||
setSelectedBatchIds(new Set());
|
||||
setSelectedSingleIids(new Set());
|
||||
}, []);
|
||||
|
||||
const handleApprove = useCallback(async () => {
|
||||
if (!analysisResult) return;
|
||||
|
||||
// Get selected batches
|
||||
const selectedBatches = analysisResult.proposedBatches.filter(
|
||||
(_, idx) => selectedBatchIds.has(idx)
|
||||
);
|
||||
|
||||
// Convert selected single issues into batches (each single issue becomes a batch of 1)
|
||||
const selectedSingleIssueBatches: GitLabProposedBatch[] = analysisResult.singleIssues
|
||||
.filter(issue => selectedSingleIids.has(issue.iid))
|
||||
.map(issue => ({
|
||||
primaryIssue: issue.iid,
|
||||
issues: [{
|
||||
iid: issue.iid,
|
||||
title: issue.title,
|
||||
labels: issue.labels,
|
||||
similarityToPrimary: 1.0
|
||||
}],
|
||||
issueCount: 1,
|
||||
commonThemes: [],
|
||||
validated: true,
|
||||
confidence: 1.0,
|
||||
reasoning: 'Single issue - not grouped with others',
|
||||
theme: issue.title
|
||||
}));
|
||||
|
||||
// Combine batches and single issues
|
||||
const allBatches = [...selectedBatches, ...selectedSingleIssueBatches];
|
||||
|
||||
try {
|
||||
await onApproveBatches(allBatches);
|
||||
setStep('done');
|
||||
} catch (error) {
|
||||
setApprovalError(error instanceof Error ? error.message : String(error));
|
||||
setStep('intro');
|
||||
}
|
||||
}, [analysisResult, selectedBatchIds, selectedSingleIids, onApproveBatches]);
|
||||
|
||||
const renderIntro = () => (
|
||||
<div className="flex flex-col items-center justify-center py-8 space-y-6">
|
||||
<div className="p-4 rounded-full bg-primary/10">
|
||||
<Layers className="h-12 w-12 text-primary" />
|
||||
</div>
|
||||
<div className="text-center space-y-2">
|
||||
<h3 className="text-lg font-semibold">{t('gitlab:batchReview.title')}</h3>
|
||||
<p className="text-sm text-muted-foreground max-w-md">
|
||||
{t('gitlab:batchReview.description')}
|
||||
</p>
|
||||
</div>
|
||||
{(analysisError || approvalError) && (
|
||||
<div className="flex items-center gap-2 p-3 rounded-lg bg-destructive/10 text-destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<span className="text-sm">{analysisError || approvalError}</span>
|
||||
</div>
|
||||
)}
|
||||
<Button onClick={onStartAnalysis} size="lg">
|
||||
<Layers className="h-4 w-4 mr-2" />
|
||||
{t('gitlab:batchReview.startAnalysis')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderAnalyzing = () => (
|
||||
<div className="flex flex-col items-center justify-center py-8 space-y-6">
|
||||
<Loader2 className="h-12 w-12 text-primary animate-spin" />
|
||||
<div className="text-center space-y-2">
|
||||
<h3 className="text-lg font-semibold">{t('gitlab:batchReview.analyzing')}</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{analysisProgress?.message || t('gitlab:batchReview.computingSimilarity')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="w-full max-w-md">
|
||||
<Progress value={analysisProgress?.progress ?? 0} />
|
||||
<p className="text-xs text-center text-muted-foreground mt-2">
|
||||
{t('gitlab:batchReview.percentComplete', { value: analysisProgress?.progress ?? 0 })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderReview = () => {
|
||||
if (!analysisResult) return null;
|
||||
|
||||
const { proposedBatches, singleIssues, totalIssues } = analysisResult;
|
||||
const selectedCount = selectedBatchIds.size;
|
||||
const totalIssuesInSelected = proposedBatches
|
||||
.filter((_, idx) => selectedBatchIds.has(idx))
|
||||
.reduce((sum, b) => sum + b.issueCount, 0);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-[60vh]">
|
||||
{/* Stats Bar */}
|
||||
<div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg mb-4">
|
||||
<div className="flex items-center gap-4 text-sm">
|
||||
<span>
|
||||
<strong>{totalIssues}</strong> {t('gitlab:batchReview.issuesAnalyzed')}
|
||||
</span>
|
||||
<span className="text-muted-foreground">|</span>
|
||||
<span>
|
||||
<strong>{proposedBatches.length}</strong> {t('gitlab:batchReview.batchesProposed')}
|
||||
</span>
|
||||
<span className="text-muted-foreground">|</span>
|
||||
<span>
|
||||
<strong>{singleIssues.length}</strong> {t('gitlab:batchReview.singleIssues')}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="ghost" size="sm" onClick={selectAllBatches}>
|
||||
{t('gitlab:batchReview.selectDeselectAll')}
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={deselectAllBatches}>
|
||||
{t('gitlab:batchReview.deselectAll')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Batches List */}
|
||||
<ScrollArea className="flex-1 -mx-6 px-6">
|
||||
<div className="space-y-3">
|
||||
{proposedBatches.map((batch, idx) => (
|
||||
<GitLabBatchCard
|
||||
key={idx}
|
||||
batch={batch}
|
||||
index={idx}
|
||||
isSelected={selectedBatchIds.has(idx)}
|
||||
isExpanded={expandedBatchIds.has(idx)}
|
||||
onToggleSelect={() => toggleBatchSelection(idx)}
|
||||
onToggleExpand={() => toggleBatchExpanded(idx)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Single Issues Section */}
|
||||
{singleIssues.length > 0 && (
|
||||
<div className="mt-6">
|
||||
<h4 className="text-sm font-medium text-muted-foreground mb-2">
|
||||
{t('gitlab:batchReview.selectSingleIssues')}
|
||||
</h4>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{singleIssues.slice(0, 10).map((issue) => (
|
||||
<div
|
||||
key={issue.iid}
|
||||
onClick={() => toggleSingleIssueSelection(issue.iid)}
|
||||
className={`p-2 rounded border text-sm truncate cursor-pointer transition-colors ${
|
||||
selectedSingleIids.has(issue.iid)
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border hover:bg-accent'
|
||||
}`}
|
||||
>
|
||||
<Checkbox
|
||||
checked={selectedSingleIids.has(issue.iid)}
|
||||
className="inline-block mr-2"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onCheckedChange={() => toggleSingleIssueSelection(issue.iid)}
|
||||
/>
|
||||
<span className="text-muted-foreground">#{issue.iid}</span>{' '}
|
||||
{issue.title}
|
||||
</div>
|
||||
))}
|
||||
{singleIssues.length > 10 && (
|
||||
<div className="p-2 text-sm text-muted-foreground">
|
||||
{t('gitlab:batchReview.andMore', { count: singleIssues.length - 10 })}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
|
||||
{/* Selection Summary */}
|
||||
<div className="flex items-center justify-between pt-4 mt-4 border-t border-border">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{t('gitlab:batchReview.batchesSelected', {
|
||||
count: selectedCount,
|
||||
issues: totalIssuesInSelected
|
||||
})}
|
||||
{selectedSingleIids.size > 0 && (
|
||||
<> {t('gitlab:batchReview.plusSingleIssues', { count: selectedSingleIids.size })}</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const renderApproving = () => (
|
||||
<div className="flex flex-col items-center justify-center py-8 space-y-6">
|
||||
<Loader2 className="h-12 w-12 text-primary animate-spin" />
|
||||
<div className="text-center space-y-2">
|
||||
<h3 className="text-lg font-semibold">{t('gitlab:batchReview.creatingBatches')}</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('gitlab:batchReview.settingUpBatches')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderDone = () => (
|
||||
<div className="flex flex-col items-center justify-center py-8 space-y-6">
|
||||
<div className="p-4 rounded-full bg-green-500/10">
|
||||
<CheckCircle2 className="h-12 w-12 text-green-500" />
|
||||
</div>
|
||||
<div className="text-center space-y-2">
|
||||
<h3 className="text-lg font-semibold">{t('gitlab:batchReview.batchesCreated')}</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('gitlab:batchReview.batchesReady')}
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={onClose}>
|
||||
{t('gitlab:batchReview.close')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-w-3xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Layers className="h-5 w-5" />
|
||||
{t('gitlab:batchReview.title')}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{step === 'intro' && t('gitlab:batchReview.description')}
|
||||
{step === 'analyzing' && t('gitlab:batchReview.computingSimilarity')}
|
||||
{step === 'review' && t('gitlab:batchReview.description')}
|
||||
{step === 'approving' && t('gitlab:batchReview.settingUpBatches')}
|
||||
{step === 'done' && t('gitlab:batchReview.batchesReady')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="py-4">
|
||||
{step === 'intro' && renderIntro()}
|
||||
{step === 'analyzing' && renderAnalyzing()}
|
||||
{step === 'review' && renderReview()}
|
||||
{step === 'approving' && renderApproving()}
|
||||
{step === 'done' && renderDone()}
|
||||
</div>
|
||||
|
||||
{step === 'review' && (
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
{t('gitlab:batchReview.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleApprove}
|
||||
disabled={(selectedBatchIds.size === 0 && selectedSingleIids.size === 0) || isApproving}
|
||||
>
|
||||
{isApproving ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
{t('gitlab:batchReview.creating')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="h-4 w-4 mr-2" />
|
||||
{t('gitlab:batchReview.approveAndCreate', {
|
||||
count: selectedBatchIds.size + selectedSingleIids.size
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
interface GitLabBatchCardProps {
|
||||
batch: GitLabProposedBatch;
|
||||
index: number;
|
||||
isSelected: boolean;
|
||||
isExpanded: boolean;
|
||||
onToggleSelect: () => void;
|
||||
onToggleExpand: () => void;
|
||||
}
|
||||
|
||||
function GitLabBatchCard({
|
||||
batch,
|
||||
index,
|
||||
isSelected,
|
||||
isExpanded,
|
||||
onToggleSelect,
|
||||
onToggleExpand,
|
||||
}: GitLabBatchCardProps) {
|
||||
const { t } = useTranslation(['gitlab']);
|
||||
const confidenceColor = batch.confidence >= 0.8
|
||||
? 'text-green-500'
|
||||
: batch.confidence >= 0.6
|
||||
? 'text-yellow-500'
|
||||
: 'text-red-500';
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`rounded-lg border transition-colors ${
|
||||
isSelected
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border bg-card'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-3 p-3">
|
||||
<Checkbox
|
||||
checked={isSelected}
|
||||
onCheckedChange={onToggleSelect}
|
||||
/>
|
||||
|
||||
<Collapsible className="flex-1" open={isExpanded} onOpenChange={onToggleExpand}>
|
||||
<div className="flex items-center justify-between">
|
||||
<CollapsibleTrigger className="flex items-center gap-2 hover:underline">
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
)}
|
||||
<span className="font-medium text-sm">
|
||||
{batch.theme || t('gitlab:batchReview.batchNumber', { number: index + 1 })}
|
||||
</span>
|
||||
</CollapsibleTrigger>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline" className="text-xs">
|
||||
<Users className="h-3 w-3 mr-1" />
|
||||
{batch.issueCount} {t('gitlab:batchReview.issues')}
|
||||
</Badge>
|
||||
<Badge
|
||||
variant={batch.validated ? 'default' : 'secondary'}
|
||||
className="text-xs"
|
||||
>
|
||||
{batch.validated ? (
|
||||
<CheckCircle2 className="h-3 w-3 mr-1" />
|
||||
) : (
|
||||
<AlertTriangle className="h-3 w-3 mr-1" />
|
||||
)}
|
||||
<span className={confidenceColor}>
|
||||
{Math.round(batch.confidence * 100)}%
|
||||
</span>
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<CollapsibleContent className="mt-3 space-y-2">
|
||||
{/* Reasoning */}
|
||||
<p className="text-xs text-muted-foreground px-6">
|
||||
{batch.reasoning}
|
||||
</p>
|
||||
|
||||
{/* Issues List */}
|
||||
<div className="space-y-1 px-6">
|
||||
{batch.issues.map((issue) => (
|
||||
<div
|
||||
key={issue.iid}
|
||||
className="flex items-center justify-between text-sm py-1"
|
||||
>
|
||||
<div className="flex items-center gap-2 truncate">
|
||||
<span className="text-muted-foreground">
|
||||
#{issue.iid}
|
||||
</span>
|
||||
<span className="truncate">{issue.title}</span>
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t('gitlab:batchReview.similarPercent', { value: Math.round(issue.similarityToPrimary * 100) })}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Themes */}
|
||||
{batch.commonThemes.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 px-6 pt-2">
|
||||
{batch.commonThemes.map((theme, i) => (
|
||||
<Badge key={i} variant="secondary" className="text-xs">
|
||||
{theme}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,3 +4,5 @@ export { InvestigationDialog } from './InvestigationDialog';
|
||||
export { EmptyState, NotConnectedState } from './EmptyStates';
|
||||
export { IssueListHeader } from './IssueListHeader';
|
||||
export { IssueList } from './IssueList';
|
||||
export { GitLabAutoFixButton } from './AutoFixButton';
|
||||
export { GitLabBatchReviewWizard } from './BatchReviewWizard';
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Unit tests for GitLab error parser
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
parseGitLabError,
|
||||
isRecoverableGitLabError,
|
||||
GitLabErrorCode
|
||||
} from '../gitlab-error-parser';
|
||||
|
||||
describe('gitlab-error-parser', () => {
|
||||
it('should parse 401 authentication errors', () => {
|
||||
const error = new Error('401 Unauthorized');
|
||||
const parsed = parseGitLabError(error);
|
||||
|
||||
expect(parsed.code).toBe(GitLabErrorCode.AUTHENTICATION_FAILED);
|
||||
expect(parsed.recoverable).toBe(true);
|
||||
});
|
||||
|
||||
it('should parse 403 permission errors', () => {
|
||||
const error = new Error('403 Forbidden');
|
||||
const parsed = parseGitLabError(error);
|
||||
|
||||
expect(parsed.code).toBe(GitLabErrorCode.INSUFFICIENT_PERMISSIONS);
|
||||
expect(parsed.recoverable).toBe(false);
|
||||
});
|
||||
|
||||
it('should parse 404 not found errors', () => {
|
||||
const error = new Error('404 Not Found');
|
||||
const parsed = parseGitLabError(error);
|
||||
|
||||
expect(parsed.code).toBe(GitLabErrorCode.PROJECT_NOT_FOUND);
|
||||
expect(parsed.recoverable).toBe(false);
|
||||
});
|
||||
|
||||
it('should parse 409 conflict errors', () => {
|
||||
const error = new Error('409 Conflict');
|
||||
const parsed = parseGitLabError(error);
|
||||
|
||||
expect(parsed.code).toBe(GitLabErrorCode.CONFLICT);
|
||||
expect(parsed.recoverable).toBe(false);
|
||||
});
|
||||
|
||||
it('should parse 429 rate limit errors', () => {
|
||||
const error = 'Rate limit exceeded';
|
||||
const parsed = parseGitLabError(error);
|
||||
|
||||
expect(parsed.code).toBe(GitLabErrorCode.RATE_LIMITED);
|
||||
expect(parsed.recoverable).toBe(true);
|
||||
});
|
||||
|
||||
it('should identify recoverable errors', () => {
|
||||
expect(isRecoverableGitLabError(new Error('401 Unauthorized'))).toBe(true);
|
||||
expect(isRecoverableGitLabError(new Error('Network error'))).toBe(true);
|
||||
expect(isRecoverableGitLabError(new Error('409 Conflict'))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* GitLab Error Parser Utility
|
||||
*
|
||||
* Parses GitLab API errors and returns error codes for i18n translation.
|
||||
* Follows the same pattern as GitHub's error parser.
|
||||
*/
|
||||
|
||||
export enum GitLabErrorCode {
|
||||
AUTHENTICATION_FAILED = 'AUTHENTICATION_FAILED',
|
||||
RATE_LIMITED = 'RATE_LIMITED',
|
||||
NETWORK_ERROR = 'NETWORK_ERROR',
|
||||
PROJECT_NOT_FOUND = 'PROJECT_NOT_FOUND',
|
||||
INSUFFICIENT_PERMISSIONS = 'INSUFFICIENT_PERMISSIONS',
|
||||
CONFLICT = 'CONFLICT',
|
||||
UNKNOWN = 'UNKNOWN'
|
||||
}
|
||||
|
||||
export interface ParsedGitLabError {
|
||||
code: GitLabErrorCode;
|
||||
recoverable: boolean;
|
||||
details?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a GitLab error and return an error code
|
||||
*/
|
||||
export function parseGitLabError(error: unknown): ParsedGitLabError {
|
||||
if (error instanceof Error) {
|
||||
return parseGitLabErrorMessage(error.message);
|
||||
}
|
||||
|
||||
if (typeof error === 'string') {
|
||||
return parseGitLabErrorMessage(error);
|
||||
}
|
||||
|
||||
// Handle Error-like objects with a message property
|
||||
if (typeof error === 'object' && error !== null && 'message' in error) {
|
||||
const message = (error as { message: string }).message;
|
||||
if (typeof message === 'string') {
|
||||
return parseGitLabErrorMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
code: GitLabErrorCode.UNKNOWN,
|
||||
recoverable: false
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse GitLab error message
|
||||
*/
|
||||
function parseGitLabErrorMessage(message: string): ParsedGitLabError {
|
||||
const lowerMessage = message.toLowerCase();
|
||||
|
||||
// Check for explicit HTTP status code in response (if available)
|
||||
// Try to extract status from common patterns like "Status: 401" or HTTP error responses
|
||||
const statusMatch = message.match(/\bstatus:\s*(\d{3})\b/i) ||
|
||||
message.match(/\bhttp\s+(\d{3})\b/i) ||
|
||||
lowerMessage.match(/\b"status":\s*(\d{3})\b/);
|
||||
|
||||
if (statusMatch) {
|
||||
const statusCode = parseInt(statusMatch[1], 10);
|
||||
switch (statusCode) {
|
||||
case 401:
|
||||
return { code: GitLabErrorCode.AUTHENTICATION_FAILED, recoverable: true };
|
||||
case 403:
|
||||
return { code: GitLabErrorCode.INSUFFICIENT_PERMISSIONS, recoverable: false };
|
||||
case 404:
|
||||
return { code: GitLabErrorCode.PROJECT_NOT_FOUND, recoverable: false };
|
||||
case 409:
|
||||
return { code: GitLabErrorCode.CONFLICT, recoverable: false };
|
||||
case 429:
|
||||
return { code: GitLabErrorCode.RATE_LIMITED, recoverable: true };
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to message content analysis with word-boundary regex to avoid false matches
|
||||
// Authentication errors
|
||||
if (/\b401\b/.test(message) || lowerMessage.includes('unauthorized') || lowerMessage.includes('invalid token')) {
|
||||
return {
|
||||
code: GitLabErrorCode.AUTHENTICATION_FAILED,
|
||||
recoverable: true
|
||||
};
|
||||
}
|
||||
|
||||
// Rate limiting (429)
|
||||
if (/\b429\b/.test(message) || lowerMessage.includes('rate limit') || lowerMessage.includes('too many requests')) {
|
||||
return {
|
||||
code: GitLabErrorCode.RATE_LIMITED,
|
||||
recoverable: true
|
||||
};
|
||||
}
|
||||
|
||||
// Network errors - use specific phrases to avoid false positives
|
||||
if (lowerMessage.includes('network') ||
|
||||
lowerMessage.includes('connection refused') ||
|
||||
lowerMessage.includes('connection failed') ||
|
||||
lowerMessage.includes('unable to connect') ||
|
||||
lowerMessage.includes('connect timeout') ||
|
||||
lowerMessage.includes('timeout')) {
|
||||
return {
|
||||
code: GitLabErrorCode.NETWORK_ERROR,
|
||||
recoverable: true
|
||||
};
|
||||
}
|
||||
|
||||
// Project not found (404) - not recoverable
|
||||
if (/\b404\b/.test(message) || lowerMessage.includes('not found')) {
|
||||
return {
|
||||
code: GitLabErrorCode.PROJECT_NOT_FOUND,
|
||||
recoverable: false
|
||||
};
|
||||
}
|
||||
|
||||
// Permission denied (403) - not recoverable
|
||||
if (/\b403\b/.test(message) || lowerMessage.includes('forbidden') || lowerMessage.includes('permission denied')) {
|
||||
return {
|
||||
code: GitLabErrorCode.INSUFFICIENT_PERMISSIONS,
|
||||
recoverable: false
|
||||
};
|
||||
}
|
||||
|
||||
// Conflict (409)
|
||||
if (/\b409\b/.test(message) || lowerMessage.includes('conflict')) {
|
||||
return {
|
||||
code: GitLabErrorCode.CONFLICT,
|
||||
recoverable: false
|
||||
};
|
||||
}
|
||||
|
||||
// Default error
|
||||
return {
|
||||
code: GitLabErrorCode.UNKNOWN,
|
||||
recoverable: false,
|
||||
details: message
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an error is recoverable
|
||||
*/
|
||||
export function isRecoverableGitLabError(error: unknown): boolean {
|
||||
const parsed = parseGitLabError(error);
|
||||
return parsed.recoverable;
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
/**
|
||||
* Filter bar for GitLab MRs list
|
||||
* Grid layout: Contributors (3) | Status (3) | Search (8)
|
||||
* Multi-select dropdowns with visible chip selections
|
||||
*
|
||||
* Stub component - implements the same pattern as PRFilterBar
|
||||
* adapted for GitLab merge requests.
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useRef, useCallback, useEffect } from 'react';
|
||||
import {
|
||||
Search,
|
||||
Users,
|
||||
Sparkles,
|
||||
CheckCircle2,
|
||||
Send,
|
||||
AlertCircle,
|
||||
CheckCheck,
|
||||
RefreshCw,
|
||||
X,
|
||||
Filter,
|
||||
Check,
|
||||
Loader2,
|
||||
ArrowUpDown,
|
||||
Clock,
|
||||
FileCode
|
||||
} from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { GitLabMRFilterState, GitLabMRStatusFilter, GitLabMRSortOption } from '../hooks/useGitLabMRFiltering';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface MRFilterBarProps {
|
||||
filters: GitLabMRFilterState;
|
||||
contributors: string[];
|
||||
hasActiveFilters: boolean;
|
||||
onSearchChange: (query: string) => void;
|
||||
onContributorsChange: (contributors: string[]) => void;
|
||||
onStatusesChange: (statuses: GitLabMRStatusFilter[]) => void;
|
||||
onSortChange: (sortBy: GitLabMRSortOption) => void;
|
||||
onClearFilters: () => void;
|
||||
}
|
||||
|
||||
// Status options
|
||||
const STATUS_OPTIONS: Array<{
|
||||
value: GitLabMRStatusFilter;
|
||||
labelKey: string;
|
||||
icon: typeof Sparkles;
|
||||
color: string;
|
||||
bgColor: string;
|
||||
}> = [
|
||||
{ value: 'reviewing', labelKey: 'mrFiltering.reviewing', icon: Loader2, color: 'text-amber-400', bgColor: 'bg-amber-500/20' },
|
||||
{ value: 'not_reviewed', labelKey: 'mrFiltering.notReviewed', icon: Sparkles, color: 'text-slate-500', bgColor: 'bg-slate-500/20' },
|
||||
{ value: 'reviewed', labelKey: 'mrFiltering.reviewed', icon: CheckCircle2, color: 'text-blue-400', bgColor: 'bg-blue-500/20' },
|
||||
{ value: 'posted', labelKey: 'mrFiltering.posted', icon: Send, color: 'text-purple-400', bgColor: 'bg-purple-500/20' },
|
||||
{ value: 'changes_requested', labelKey: 'mrFiltering.changesRequested', icon: AlertCircle, color: 'text-red-400', bgColor: 'bg-red-500/20' },
|
||||
{ value: 'ready_to_merge', labelKey: 'mrFiltering.readyToMerge', icon: CheckCheck, color: 'text-emerald-400', bgColor: 'bg-emerald-500/20' },
|
||||
{ value: 'ready_for_followup', labelKey: 'mrFiltering.readyForFollowup', icon: RefreshCw, color: 'text-cyan-400', bgColor: 'bg-cyan-500/20' },
|
||||
];
|
||||
|
||||
// Sort options
|
||||
const SORT_OPTIONS: Array<{
|
||||
value: GitLabMRSortOption;
|
||||
labelKey: string;
|
||||
icon: typeof Clock;
|
||||
}> = [
|
||||
{ value: 'newest', labelKey: 'mrFiltering.sort.newest', icon: Clock },
|
||||
{ value: 'oldest', labelKey: 'mrFiltering.sort.oldest', icon: Clock },
|
||||
{ value: 'largest', labelKey: 'mrFiltering.sort.largest', icon: FileCode },
|
||||
];
|
||||
|
||||
/**
|
||||
* Modern Filter Dropdown Component
|
||||
*/
|
||||
function FilterDropdown<T extends string>({
|
||||
title,
|
||||
icon: Icon,
|
||||
items,
|
||||
selected,
|
||||
onChange,
|
||||
renderItem,
|
||||
renderTrigger,
|
||||
searchable = false,
|
||||
searchPlaceholder,
|
||||
selectedCountLabel,
|
||||
noResultsLabel,
|
||||
clearLabel,
|
||||
}: {
|
||||
title: string;
|
||||
icon: typeof Users;
|
||||
items: T[];
|
||||
selected: T[];
|
||||
onChange: (selected: T[]) => void;
|
||||
renderItem?: (item: T) => React.ReactNode;
|
||||
renderTrigger?: (selected: T[]) => React.ReactNode;
|
||||
searchable?: boolean;
|
||||
searchPlaceholder?: string;
|
||||
selectedCountLabel?: string;
|
||||
noResultsLabel?: string;
|
||||
clearLabel?: string;
|
||||
}) {
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [focusedIndex, setFocusedIndex] = useState(-1);
|
||||
const itemRefs = useRef<(HTMLDivElement | null)[]>([]);
|
||||
|
||||
const toggleItem = useCallback((item: T) => {
|
||||
if (selected.includes(item)) {
|
||||
onChange(selected.filter((s) => s !== item));
|
||||
} else {
|
||||
onChange([...selected, item]);
|
||||
}
|
||||
}, [selected, onChange]);
|
||||
|
||||
const filteredItems = useMemo(() => {
|
||||
if (!searchTerm) return items;
|
||||
return items.filter(item =>
|
||||
item.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
);
|
||||
}, [items, searchTerm]);
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (filteredItems.length === 0) return;
|
||||
|
||||
switch (e.key) {
|
||||
case 'ArrowDown':
|
||||
e.preventDefault();
|
||||
setFocusedIndex(prev =>
|
||||
prev < filteredItems.length - 1 ? prev + 1 : 0
|
||||
);
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
e.preventDefault();
|
||||
setFocusedIndex(prev =>
|
||||
prev > 0 ? prev - 1 : filteredItems.length - 1
|
||||
);
|
||||
break;
|
||||
case 'Enter':
|
||||
case ' ':
|
||||
e.preventDefault();
|
||||
if (focusedIndex >= 0 && focusedIndex < filteredItems.length) {
|
||||
toggleItem(filteredItems[focusedIndex]);
|
||||
}
|
||||
break;
|
||||
case 'Escape':
|
||||
setIsOpen(false);
|
||||
break;
|
||||
}
|
||||
}, [filteredItems, focusedIndex, toggleItem]);
|
||||
|
||||
// Scroll focused item into view for keyboard navigation
|
||||
useEffect(() => {
|
||||
if (focusedIndex >= 0 && itemRefs.current[focusedIndex]) {
|
||||
itemRefs.current[focusedIndex]?.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
}, [focusedIndex]);
|
||||
|
||||
return (
|
||||
<DropdownMenu open={isOpen} onOpenChange={(open) => {
|
||||
setIsOpen(open);
|
||||
if (!open) {
|
||||
setSearchTerm('');
|
||||
setFocusedIndex(-1);
|
||||
}
|
||||
}}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className={cn(
|
||||
"h-8 w-full justify-start border-dashed bg-transparent",
|
||||
selected.length > 0 && "border-solid bg-accent/50"
|
||||
)}
|
||||
>
|
||||
<Icon className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||
<span className="truncate">{title}</span>
|
||||
{selected.length > 0 && (
|
||||
<>
|
||||
<Separator orientation="vertical" className="mx-2 h-4" />
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="rounded-sm px-1 font-normal lg:hidden"
|
||||
>
|
||||
{selected.length}
|
||||
</Badge>
|
||||
<div className="hidden space-x-1 lg:flex flex-1 truncate">
|
||||
{selected.length > 2 ? (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="rounded-sm px-1 font-normal"
|
||||
>
|
||||
{selectedCountLabel}
|
||||
</Badge>
|
||||
) : (
|
||||
renderTrigger ? renderTrigger(selected) : (
|
||||
selected.map((item) => (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
key={item}
|
||||
className="rounded-sm px-1 font-normal"
|
||||
>
|
||||
{item}
|
||||
</Badge>
|
||||
))
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-[240px] p-0">
|
||||
<div className="px-3 py-2 border-b border-border/50">
|
||||
<div className="text-xs font-semibold text-muted-foreground mb-1">
|
||||
{title}
|
||||
</div>
|
||||
{searchable && (
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={searchPlaceholder}
|
||||
className="h-7 text-xs pl-7 bg-muted/50 border-none focus-visible:ring-1 focus-visible:ring-primary/50"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
onKeyDown={(e) => e.stopPropagation()}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="max-h-[300px] overflow-y-auto custom-scrollbar p-1"
|
||||
role="listbox"
|
||||
aria-multiselectable="true"
|
||||
onKeyDown={handleKeyDown}
|
||||
tabIndex={0}
|
||||
>
|
||||
{filteredItems.length === 0 ? (
|
||||
<div className="p-3 text-xs text-muted-foreground text-center">
|
||||
{noResultsLabel}
|
||||
</div>
|
||||
) : (
|
||||
filteredItems.map((item, index) => {
|
||||
const isSelected = selected.includes(item);
|
||||
const isFocused = index === focusedIndex;
|
||||
return (
|
||||
<div
|
||||
key={item}
|
||||
ref={(el) => { itemRefs.current[index] = el; }}
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
className={cn(
|
||||
"relative flex cursor-pointer select-none items-center rounded-sm px-2 py-2 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
isSelected && "bg-accent/50",
|
||||
isFocused && "ring-2 ring-primary/50 bg-accent"
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
toggleItem(item);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
toggleItem(item);
|
||||
}
|
||||
}}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<div className={cn(
|
||||
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary/30",
|
||||
isSelected ? "bg-primary border-primary text-primary-foreground" : "opacity-50 [&_svg]:invisible"
|
||||
)}>
|
||||
<Check className={cn("h-3 w-3")} />
|
||||
</div>
|
||||
{renderItem ? renderItem(item) : item}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
|
||||
{selected.length > 0 && (
|
||||
<div className="p-1 border-t border-border/50 bg-muted/20">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full justify-center text-xs h-7 hover:bg-destructive/10 hover:text-destructive"
|
||||
onClick={() => onChange([])}
|
||||
>
|
||||
{clearLabel}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-select Sort Dropdown Component
|
||||
*/
|
||||
function SortDropdown({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
title,
|
||||
}: {
|
||||
value: GitLabMRSortOption;
|
||||
onChange: (value: GitLabMRSortOption) => void;
|
||||
options: typeof SORT_OPTIONS;
|
||||
title: string;
|
||||
}) {
|
||||
const { t } = useTranslation('gitlab');
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [focusedIndex, setFocusedIndex] = useState(-1);
|
||||
|
||||
const currentOption = options.find((opt) => opt.value === value) || options[0];
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (options.length === 0) return;
|
||||
|
||||
switch (e.key) {
|
||||
case 'ArrowDown':
|
||||
e.preventDefault();
|
||||
setFocusedIndex((prev) => (prev < options.length - 1 ? prev + 1 : 0));
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
e.preventDefault();
|
||||
setFocusedIndex((prev) => (prev > 0 ? prev - 1 : options.length - 1));
|
||||
break;
|
||||
case 'Enter':
|
||||
case ' ':
|
||||
e.preventDefault();
|
||||
if (focusedIndex >= 0 && focusedIndex < options.length) {
|
||||
onChange(options[focusedIndex].value);
|
||||
setIsOpen(false);
|
||||
}
|
||||
break;
|
||||
case 'Escape':
|
||||
setIsOpen(false);
|
||||
break;
|
||||
}
|
||||
}, [options, focusedIndex, onChange]);
|
||||
|
||||
return (
|
||||
<DropdownMenu
|
||||
open={isOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsOpen(open);
|
||||
if (open) {
|
||||
// Focus current selection on open for better keyboard UX
|
||||
setFocusedIndex(options.findIndex((o) => o.value === value));
|
||||
} else {
|
||||
setFocusedIndex(-1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 justify-start border-dashed bg-transparent"
|
||||
>
|
||||
<ArrowUpDown className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||
<span className="truncate">{title}</span>
|
||||
<Separator orientation="vertical" className="mx-2 h-4" />
|
||||
<Badge variant="secondary" className="rounded-sm px-1 font-normal">
|
||||
{t(currentOption.labelKey)}
|
||||
</Badge>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="w-[180px] p-0">
|
||||
<div className="px-3 py-2 border-b border-border/50">
|
||||
<div className="text-xs font-semibold text-muted-foreground">
|
||||
{title}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="p-1"
|
||||
role="listbox"
|
||||
tabIndex={0}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
{options.map((option, index) => {
|
||||
const isSelected = value === option.value;
|
||||
const isFocused = focusedIndex === index;
|
||||
const Icon = option.icon;
|
||||
return (
|
||||
<div
|
||||
key={option.value}
|
||||
role="option"
|
||||
aria-selected={isSelected}
|
||||
className={cn(
|
||||
"relative flex cursor-pointer select-none items-center rounded-sm px-2 py-2 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground",
|
||||
isSelected && "bg-accent/50",
|
||||
isFocused && "bg-accent text-accent-foreground"
|
||||
)}
|
||||
onClick={() => {
|
||||
onChange(option.value);
|
||||
setIsOpen(false);
|
||||
}}
|
||||
>
|
||||
<div className={cn(
|
||||
"mr-2 flex h-4 w-4 items-center justify-center rounded-full border border-primary/30",
|
||||
isSelected ? "bg-primary border-primary text-primary-foreground" : "opacity-50"
|
||||
)}>
|
||||
{isSelected && <Check className="h-2.5 w-2.5" />}
|
||||
</div>
|
||||
<Icon className="mr-2 h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span>{t(option.labelKey)}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
|
||||
export function MRFilterBar({
|
||||
filters,
|
||||
contributors,
|
||||
hasActiveFilters,
|
||||
onSearchChange,
|
||||
onContributorsChange,
|
||||
onStatusesChange,
|
||||
onSortChange,
|
||||
onClearFilters,
|
||||
}: MRFilterBarProps) {
|
||||
const { t } = useTranslation('gitlab');
|
||||
|
||||
// Get status option by value
|
||||
const getStatusOption = (value: GitLabMRStatusFilter) =>
|
||||
STATUS_OPTIONS.find((opt) => opt.value === value);
|
||||
|
||||
return (
|
||||
<div className="px-4 py-2 border-b border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
|
||||
<div className="flex items-center gap-2 h-9">
|
||||
{/* Search Input - Flexible width */}
|
||||
<div className="relative flex-1 max-w-md">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={t('mrFiltering.searchPlaceholder')}
|
||||
value={filters.searchQuery}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
className="h-8 pl-9 bg-background/50 focus:bg-background transition-colors"
|
||||
/>
|
||||
{filters.searchQuery && (
|
||||
<button
|
||||
onClick={() => onSearchChange('')}
|
||||
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
aria-label={t('mrFiltering.clearSearch')}
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator orientation="vertical" className="h-5 mx-1" />
|
||||
|
||||
{/* Contributors Filter */}
|
||||
<div className="flex-1 max-w-[240px]">
|
||||
<FilterDropdown
|
||||
title={t('mrFiltering.contributors')}
|
||||
icon={Users}
|
||||
items={contributors}
|
||||
selected={filters.contributors}
|
||||
onChange={onContributorsChange}
|
||||
searchable={true}
|
||||
searchPlaceholder={t('mrFiltering.searchContributors')}
|
||||
selectedCountLabel={t('mrFiltering.selectedCount', { count: filters.contributors.length })}
|
||||
noResultsLabel={t('mrFiltering.noResultsFound')}
|
||||
clearLabel={t('mrFiltering.clearFilters')}
|
||||
renderItem={(contributor) => (
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<div className="h-5 w-5 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
|
||||
<span className="text-[10px] font-medium text-primary">
|
||||
{contributor.slice(0, 2).toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
<span className="truncate text-sm">{contributor}</span>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Status Filter */}
|
||||
<div className="flex-1 max-w-[240px]">
|
||||
<FilterDropdown
|
||||
title={t('mrFiltering.allStatuses')}
|
||||
icon={Filter}
|
||||
items={STATUS_OPTIONS.map((opt) => opt.value)}
|
||||
selected={filters.statuses}
|
||||
onChange={onStatusesChange}
|
||||
selectedCountLabel={t('mrFiltering.selectedCount', { count: filters.statuses.length })}
|
||||
noResultsLabel={t('mrFiltering.noResultsFound')}
|
||||
clearLabel={t('mrFiltering.clearFilters')}
|
||||
renderItem={(status) => {
|
||||
const option = getStatusOption(status);
|
||||
if (!option) return null;
|
||||
const Icon = option.icon;
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={cn("p-1 rounded-full", option.bgColor)}>
|
||||
<Icon className={cn("h-3 w-3", option.color)} />
|
||||
</div>
|
||||
<span className="text-sm">{t(option.labelKey)}</span>
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
renderTrigger={(selected) => (
|
||||
selected.map(status => {
|
||||
const option = getStatusOption(status);
|
||||
if (!option) return null;
|
||||
const Icon = option.icon;
|
||||
return (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
key={status}
|
||||
className={cn(
|
||||
"rounded-sm px-1 font-normal gap-1",
|
||||
option.bgColor,
|
||||
option.color
|
||||
)}
|
||||
>
|
||||
<Icon className="h-3 w-3" />
|
||||
<span className="truncate max-w-[80px]">{t(option.labelKey)}</span>
|
||||
</Badge>
|
||||
);
|
||||
})
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sort Dropdown */}
|
||||
<div className="flex-shrink-0">
|
||||
<SortDropdown
|
||||
value={filters.sortBy}
|
||||
onChange={onSortChange}
|
||||
options={SORT_OPTIONS}
|
||||
title={t('mrFiltering.sort.label')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Reset All */}
|
||||
{hasActiveFilters && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onClearFilters}
|
||||
className="h-8 px-2 lg:px-3 text-muted-foreground hover:text-foreground ml-auto"
|
||||
>
|
||||
<span className="hidden lg:inline mr-2">{t('mrFiltering.reset')}</span>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,732 @@
|
||||
/**
|
||||
* MR Logs Component
|
||||
*
|
||||
* Displays detailed logs from GitLab merge request review operations.
|
||||
* Shows AI analysis phases, agent activities, and review progress.
|
||||
*
|
||||
* Stub component - implements the same pattern as PRLogs
|
||||
* adapted for GitLab merge requests.
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Terminal,
|
||||
Loader2,
|
||||
FolderOpen,
|
||||
BrainCircuit,
|
||||
FileCheck,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Info,
|
||||
Clock,
|
||||
Activity
|
||||
} from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type {
|
||||
PRLogs,
|
||||
PRLogPhase,
|
||||
PRPhaseLog,
|
||||
PRLogEntry
|
||||
} from '@preload/api/modules/github-api';
|
||||
|
||||
// Type aliases for GitLab compatibility
|
||||
type GitLabMRLogs = PRLogs;
|
||||
type GitLabMRLogPhase = PRLogPhase;
|
||||
type GitLabMRPhaseLog = PRPhaseLog;
|
||||
type GitLabMRLogEntry = PRLogEntry;
|
||||
|
||||
interface MRLogsProps {
|
||||
mrIid: number;
|
||||
logs: GitLabMRLogs | null;
|
||||
isLoading: boolean;
|
||||
isStreaming?: boolean;
|
||||
}
|
||||
|
||||
// TODO: The GITLAB_MR_GET_LOGS IPC handler returns string[] but this component expects PRLogs.
|
||||
// Add a transformation to convert string[] to PRLogs structure in the handler or a data layer.
|
||||
// For now, handle both formats defensively.
|
||||
|
||||
// Phase label translation key mapping
|
||||
const PHASE_LABEL_KEYS: Record<GitLabMRLogPhase, string> = {
|
||||
context: 'gitlab:mrFiltering.logs.contextGathering',
|
||||
analysis: 'gitlab:mrFiltering.logs.aiAnalysis',
|
||||
synthesis: 'gitlab:mrFiltering.logs.synthesis',
|
||||
};
|
||||
|
||||
// Helper function to get phase labels with translation
|
||||
function getPhaseLabel(phase: GitLabMRLogPhase, t: (key: string) => string): string {
|
||||
return t(PHASE_LABEL_KEYS[phase]);
|
||||
}
|
||||
|
||||
const PHASE_ICONS: Record<GitLabMRLogPhase, typeof FolderOpen> = {
|
||||
context: FolderOpen,
|
||||
analysis: BrainCircuit,
|
||||
synthesis: FileCheck
|
||||
};
|
||||
|
||||
const PHASE_COLORS: Record<GitLabMRLogPhase, string> = {
|
||||
context: 'text-blue-500 bg-blue-500/10 border-blue-500/30',
|
||||
analysis: 'text-purple-500 bg-purple-500/10 border-purple-500/30',
|
||||
synthesis: 'text-green-500 bg-green-500/10 border-green-500/30'
|
||||
};
|
||||
|
||||
// Source colors for different log sources
|
||||
const SOURCE_COLORS: Record<string, string> = {
|
||||
'Context': 'bg-blue-500/20 text-blue-400',
|
||||
'AI': 'bg-purple-500/20 text-purple-400',
|
||||
'Orchestrator': 'bg-orange-500/20 text-orange-400',
|
||||
'ParallelOrchestrator': 'bg-orange-500/20 text-orange-400',
|
||||
'Followup': 'bg-cyan-500/20 text-cyan-400',
|
||||
'ParallelFollowup': 'bg-cyan-500/20 text-cyan-400',
|
||||
'BotDetector': 'bg-amber-500/20 text-amber-400',
|
||||
'Progress': 'bg-green-500/20 text-green-400',
|
||||
'MR Review Engine': 'bg-indigo-500/20 text-indigo-400',
|
||||
'Summary': 'bg-emerald-500/20 text-emerald-400',
|
||||
'Agent:logic-reviewer': 'bg-blue-600/20 text-blue-400',
|
||||
'Agent:quality-reviewer': 'bg-indigo-600/20 text-indigo-400',
|
||||
'Agent:security-reviewer': 'bg-red-600/20 text-red-400',
|
||||
'Agent:ai-triage-reviewer': 'bg-slate-500/20 text-slate-400',
|
||||
'Agent:resolution-verifier': 'bg-teal-600/20 text-teal-400',
|
||||
'Agent:new-code-reviewer': 'bg-cyan-600/20 text-cyan-400',
|
||||
'Agent:comment-analyzer': 'bg-gray-500/20 text-gray-400',
|
||||
'Specialist:security': 'bg-red-600/20 text-red-400',
|
||||
'Specialist:quality': 'bg-indigo-600/20 text-indigo-400',
|
||||
'Specialist:logic': 'bg-blue-600/20 text-blue-400',
|
||||
'Specialist:codebase-fit': 'bg-emerald-600/20 text-emerald-400',
|
||||
'FindingValidator': 'bg-amber-600/20 text-amber-400',
|
||||
'default': 'bg-muted text-muted-foreground'
|
||||
};
|
||||
|
||||
// Helper type for grouped agent entries
|
||||
interface AgentGroup {
|
||||
agentName: string;
|
||||
entries: GitLabMRLogEntry[];
|
||||
}
|
||||
|
||||
// Patterns that indicate orchestrator tool activity (vs. important messages)
|
||||
const TOOL_ACTIVITY_PATTERNS = [
|
||||
/^Reading /,
|
||||
/^Searching for /,
|
||||
/^Finding files /,
|
||||
/^Running: /,
|
||||
/^Editing /,
|
||||
/^Writing /,
|
||||
/^Using tool: /,
|
||||
/^Processing\.\.\. \(\d+ messages/,
|
||||
/^Tool result \[/,
|
||||
];
|
||||
|
||||
function isToolActivityLog(content: string): boolean {
|
||||
return TOOL_ACTIVITY_PATTERNS.some(pattern => pattern.test(content));
|
||||
}
|
||||
|
||||
// Group entries by: agents, orchestrator activity, and other entries
|
||||
function groupEntriesByAgent(entries: GitLabMRLogEntry[]): {
|
||||
agentGroups: AgentGroup[];
|
||||
orchestratorActivity: GitLabMRLogEntry[];
|
||||
otherEntries: GitLabMRLogEntry[];
|
||||
} {
|
||||
const agentMap = new Map<string, GitLabMRLogEntry[]>();
|
||||
const orchestratorActivity: GitLabMRLogEntry[] = [];
|
||||
const otherEntries: GitLabMRLogEntry[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.source?.startsWith('Agent:') || entry.source?.startsWith('Specialist:')) {
|
||||
const existing = agentMap.get(entry.source) || [];
|
||||
existing.push(entry);
|
||||
agentMap.set(entry.source, existing);
|
||||
} else if (
|
||||
(entry.source === 'ParallelOrchestrator' || entry.source === 'ParallelFollowup') &&
|
||||
isToolActivityLog(entry.content)
|
||||
) {
|
||||
orchestratorActivity.push(entry);
|
||||
} else {
|
||||
otherEntries.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
const agentGroups: AgentGroup[] = Array.from(agentMap.entries())
|
||||
.map(([agentName, agentEntries]) => ({ agentName, entries: agentEntries }))
|
||||
.sort((a, b) => {
|
||||
const aTime = a.entries[0]?.timestamp || '';
|
||||
const bTime = b.entries[0]?.timestamp || '';
|
||||
return aTime.localeCompare(bTime);
|
||||
});
|
||||
|
||||
return { agentGroups, orchestratorActivity, otherEntries };
|
||||
}
|
||||
|
||||
export function MRLogs({ mrIid, logs, isLoading, isStreaming = false }: MRLogsProps) {
|
||||
const { t } = useTranslation(['gitlab']);
|
||||
const [expandedPhases, setExpandedPhases] = useState<Set<GitLabMRLogPhase>>(new Set(['analysis']));
|
||||
const [expandedAgents, setExpandedAgents] = useState<Set<string>>(new Set());
|
||||
|
||||
// TODO: Remove this fallback when GITLAB_MR_GET_LOGS returns structured PRLogs
|
||||
const logsAsArray = Array.isArray(logs) ? logs : null;
|
||||
|
||||
const togglePhase = (phase: GitLabMRLogPhase) => {
|
||||
setExpandedPhases(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(phase)) {
|
||||
next.delete(phase);
|
||||
} else {
|
||||
next.add(phase);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleAgent = (agentKey: string) => {
|
||||
setExpandedAgents(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(agentKey)) {
|
||||
next.delete(agentKey);
|
||||
} else {
|
||||
next.add(agentKey);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-y-auto scrollbar-thin scrollbar-thumb-border scrollbar-track-transparent">
|
||||
<div className="p-4 space-y-2">
|
||||
{isLoading && !logs ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : logsAsArray ? (
|
||||
// Fallback for string[] format (current IPC handler return type)
|
||||
// TODO: Remove when GITLAB_MR_GET_LOGS returns structured PRLogs
|
||||
<>
|
||||
<div className="text-sm text-muted-foreground mb-4">
|
||||
{t('gitlab:mrFiltering.logs.mrLabel', { iid: mrIid })}
|
||||
</div>
|
||||
<div className="space-y-1 text-xs font-mono text-muted-foreground">
|
||||
{logsAsArray.map((log, idx) => (
|
||||
<div key={idx} className="py-0.5">{log}</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : logs ? (
|
||||
<>
|
||||
{/* Logs header */}
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="text-sm text-muted-foreground flex items-center gap-2">
|
||||
{t('gitlab:mrFiltering.logs.mrLabel', { iid: mrIid })}
|
||||
{logs.is_followup && <Badge variant="outline" className="text-xs">{t('gitlab:mrFiltering.logs.followup')}</Badge>}
|
||||
{isStreaming && (
|
||||
<Badge variant="outline" className="text-xs bg-blue-500/10 text-blue-500 border-blue-500/30 flex items-center gap-1">
|
||||
<Loader2 className="h-2.5 w-2.5 animate-spin" />
|
||||
{t('gitlab:mrFiltering.logs.live')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(logs.updated_at).toLocaleString(undefined, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Phase-based collapsible logs */}
|
||||
{(['context', 'analysis', 'synthesis'] as GitLabMRLogPhase[]).map((phase) => (
|
||||
<PhaseLogSection
|
||||
key={phase}
|
||||
phase={phase}
|
||||
phaseLog={logs.phases[phase]}
|
||||
isExpanded={expandedPhases.has(phase)}
|
||||
onToggle={() => togglePhase(phase)}
|
||||
isStreaming={isStreaming}
|
||||
expandedAgents={expandedAgents}
|
||||
onToggleAgent={toggleAgent}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
) : isStreaming ? (
|
||||
<div className="text-center text-sm text-muted-foreground py-8">
|
||||
<Loader2 className="mx-auto mb-2 h-8 w-8 animate-spin text-blue-500" />
|
||||
<p>{t('gitlab:mrFiltering.logs.waitingForLogs')}</p>
|
||||
<p className="text-xs mt-1">{t('gitlab:mrFiltering.logs.reviewStarting')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center text-sm text-muted-foreground py-8">
|
||||
<Terminal className="mx-auto mb-2 h-8 w-8 opacity-50" />
|
||||
<p>{t('gitlab:mrFiltering.logs.noLogsAvailable')}</p>
|
||||
<p className="text-xs mt-1">{t('gitlab:mrFiltering.logs.runReviewGenerateLogs')}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Phase Log Section Component
|
||||
interface PhaseLogSectionProps {
|
||||
phase: GitLabMRLogPhase;
|
||||
phaseLog: GitLabMRPhaseLog | null;
|
||||
isExpanded: boolean;
|
||||
onToggle: () => void;
|
||||
isStreaming?: boolean;
|
||||
expandedAgents: Set<string>;
|
||||
onToggleAgent: (agentKey: string) => void;
|
||||
}
|
||||
|
||||
function PhaseLogSection({ phase, phaseLog, isExpanded, onToggle, isStreaming = false, expandedAgents, onToggleAgent }: PhaseLogSectionProps) {
|
||||
const { t } = useTranslation(['gitlab']);
|
||||
const Icon = PHASE_ICONS[phase];
|
||||
const status = phaseLog?.status || 'pending';
|
||||
const hasEntries = (phaseLog?.entries.length || 0) > 0;
|
||||
|
||||
const getStatusBadge = () => {
|
||||
if (status === 'active' || (isStreaming && status === 'pending')) {
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs bg-info/10 text-info border-info/30 flex items-center gap-1">
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
{isStreaming ? t('gitlab:mrFiltering.logs.streaming') : t('gitlab:mrFiltering.logs.running')}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
if (isStreaming && status === 'completed' && !hasEntries) {
|
||||
return (
|
||||
<Badge variant="secondary" className="text-xs text-muted-foreground">
|
||||
{t('gitlab:mrFiltering.logs.pending')}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs bg-success/10 text-success border-success/30 flex items-center gap-1">
|
||||
<CheckCircle2 className="h-3 w-3" />
|
||||
{t('gitlab:mrFiltering.logs.complete')}
|
||||
</Badge>
|
||||
);
|
||||
case 'failed':
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs bg-destructive/10 text-destructive border-destructive/30 flex items-center gap-1">
|
||||
<XCircle className="h-3 w-3" />
|
||||
{t('gitlab:mrFiltering.logs.failed')}
|
||||
</Badge>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<Badge variant="secondary" className="text-xs text-muted-foreground">
|
||||
{t('gitlab:mrFiltering.logs.pending')}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Collapsible open={isExpanded} onOpenChange={onToggle}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<button
|
||||
className={cn(
|
||||
'w-full flex items-center justify-between p-3 rounded-lg border transition-colors',
|
||||
'hover:bg-secondary/50',
|
||||
status === 'active' && PHASE_COLORS[phase],
|
||||
status === 'completed' && 'border-success/30 bg-success/5',
|
||||
status === 'failed' && 'border-destructive/30 bg-destructive/5',
|
||||
status === 'pending' && 'border-border bg-secondary/30'
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
<Icon className={cn('h-4 w-4', status === 'active' ? PHASE_COLORS[phase].split(' ')[0] : 'text-muted-foreground')} />
|
||||
<span className="font-medium text-sm">{getPhaseLabel(phase, t)}</span>
|
||||
{hasEntries && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
({phaseLog?.entries.length} {t('gitlab:mrFiltering.logs.entries')})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{getStatusBadge()}
|
||||
</div>
|
||||
</button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="mt-1 ml-6 border-l-2 border-border pl-4 py-2 space-y-2">
|
||||
{!hasEntries ? (
|
||||
<p className="text-xs text-muted-foreground italic">{t('gitlab:mrFiltering.logs.noLogsYet')}</p>
|
||||
) : (
|
||||
<GroupedLogEntries
|
||||
entries={phaseLog?.entries || []}
|
||||
phase={phase}
|
||||
expandedAgents={expandedAgents}
|
||||
onToggleAgent={onToggleAgent}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
|
||||
// Grouped Log Entries Component
|
||||
interface GroupedLogEntriesProps {
|
||||
entries: GitLabMRLogEntry[];
|
||||
phase: GitLabMRLogPhase;
|
||||
expandedAgents: Set<string>;
|
||||
onToggleAgent: (agentKey: string) => void;
|
||||
}
|
||||
|
||||
function GroupedLogEntries({ entries, phase, expandedAgents, onToggleAgent }: GroupedLogEntriesProps) {
|
||||
const { agentGroups, orchestratorActivity, otherEntries } = groupEntriesByAgent(entries);
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{otherEntries.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
{otherEntries.map((entry, idx) => (
|
||||
<LogEntry key={`other-${entry.timestamp}-${idx}`} entry={entry} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{orchestratorActivity.length > 0 && (
|
||||
<OrchestratorActivitySection
|
||||
entries={orchestratorActivity}
|
||||
phase={phase}
|
||||
isExpanded={expandedAgents.has(`${phase}-orchestrator-activity`)}
|
||||
onToggle={() => onToggleAgent(`${phase}-orchestrator-activity`)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{agentGroups.map((group) => (
|
||||
<AgentLogGroup
|
||||
key={`${phase}-${group.agentName}`}
|
||||
group={group}
|
||||
phase={phase}
|
||||
isExpanded={expandedAgents.has(`${phase}-${group.agentName}`)}
|
||||
onToggle={() => onToggleAgent(`${phase}-${group.agentName}`)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Orchestrator Activity Section
|
||||
interface OrchestratorActivitySectionProps {
|
||||
entries: GitLabMRLogEntry[];
|
||||
phase: GitLabMRLogPhase;
|
||||
isExpanded: boolean;
|
||||
onToggle: () => void;
|
||||
}
|
||||
|
||||
function OrchestratorActivitySection({ entries, isExpanded, onToggle }: OrchestratorActivitySectionProps) {
|
||||
const { t } = useTranslation(['gitlab']);
|
||||
|
||||
const readCount = entries.filter(e => e.content.startsWith('Reading ')).length;
|
||||
const searchCount = entries.filter(e => e.content.startsWith('Searching for ')).length;
|
||||
const otherCount = entries.length - readCount - searchCount;
|
||||
|
||||
const summaryParts: string[] = [];
|
||||
if (readCount > 0) {
|
||||
summaryParts.push(t('gitlab:mrFiltering.logs.filesRead', { count: readCount }));
|
||||
}
|
||||
if (searchCount > 0) {
|
||||
summaryParts.push(t('gitlab:mrFiltering.logs.searches', { count: searchCount }));
|
||||
}
|
||||
if (otherCount > 0) {
|
||||
summaryParts.push(t('gitlab:mrFiltering.logs.other', { count: otherCount }));
|
||||
}
|
||||
const summary = summaryParts.join(', ') || t('gitlab:mrFiltering.logs.operations', { count: entries.length });
|
||||
|
||||
return (
|
||||
<div className="rounded-md border border-border/50 bg-secondary/10 overflow-hidden">
|
||||
<button
|
||||
onClick={onToggle}
|
||||
className={cn(
|
||||
'w-full flex items-center justify-between p-2 transition-colors',
|
||||
'hover:bg-secondary/30',
|
||||
isExpanded && 'bg-secondary/20'
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-3 w-3 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronRight className="h-3 w-3 text-muted-foreground" />
|
||||
)}
|
||||
<Activity className="h-3 w-3 text-orange-400" />
|
||||
<span className="text-xs text-muted-foreground">{t('gitlab:mrFiltering.logs.agentActivity')}</span>
|
||||
</div>
|
||||
<Badge variant="outline" className="text-[9px] px-1.5 py-0 bg-orange-500/10 text-orange-400 border-orange-500/30">
|
||||
{summary}
|
||||
</Badge>
|
||||
</button>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="border-t border-border/30 p-2 space-y-0.5 max-h-[300px] overflow-y-auto">
|
||||
{entries.map((entry, idx) => (
|
||||
<div key={`activity-${entry.timestamp}-${idx}`} className="flex items-start gap-2 text-[10px] text-muted-foreground/80 py-0.5">
|
||||
<span className="text-muted-foreground/50 tabular-nums shrink-0">
|
||||
{new Date(entry.timestamp).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
|
||||
</span>
|
||||
<span className="break-words">{entry.content}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Agent Log Group Component
|
||||
interface AgentLogGroupProps {
|
||||
group: AgentGroup;
|
||||
phase: GitLabMRLogPhase;
|
||||
isExpanded: boolean;
|
||||
onToggle: () => void;
|
||||
}
|
||||
|
||||
const SKIP_AS_SUMMARY_PATTERNS = [
|
||||
/^Starting analysis\.\.\.$/,
|
||||
/^Processing SDK stream\.\.\.$/,
|
||||
/^Processing\.\.\./,
|
||||
/^Awaiting response stream\.\.\.$/,
|
||||
];
|
||||
|
||||
function isBoringSummary(content: string): boolean {
|
||||
return SKIP_AS_SUMMARY_PATTERNS.some(pattern => pattern.test(content));
|
||||
}
|
||||
|
||||
function findSummaryEntry(entries: GitLabMRLogEntry[]): { summaryEntry: GitLabMRLogEntry | undefined; otherEntries: GitLabMRLogEntry[] } {
|
||||
if (entries.length === 0) return { summaryEntry: undefined, otherEntries: [] };
|
||||
|
||||
const completeEntry = entries.find(e => e.content.startsWith('Complete:'));
|
||||
if (completeEntry) {
|
||||
return {
|
||||
summaryEntry: completeEntry,
|
||||
otherEntries: entries.filter(e => e !== completeEntry),
|
||||
};
|
||||
}
|
||||
|
||||
const aiResponseEntry = entries.find(e => e.content.startsWith('AI response:'));
|
||||
if (aiResponseEntry) {
|
||||
return {
|
||||
summaryEntry: aiResponseEntry,
|
||||
otherEntries: entries.filter(e => e !== aiResponseEntry),
|
||||
};
|
||||
}
|
||||
|
||||
const meaningfulEntry = entries.find(e => !isBoringSummary(e.content));
|
||||
if (meaningfulEntry) {
|
||||
return {
|
||||
summaryEntry: meaningfulEntry,
|
||||
otherEntries: entries.filter(e => e !== meaningfulEntry),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
summaryEntry: entries[0],
|
||||
otherEntries: entries.slice(1),
|
||||
};
|
||||
}
|
||||
|
||||
function AgentLogGroup({ group, isExpanded, onToggle }: AgentLogGroupProps) {
|
||||
const { t } = useTranslation(['common']);
|
||||
const { agentName, entries } = group;
|
||||
const { summaryEntry, otherEntries } = findSummaryEntry(entries);
|
||||
const hasMoreEntries = otherEntries.length > 0;
|
||||
const displayName = agentName.replace('Agent:', '').replace('Specialist:', '');
|
||||
|
||||
const getSourceColor = (source: string) => {
|
||||
return SOURCE_COLORS[source] || SOURCE_COLORS.default;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-md border border-border/50 bg-secondary/20 overflow-hidden">
|
||||
<div className="p-2 space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn('text-[10px] px-1.5 py-0.5', getSourceColor(agentName))}
|
||||
>
|
||||
{displayName}
|
||||
</Badge>
|
||||
{hasMoreEntries && (
|
||||
<button
|
||||
onClick={onToggle}
|
||||
className={cn(
|
||||
'flex items-center gap-1 text-[10px] px-2 py-0.5 rounded transition-colors',
|
||||
'text-muted-foreground hover:text-foreground hover:bg-secondary/50',
|
||||
isExpanded && 'bg-secondary/50 text-foreground'
|
||||
)}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<>
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
<span>{t('gitlab:mrFiltering.logs.hideMore', { count: otherEntries.length })}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ChevronRight className="h-3 w-3" />
|
||||
<span>{t('gitlab:mrFiltering.logs.showMore', { count: otherEntries.length })}</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{summaryEntry && (
|
||||
<LogEntry entry={{ ...summaryEntry, source: undefined }} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{hasMoreEntries && isExpanded && (
|
||||
<div className="border-t border-border/30 bg-secondary/10 p-2 space-y-1">
|
||||
{otherEntries.map((entry, idx) => (
|
||||
<LogEntry key={`${entry.timestamp}-${idx}`} entry={{ ...entry, source: undefined }} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Log Entry Component
|
||||
interface LogEntryProps {
|
||||
entry: GitLabMRLogEntry;
|
||||
}
|
||||
|
||||
function LogEntry({ entry }: LogEntryProps) {
|
||||
const { t } = useTranslation(['gitlab']);
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const hasDetail = Boolean(entry.detail);
|
||||
|
||||
const formatTime = (timestamp: string) => {
|
||||
try {
|
||||
const date = new Date(timestamp);
|
||||
return date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
const getSourceColor = (source: string | undefined) => {
|
||||
if (!source) return SOURCE_COLORS.default;
|
||||
return SOURCE_COLORS[source] || SOURCE_COLORS.default;
|
||||
};
|
||||
|
||||
if (entry.type === 'error') {
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<div className="flex items-start gap-2 text-xs text-destructive bg-destructive/10 rounded-md px-2 py-1">
|
||||
<XCircle className="h-3 w-3 mt-0.5 shrink-0" />
|
||||
<span className="break-words flex-1">{entry.content}</span>
|
||||
{hasDetail && (
|
||||
<button
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
className={cn(
|
||||
'flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded shrink-0',
|
||||
'text-muted-foreground hover:text-foreground hover:bg-secondary/50 transition-colors',
|
||||
isExpanded && 'bg-secondary/50'
|
||||
)}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<>
|
||||
<ChevronDown className="h-2.5 w-2.5" />
|
||||
<span>{t('gitlab:mrFiltering.logs.less')}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ChevronRight className="h-2.5 w-2.5" />
|
||||
<span>{t('gitlab:mrFiltering.logs.more')}</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{hasDetail && isExpanded && (
|
||||
<div className="mt-1.5 ml-4 p-2 bg-destructive/5 rounded-md border border-destructive/20 overflow-x-auto">
|
||||
<pre className="text-[10px] text-destructive/80 whitespace-pre-wrap break-words font-mono max-h-[300px] overflow-y-auto">
|
||||
{entry.detail}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === 'success') {
|
||||
return (
|
||||
<div className="flex items-start gap-2 text-xs text-success bg-success/10 rounded-md px-2 py-1">
|
||||
<CheckCircle2 className="h-3 w-3 mt-0.5 shrink-0" />
|
||||
<span className="break-words flex-1">{entry.content}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (entry.type === 'info') {
|
||||
return (
|
||||
<div className="flex items-start gap-2 text-xs text-info bg-info/10 rounded-md px-2 py-1">
|
||||
<Info className="h-3 w-3 mt-0.5 shrink-0" />
|
||||
<span className="break-words flex-1">{entry.content}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<div className="flex items-start gap-2 text-xs text-muted-foreground py-0.5">
|
||||
<span className="text-[10px] text-muted-foreground/60 tabular-nums shrink-0">
|
||||
{formatTime(entry.timestamp)}
|
||||
</span>
|
||||
{entry.source && (
|
||||
<Badge variant="outline" className={cn('text-[9px] px-1 py-0 shrink-0', getSourceColor(entry.source))}>
|
||||
{entry.source}
|
||||
</Badge>
|
||||
)}
|
||||
<span className="break-words whitespace-pre-wrap flex-1">{entry.content}</span>
|
||||
{hasDetail && (
|
||||
<button
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
className={cn(
|
||||
'flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded shrink-0',
|
||||
'text-muted-foreground hover:text-foreground hover:bg-secondary/50 transition-colors',
|
||||
isExpanded && 'bg-secondary/50'
|
||||
)}
|
||||
>
|
||||
{isExpanded ? (
|
||||
<>
|
||||
<ChevronDown className="h-2.5 w-2.5" />
|
||||
<span>{t('gitlab:mrFiltering.logs.less')}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ChevronRight className="h-2.5 w-2.5" />
|
||||
<span>{t('gitlab:mrFiltering.logs.more')}</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{hasDetail && isExpanded && (
|
||||
<div className="mt-1.5 ml-12 p-2 bg-secondary/30 rounded-md border border-border/50 overflow-x-auto">
|
||||
<pre className="text-[10px] text-muted-foreground whitespace-pre-wrap break-words font-mono max-h-[300px] overflow-y-auto">
|
||||
{entry.detail}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import { CheckCircle2, Circle, XCircle, Loader2, AlertTriangle, GitMerge, HelpCircle } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { ChecksStatus, ReviewsStatus, MergeableState } from '@shared/types/pr-status';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
/**
|
||||
* CI Status Icon Component
|
||||
* Displays an icon representing the CI checks status
|
||||
*/
|
||||
interface CIStatusIconProps {
|
||||
status: ChecksStatus;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function CIStatusIcon({ status, className }: CIStatusIconProps) {
|
||||
const baseClasses = 'h-4 w-4';
|
||||
|
||||
switch (status) {
|
||||
case 'success':
|
||||
return <CheckCircle2 className={cn(baseClasses, 'text-emerald-400', className)} />;
|
||||
case 'pending':
|
||||
return <Loader2 className={cn(baseClasses, 'text-amber-400 animate-spin', className)} />;
|
||||
case 'failure':
|
||||
return <XCircle className={cn(baseClasses, 'text-red-400', className)} />;
|
||||
default:
|
||||
return <Circle className={cn(baseClasses, 'text-muted-foreground/50', className)} />;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Review Status Badge Component
|
||||
* Displays a badge representing the review status
|
||||
*/
|
||||
interface ReviewStatusBadgeProps {
|
||||
status: ReviewsStatus;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function ReviewStatusBadge({ status, className }: ReviewStatusBadgeProps) {
|
||||
const { t } = useTranslation('common');
|
||||
|
||||
switch (status) {
|
||||
case 'approved':
|
||||
return (
|
||||
<Badge variant="success" className={cn('gap-1', className)}>
|
||||
<CheckCircle2 className="h-3 w-3" />
|
||||
{t('prStatus.review.approved')}
|
||||
</Badge>
|
||||
);
|
||||
case 'changes_requested':
|
||||
return (
|
||||
<Badge variant="destructive" className={cn('gap-1', className)}>
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
{t('prStatus.review.changesRequested')}
|
||||
</Badge>
|
||||
);
|
||||
case 'pending':
|
||||
return (
|
||||
<Badge variant="warning" className={cn('gap-1', className)}>
|
||||
<Circle className="h-3 w-3" />
|
||||
{t('prStatus.review.pending')}
|
||||
</Badge>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge Readiness Icon Component
|
||||
* Displays an icon representing the merge readiness state
|
||||
*/
|
||||
interface MergeReadinessIconProps {
|
||||
state: MergeableState;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function MergeReadinessIcon({ state, className }: MergeReadinessIconProps) {
|
||||
const baseClasses = 'h-4 w-4';
|
||||
|
||||
switch (state) {
|
||||
case 'clean':
|
||||
return <GitMerge className={cn(baseClasses, 'text-emerald-400', className)} />;
|
||||
case 'dirty':
|
||||
return <AlertTriangle className={cn(baseClasses, 'text-amber-400', className)} />;
|
||||
case 'blocked':
|
||||
return <HelpCircle className={cn(baseClasses, 'text-red-400', className)} />;
|
||||
default:
|
||||
return <HelpCircle className={cn(baseClasses, 'text-muted-foreground/50', className)} />;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* StatusIndicator Props
|
||||
*/
|
||||
export interface MRStatusIndicatorProps {
|
||||
/** CI checks status */
|
||||
checksStatus?: ChecksStatus | null;
|
||||
/** Review status */
|
||||
reviewsStatus?: ReviewsStatus | null;
|
||||
/** Raw GitLab merge status string (e.g., 'can_be_merged', 'cannot_be_merged', 'checking') */
|
||||
mergeStatus?: string | null;
|
||||
/** Additional CSS classes */
|
||||
className?: string;
|
||||
/** Whether to show a compact version (icons only) */
|
||||
compact?: boolean;
|
||||
/** Whether to show the merge readiness indicator */
|
||||
showMergeStatus?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* StatusIndicator Component
|
||||
*
|
||||
* Displays CI status (success/pending/failure icons), review status
|
||||
* (approved/changes_requested/pending badges), and merge readiness
|
||||
* for GitLab MRs in the MR list view.
|
||||
*
|
||||
* Used alongside the existing MRStatusFlow dots component to provide
|
||||
* real-time MR status from GitLab's API polling.
|
||||
*/
|
||||
// Comprehensive merge status mapping for all GitLab detailed_merge_status values
|
||||
const mergeKeyMap: Record<string, string> = {
|
||||
can_be_merged: 'ready',
|
||||
mergeable: 'ready',
|
||||
cannot_be_merged: 'conflict',
|
||||
conflict: 'conflict',
|
||||
need_rebase: 'conflict',
|
||||
checking: 'checking',
|
||||
// Additional GitLab merge status values
|
||||
policies: 'blocked',
|
||||
merge_when_pipeline_succeeds: 'merging',
|
||||
pipeline_failed: 'conflict',
|
||||
pipeline_success: 'ready',
|
||||
cant_be_merged: 'conflict',
|
||||
blocked: 'blocked',
|
||||
unchecked: 'checking',
|
||||
web_ide: 'checking',
|
||||
ci_must_pass: 'blocked',
|
||||
ci_still_running: 'blocked',
|
||||
discussions_not_resolved: 'blocked',
|
||||
draft_status: 'blocked',
|
||||
not_open: 'blocked',
|
||||
merge_request_blocked: 'blocked',
|
||||
// Safe default for unknown statuses
|
||||
};
|
||||
|
||||
// Map GitLab merge status to MergeableState for the icon
|
||||
const gitlabToMergeableState: Record<string, MergeableState> = {
|
||||
can_be_merged: 'clean',
|
||||
mergeable: 'clean',
|
||||
cannot_be_merged: 'dirty',
|
||||
conflict: 'dirty',
|
||||
need_rebase: 'dirty',
|
||||
checking: 'blocked',
|
||||
// Additional GitLab merge status values
|
||||
policies: 'blocked',
|
||||
merge_when_pipeline_succeeds: 'clean',
|
||||
pipeline_failed: 'dirty',
|
||||
pipeline_success: 'clean',
|
||||
cant_be_merged: 'dirty',
|
||||
blocked: 'blocked',
|
||||
unchecked: 'blocked',
|
||||
web_ide: 'blocked',
|
||||
ci_must_pass: 'blocked',
|
||||
ci_still_running: 'blocked',
|
||||
discussions_not_resolved: 'blocked',
|
||||
draft_status: 'blocked',
|
||||
not_open: 'blocked',
|
||||
merge_request_blocked: 'blocked',
|
||||
// Safe default
|
||||
};
|
||||
|
||||
export function MRStatusIndicator({
|
||||
checksStatus,
|
||||
reviewsStatus,
|
||||
mergeStatus,
|
||||
className,
|
||||
compact = false,
|
||||
showMergeStatus = true,
|
||||
}: MRStatusIndicatorProps) {
|
||||
const { t } = useTranslation('common');
|
||||
|
||||
// Check if any renderable status data is available
|
||||
const showChecks = Boolean(checksStatus && checksStatus !== 'none');
|
||||
const showReviews = Boolean(reviewsStatus && reviewsStatus !== 'none');
|
||||
const showMerge = Boolean(mergeStatus);
|
||||
|
||||
// Don't render if no renderable status data is available
|
||||
if (!showChecks && !showReviews && !showMerge) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const mergeKey = mergeStatus ? mergeKeyMap[mergeStatus] : null;
|
||||
const mergeableState = mergeStatus ? gitlabToMergeableState[mergeStatus] : null;
|
||||
|
||||
return (
|
||||
<div className={cn('flex items-center gap-2', className)}>
|
||||
{/* CI Status */}
|
||||
{showChecks && (
|
||||
<div className="flex items-center gap-1" title={t(`mrStatus.ci.${checksStatus}`)}>
|
||||
<CIStatusIcon status={checksStatus!} />
|
||||
{!compact && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t(`mrStatus.ci.${checksStatus}`)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Review Status */}
|
||||
{showReviews && (
|
||||
compact ? (
|
||||
<ReviewStatusBadge status={reviewsStatus!} className="px-1.5 py-0" />
|
||||
) : (
|
||||
<ReviewStatusBadge status={reviewsStatus!} />
|
||||
)
|
||||
)}
|
||||
|
||||
{/* Merge Readiness */}
|
||||
{showMergeStatus && mergeKey && mergeableState && (
|
||||
<div className="flex items-center gap-1" title={t(`mrStatus.merge.${mergeKey}`)}>
|
||||
<MergeReadinessIcon state={mergeableState} />
|
||||
{!compact && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t(`mrStatus.merge.${mergeKey}`)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact Status Indicator
|
||||
*
|
||||
* A minimal version showing just icons with tooltips.
|
||||
* Useful for tight spaces in the MR list.
|
||||
*/
|
||||
export function CompactMRStatusIndicator(props: Omit<MRStatusIndicatorProps, 'compact'>) {
|
||||
return <MRStatusIndicator {...props} compact />;
|
||||
}
|
||||
|
||||
// Re-export sub-components for flexibility
|
||||
export { CIStatusIcon, ReviewStatusBadge, MergeReadinessIcon };
|
||||
@@ -6,3 +6,6 @@ export { ReviewFindings } from './ReviewFindings';
|
||||
export { FindingItem } from './FindingItem';
|
||||
export { FindingsSummary } from './FindingsSummary';
|
||||
export { SeverityGroupHeader } from './SeverityGroupHeader';
|
||||
export { MRFilterBar } from './MRFilterBar';
|
||||
export { MRStatusIndicator, CompactMRStatusIndicator } from './StatusIndicator';
|
||||
export { MRLogs } from './MRLogs';
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from './useGitLabMRs';
|
||||
export * from './useFindingSelection';
|
||||
export * from './useGitLabMRFiltering';
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* Hook for filtering and searching GitLab MRs
|
||||
*
|
||||
* Stub hook - implements the same pattern as usePRFiltering
|
||||
* adapted for GitLab merge requests.
|
||||
*
|
||||
* NOTE: This hook and MRFilterBar are reserved for future filtering functionality.
|
||||
* They are not currently integrated into the GitLab MRs UI but are retained
|
||||
* for when filtering/search features are implemented.
|
||||
*
|
||||
* TODO: Integrate MRFilterBar into GitLabMergeRequests.tsx by:
|
||||
* 1. Importing useGitLabMRFiltering hook
|
||||
* 2. Importing MRFilterBar component from ./components/MRFilterBar
|
||||
* 3. Adding filter state management to GitLabMergeRequests component
|
||||
* 4. Passing filtered MRs to MergeRequestList instead of raw mrs
|
||||
* 5. Adding UI toggle for filter bar visibility
|
||||
*/
|
||||
|
||||
import { useMemo, useState, useCallback } from 'react';
|
||||
import type {
|
||||
GitLabMergeRequest,
|
||||
GitLabMRReviewResult,
|
||||
GitLabMRReviewProgress,
|
||||
GitLabNewCommitsCheck
|
||||
} from '@shared/types';
|
||||
|
||||
export type GitLabMRStatusFilter =
|
||||
| 'all'
|
||||
| 'reviewing'
|
||||
| 'not_reviewed'
|
||||
| 'reviewed'
|
||||
| 'posted'
|
||||
| 'changes_requested'
|
||||
| 'ready_to_merge'
|
||||
| 'ready_for_followup';
|
||||
|
||||
export type GitLabMRSortOption = 'newest' | 'oldest' | 'largest';
|
||||
|
||||
export interface GitLabMRFilterState {
|
||||
searchQuery: string;
|
||||
contributors: string[];
|
||||
statuses: GitLabMRStatusFilter[];
|
||||
sortBy: GitLabMRSortOption;
|
||||
}
|
||||
|
||||
interface GitLabMRReviewInfo {
|
||||
isReviewing: boolean;
|
||||
result: GitLabMRReviewResult | null;
|
||||
newCommitsCheck?: GitLabNewCommitsCheck | null;
|
||||
}
|
||||
|
||||
const DEFAULT_FILTERS: GitLabMRFilterState = {
|
||||
searchQuery: '',
|
||||
contributors: [],
|
||||
statuses: [],
|
||||
sortBy: 'newest',
|
||||
};
|
||||
|
||||
/**
|
||||
* Determine the computed status of an MR based on its review state
|
||||
*/
|
||||
function getMRComputedStatus(
|
||||
reviewInfo: GitLabMRReviewInfo | null
|
||||
): GitLabMRStatusFilter {
|
||||
// Check if currently reviewing (highest priority)
|
||||
if (reviewInfo?.isReviewing) {
|
||||
return 'reviewing';
|
||||
}
|
||||
|
||||
if (!reviewInfo?.result) {
|
||||
return 'not_reviewed';
|
||||
}
|
||||
|
||||
const result = reviewInfo.result;
|
||||
const hasPosted = Boolean(result.hasPostedFindings);
|
||||
// Use overallStatus from review result as source of truth, fallback to severity check
|
||||
const hasBlockingFindings =
|
||||
result.overallStatus === 'request_changes' ||
|
||||
result.findings?.some(f => f.severity === 'critical' || f.severity === 'high');
|
||||
// Use backend-calculated field that compares commit timestamps against review post time
|
||||
const hasCommitsAfterPosting = reviewInfo.newCommitsCheck?.hasCommitsAfterPosting ?? false;
|
||||
|
||||
// Check for ready for follow-up first (highest priority after posting)
|
||||
// Must have new commits that happened AFTER findings were posted
|
||||
if (hasCommitsAfterPosting) {
|
||||
return 'ready_for_followup';
|
||||
}
|
||||
|
||||
// Posted with blocking findings
|
||||
if (hasPosted && hasBlockingFindings) {
|
||||
return 'changes_requested';
|
||||
}
|
||||
|
||||
// Posted without blocking findings
|
||||
if (hasPosted) {
|
||||
return 'ready_to_merge';
|
||||
}
|
||||
|
||||
// Has review result but not posted yet
|
||||
return 'reviewed';
|
||||
}
|
||||
|
||||
export function useGitLabMRFiltering(
|
||||
mrs: GitLabMergeRequest[],
|
||||
getReviewStateForMR: (mrIid: number) => {
|
||||
isReviewing: boolean;
|
||||
progress: GitLabMRReviewProgress | null;
|
||||
result: GitLabMRReviewResult | null;
|
||||
error: string | null;
|
||||
newCommitsCheck: GitLabNewCommitsCheck | null;
|
||||
} | null
|
||||
) {
|
||||
const [filters, setFiltersState] = useState<GitLabMRFilterState>(DEFAULT_FILTERS);
|
||||
|
||||
// Derive unique contributors from MRs
|
||||
const contributors = useMemo(() => {
|
||||
const authorSet = new Set<string>();
|
||||
mrs.forEach(mr => {
|
||||
if (mr.author?.username) {
|
||||
authorSet.add(mr.author.username);
|
||||
}
|
||||
});
|
||||
return Array.from(authorSet).sort((a, b) =>
|
||||
a.toLowerCase().localeCompare(b.toLowerCase())
|
||||
);
|
||||
}, [mrs]);
|
||||
|
||||
// Filter and sort MRs based on current filters
|
||||
const filteredMRs = useMemo(() => {
|
||||
const filtered = mrs.filter(mr => {
|
||||
// Search filter - matches title or description
|
||||
if (filters.searchQuery) {
|
||||
const query = filters.searchQuery.toLowerCase();
|
||||
const matchesTitle = mr.title.toLowerCase().includes(query);
|
||||
const matchesDescription = mr.description?.toLowerCase().includes(query);
|
||||
const matchesIid = mr.iid.toString().includes(query);
|
||||
if (!matchesTitle && !matchesDescription && !matchesIid) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Contributors filter (multi-select)
|
||||
if (filters.contributors.length > 0) {
|
||||
const authorUsername = mr.author?.username;
|
||||
if (!authorUsername || !filters.contributors.includes(authorUsername)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Status filter (multi-select)
|
||||
if (filters.statuses.length > 0) {
|
||||
// 'all' acts as a wildcard - include all MRs when 'all' is selected
|
||||
const activeStatuses = filters.statuses.filter(s => s !== 'all');
|
||||
if (activeStatuses.length > 0) {
|
||||
const reviewInfo = getReviewStateForMR(mr.iid);
|
||||
const computedStatus = getMRComputedStatus(reviewInfo);
|
||||
|
||||
// Check if MR matches any of the selected statuses
|
||||
const matchesStatus = activeStatuses.some(status => {
|
||||
// Special handling: 'posted' should match any posted state
|
||||
if (status === 'posted') {
|
||||
const hasPosted = reviewInfo?.result?.hasPostedFindings;
|
||||
return hasPosted;
|
||||
}
|
||||
return computedStatus === status;
|
||||
});
|
||||
|
||||
if (!matchesStatus) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
// Pre-compute timestamps to avoid creating Date objects on every comparison
|
||||
const timestamps = new Map(
|
||||
filtered.map((mr) => [mr.iid, new Date(mr.createdAt).getTime()])
|
||||
);
|
||||
|
||||
// Sort the filtered results
|
||||
return filtered.sort((a, b) => {
|
||||
const aTime = timestamps.get(a.iid)!;
|
||||
const bTime = timestamps.get(b.iid)!;
|
||||
|
||||
switch (filters.sortBy) {
|
||||
case 'newest':
|
||||
// Sort by createdAt descending (most recent first)
|
||||
return bTime - aTime;
|
||||
case 'oldest':
|
||||
// Sort by createdAt ascending (oldest first)
|
||||
return aTime - bTime;
|
||||
case 'largest': {
|
||||
// Sort by title length as a proxy for complexity (descending)
|
||||
const aTitleLen = a.title.length;
|
||||
const bTitleLen = b.title.length;
|
||||
if (bTitleLen !== aTitleLen) return bTitleLen - aTitleLen;
|
||||
// Secondary sort by createdAt (newest first) for stable ordering
|
||||
return bTime - aTime;
|
||||
}
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
}, [mrs, filters, getReviewStateForMR]);
|
||||
|
||||
// Filter setters
|
||||
const setSearchQuery = useCallback((query: string) => {
|
||||
setFiltersState(prev => ({ ...prev, searchQuery: query }));
|
||||
}, []);
|
||||
|
||||
const setContributors = useCallback((selected: string[]) => {
|
||||
setFiltersState(prev => ({ ...prev, contributors: selected }));
|
||||
}, []);
|
||||
|
||||
const setStatuses = useCallback((statuses: GitLabMRStatusFilter[]) => {
|
||||
setFiltersState(prev => ({ ...prev, statuses }));
|
||||
}, []);
|
||||
|
||||
const setSortBy = useCallback((sortBy: GitLabMRSortOption) => {
|
||||
setFiltersState(prev => ({ ...prev, sortBy }));
|
||||
}, []);
|
||||
|
||||
const clearFilters = useCallback(() => {
|
||||
setFiltersState((prev) => ({
|
||||
...DEFAULT_FILTERS,
|
||||
sortBy: prev.sortBy, // Preserve sort preference when clearing filters
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const hasActiveFilters = useMemo(() => {
|
||||
return (
|
||||
filters.searchQuery !== '' ||
|
||||
filters.contributors.length > 0 ||
|
||||
filters.statuses.length > 0
|
||||
);
|
||||
}, [filters]);
|
||||
|
||||
return {
|
||||
filteredMRs,
|
||||
contributors,
|
||||
filters,
|
||||
setSearchQuery,
|
||||
setContributors,
|
||||
setStatuses,
|
||||
setSortBy,
|
||||
clearFilters,
|
||||
hasActiveFilters,
|
||||
};
|
||||
}
|
||||