Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9fc7320158 | |||
| d64e999db5 | |||
| 85d6b18529 | |||
| 737060902f | |||
| 062758bc1d | |||
| 435cc0733a | |||
| 5aac714b59 | |||
| 4d4234378f | |||
| d1fbccde39 | |||
| ed93df698b | |||
| 8872d33e32 | |||
| 3b3ad75c1b | |||
| 8ece0009ee | |||
| 115576e85d | |||
| 3791b37bbd | |||
| 2823873566 | |||
| 4f1b7b2a95 | |||
| 5e78d748ee | |||
| aa5fc7f952 |
@@ -0,0 +1,10 @@
|
||||
node_modules
|
||||
.next
|
||||
.git
|
||||
.env*
|
||||
*.md
|
||||
tests
|
||||
scripts
|
||||
guides
|
||||
apps/frontend
|
||||
apps/backend
|
||||
@@ -0,0 +1,165 @@
|
||||
# Publish OSS Packages to npm
|
||||
#
|
||||
# Builds and publishes @auto-claude/types and @auto-claude/ui to npm
|
||||
# when a version tag is pushed. Includes a dry-run job on PRs to catch
|
||||
# issues before release.
|
||||
|
||||
name: Publish Packages
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
pull_request:
|
||||
branches: [main, develop]
|
||||
paths:
|
||||
- 'packages/**'
|
||||
- 'package.json'
|
||||
- 'package-lock.json'
|
||||
- '.github/workflows/publish-packages.yml'
|
||||
|
||||
concurrency:
|
||||
group: publish-packages-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
# --------------------------------------------------------------------------
|
||||
# Validate - Typecheck and test before publishing
|
||||
# --------------------------------------------------------------------------
|
||||
validate:
|
||||
name: Validate packages
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js and install dependencies
|
||||
uses: ./.github/actions/setup-node-frontend
|
||||
with:
|
||||
ignore-scripts: 'true'
|
||||
|
||||
- name: Typecheck @auto-claude/types
|
||||
run: npx tsc --project packages/types/tsconfig.json --noEmit
|
||||
|
||||
- name: Typecheck @auto-claude/ui
|
||||
run: npx tsc --project packages/ui/tsconfig.json --noEmit
|
||||
|
||||
- name: Build @auto-claude/types
|
||||
run: npx tsc --project packages/types/tsconfig.build.json
|
||||
|
||||
- name: Build @auto-claude/ui
|
||||
run: npx tsc --project packages/ui/tsconfig.build.json
|
||||
|
||||
- name: Typecheck frontend
|
||||
working-directory: apps/frontend
|
||||
run: npm run typecheck
|
||||
|
||||
- name: Run frontend tests
|
||||
working-directory: apps/frontend
|
||||
run: npm run test
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Dry Run - Verify publish would succeed (PRs only)
|
||||
# --------------------------------------------------------------------------
|
||||
dry-run:
|
||||
name: Publish dry run
|
||||
runs-on: ubuntu-latest
|
||||
needs: validate
|
||||
if: github.event_name == 'pull_request'
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js and install dependencies
|
||||
uses: ./.github/actions/setup-node-frontend
|
||||
with:
|
||||
ignore-scripts: 'true'
|
||||
|
||||
- name: Build @auto-claude/types
|
||||
run: npx tsc --project packages/types/tsconfig.build.json
|
||||
|
||||
- name: Build @auto-claude/ui
|
||||
run: npx tsc --project packages/ui/tsconfig.build.json
|
||||
|
||||
- name: Dry run publish @auto-claude/types
|
||||
run: npm publish --workspace packages/types --dry-run
|
||||
|
||||
- name: Dry run publish @auto-claude/ui
|
||||
run: npm publish --workspace packages/ui --dry-run
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Publish - Push packages to npm (tagged releases only)
|
||||
# --------------------------------------------------------------------------
|
||||
publish:
|
||||
name: Publish to npm
|
||||
runs-on: ubuntu-latest
|
||||
needs: validate
|
||||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js and install dependencies
|
||||
uses: ./.github/actions/setup-node-frontend
|
||||
with:
|
||||
ignore-scripts: 'true'
|
||||
|
||||
- name: Configure npm authentication
|
||||
run: echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc
|
||||
env:
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
- name: Validate tag matches package versions
|
||||
run: |
|
||||
TAG_VERSION="${GITHUB_REF#refs/tags/v}"
|
||||
TYPES_VERSION=$(node -p "require('./packages/types/package.json').version")
|
||||
UI_VERSION=$(node -p "require('./packages/ui/package.json').version")
|
||||
echo "Tag version: ${TAG_VERSION}"
|
||||
echo "types version: ${TYPES_VERSION}"
|
||||
echo "ui version: ${UI_VERSION}"
|
||||
if [ "$TAG_VERSION" != "$TYPES_VERSION" ]; then
|
||||
echo "::error::Tag v${TAG_VERSION} does not match @auto-claude/types version ${TYPES_VERSION}"
|
||||
exit 1
|
||||
fi
|
||||
if [ "$TAG_VERSION" != "$UI_VERSION" ]; then
|
||||
echo "::error::Tag v${TAG_VERSION} does not match @auto-claude/ui version ${UI_VERSION}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Build @auto-claude/types
|
||||
run: npx tsc --project packages/types/tsconfig.build.json
|
||||
|
||||
- name: Build @auto-claude/ui
|
||||
run: npx tsc --project packages/ui/tsconfig.build.json
|
||||
|
||||
- name: Publish @auto-claude/types
|
||||
run: |
|
||||
PACKAGE_VERSION=$(node -p "require('./packages/types/package.json').version")
|
||||
HTTP_CODE=$(npm view "@auto-claude/types@${PACKAGE_VERSION}" version --json 2>&1) && RC=$? || RC=$?
|
||||
if [ $RC -eq 0 ] && echo "$HTTP_CODE" | grep -q "$PACKAGE_VERSION"; then
|
||||
echo "::notice::@auto-claude/types@${PACKAGE_VERSION} already published, skipping"
|
||||
elif echo "$HTTP_CODE" | grep -qi "E404\|not found\|is not in this registry"; then
|
||||
npm publish --workspace packages/types --access public --provenance
|
||||
else
|
||||
echo "::warning::Unexpected error checking @auto-claude/types@${PACKAGE_VERSION}: ${HTTP_CODE}"
|
||||
npm publish --workspace packages/types --access public --provenance
|
||||
fi
|
||||
|
||||
- name: Publish @auto-claude/ui
|
||||
run: |
|
||||
PACKAGE_VERSION=$(node -p "require('./packages/ui/package.json').version")
|
||||
HTTP_CODE=$(npm view "@auto-claude/ui@${PACKAGE_VERSION}" version --json 2>&1) && RC=$? || RC=$?
|
||||
if [ $RC -eq 0 ] && echo "$HTTP_CODE" | grep -q "$PACKAGE_VERSION"; then
|
||||
echo "::notice::@auto-claude/ui@${PACKAGE_VERSION} already published, skipping"
|
||||
elif echo "$HTTP_CODE" | grep -qi "E404\|not found\|is not in this registry"; then
|
||||
npm publish --workspace packages/ui --access public --provenance
|
||||
else
|
||||
echo "::warning::Unexpected error checking @auto-claude/ui@${PACKAGE_VERSION}: ${HTTP_CODE}"
|
||||
npm publish --workspace packages/ui --access public --provenance
|
||||
fi
|
||||
@@ -119,6 +119,7 @@ apps/frontend/node_modules
|
||||
# Build output
|
||||
dist/
|
||||
out/
|
||||
.next
|
||||
*.tsbuildinfo
|
||||
apps/frontend/python-runtime/
|
||||
|
||||
|
||||
@@ -40,6 +40,18 @@ Auto Claude is a desktop application (+ CLI) where users describe a goal and AI
|
||||
|
||||
**PR target** — Always target the `develop` branch for PRs to AndyMik90/Auto-Claude, NOT `main`.
|
||||
|
||||
## Work Approach
|
||||
|
||||
**Investigate before speculating** — Always read the actual code before proposing root causes. Spawn agents to grep and read relevant source files before forming any hypothesis. Never guess at causes without evidence from the codebase.
|
||||
|
||||
**Spawn agents for complex tasks** — When tackling complex tasks, spawn sub-agents/agent teams immediately rather than trying to handle everything in a single context window. Never attempt to analyze large codebases or multiple features monolithically.
|
||||
|
||||
**Minimal fixes only** — Prefer the simplest approach (e.g., prompt-only changes, single guard clause) before suggesting multi-component solutions. If the user asks for X, implement X — don't bundle additional fixes they didn't request.
|
||||
|
||||
## Known Gotchas
|
||||
|
||||
**Electron path resolution** — For bug fixes in the Electron app, always check path resolution differences between dev and production builds (`app.isPackaged`, `process.resourcesPath`). Paths that work in dev often break when Electron is bundled for production — verify both contexts.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
@@ -98,30 +110,6 @@ cd apps/backend && uv venv && uv pip install -r requirements.txt
|
||||
cd apps/frontend && npm install
|
||||
```
|
||||
|
||||
### Backend
|
||||
```bash
|
||||
cd apps/backend
|
||||
python spec_runner.py --interactive # Create spec interactively
|
||||
python spec_runner.py --task "description" # Create from task
|
||||
python run.py --spec 001 # Run autonomous build
|
||||
python run.py --spec 001 --qa # Run QA validation
|
||||
python run.py --spec 001 --merge # Merge completed build
|
||||
python run.py --list # List all specs
|
||||
```
|
||||
|
||||
### Frontend
|
||||
```bash
|
||||
cd apps/frontend
|
||||
npm run dev # Dev mode (Electron + Vite HMR)
|
||||
npm run build # Production build
|
||||
npm run test # Vitest unit tests
|
||||
npm run test:watch # Vitest watch mode
|
||||
npm run lint # Biome check
|
||||
npm run lint:fix # Biome auto-fix
|
||||
npm run typecheck # TypeScript strict check
|
||||
npm run package # Package for distribution
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
| Stack | Command | Tool |
|
||||
@@ -145,30 +133,7 @@ See [RELEASE.md](RELEASE.md) for full release process.
|
||||
|
||||
Client: `apps/backend/core/client.py` — `create_client()` returns a configured `ClaudeSDKClient` with security hooks, tool permissions, and MCP server integration.
|
||||
|
||||
Model and thinking level are user-configurable (via the Electron UI settings or CLI override). Use `phase_config.py` helpers to resolve the correct values:
|
||||
|
||||
```python
|
||||
from core.client import create_client
|
||||
from phase_config import get_phase_model, get_phase_thinking_budget
|
||||
|
||||
# Resolve model/thinking from user settings (Electron UI or CLI override)
|
||||
phase_model = get_phase_model(spec_dir, "coding", cli_model=None)
|
||||
phase_thinking = get_phase_thinking_budget(spec_dir, "coding", cli_thinking=None)
|
||||
|
||||
client = create_client(
|
||||
project_dir=project_dir,
|
||||
spec_dir=spec_dir,
|
||||
model=phase_model,
|
||||
agent_type="coder", # planner | coder | qa_reviewer | qa_fixer
|
||||
max_thinking_tokens=phase_thinking,
|
||||
)
|
||||
|
||||
# Run agent session (uses context manager + run_agent_session helper)
|
||||
async with client:
|
||||
status, response = await run_agent_session(client, prompt, spec_dir)
|
||||
```
|
||||
|
||||
Working examples: `agents/planner.py`, `agents/coder.py`, `qa/reviewer.py`, `qa/fixer.py`, `spec/`
|
||||
Model and thinking level are user-configurable (via the Electron UI settings or CLI override). Use `phase_config.py` helpers to resolve the correct values
|
||||
|
||||
### Agent Prompts (`apps/backend/prompts/`)
|
||||
|
||||
@@ -323,6 +288,8 @@ cd apps/backend && python run.py --spec 001
|
||||
# Desktop app
|
||||
npm start # Production build + run
|
||||
npm run dev # Development mode with HMR
|
||||
npm run dev:debug # Debug mode with verbose output
|
||||
npm run dev:mcp # Electron MCP server for AI debugging
|
||||
|
||||
# Project data: .auto-claude/specs/ (gitignored)
|
||||
```
|
||||
|
||||
@@ -16,17 +16,17 @@
|
||||
### Stable Release
|
||||
|
||||
<!-- STABLE_VERSION_BADGE -->
|
||||
[](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.5)
|
||||
[](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.7)
|
||||
<!-- STABLE_VERSION_BADGE_END -->
|
||||
|
||||
<!-- STABLE_DOWNLOADS -->
|
||||
| Platform | Download |
|
||||
|----------|----------|
|
||||
| **Windows** | [Auto-Claude-2.7.5-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-win32-x64.exe) |
|
||||
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.5-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-darwin-arm64.dmg) |
|
||||
| **macOS (Intel)** | [Auto-Claude-2.7.5-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-darwin-x64.dmg) |
|
||||
| **Linux** | [Auto-Claude-2.7.5-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-linux-x86_64.AppImage) |
|
||||
| **Linux (Debian)** | [Auto-Claude-2.7.5-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-linux-amd64.deb) |
|
||||
| **Windows** | [Auto-Claude-2.7.7-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.7/Auto-Claude-2.7.7-win32-x64.exe) |
|
||||
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.7-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.7/Auto-Claude-2.7.7-darwin-arm64.dmg) |
|
||||
| **macOS (Intel)** | [Auto-Claude-2.7.7-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.7/Auto-Claude-2.7.7-darwin-x64.dmg) |
|
||||
| **Linux** | [Auto-Claude-2.7.7-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.7/Auto-Claude-2.7.7-linux-x86_64.AppImage) |
|
||||
| **Linux (Debian)** | [Auto-Claude-2.7.7-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.7/Auto-Claude-2.7.7-linux-amd64.deb) |
|
||||
| **Linux (Flatpak)** | [Auto-Claude-2.7.5-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.5/Auto-Claude-2.7.5-linux-x86_64.flatpak) |
|
||||
<!-- STABLE_DOWNLOADS_END -->
|
||||
|
||||
@@ -35,18 +35,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.7.6-beta.3)
|
||||
[](https://github.com/AndyMik90/Auto-Claude/releases/tag/v2.7.6-beta.4)
|
||||
<!-- BETA_VERSION_BADGE_END -->
|
||||
|
||||
<!-- BETA_DOWNLOADS -->
|
||||
| Platform | Download |
|
||||
|----------|----------|
|
||||
| **Windows** | [Auto-Claude-2.7.6-beta.3-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.3/Auto-Claude-2.7.6-beta.3-win32-x64.exe) |
|
||||
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.6-beta.3-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.3/Auto-Claude-2.7.6-beta.3-darwin-arm64.dmg) |
|
||||
| **macOS (Intel)** | [Auto-Claude-2.7.6-beta.3-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.3/Auto-Claude-2.7.6-beta.3-darwin-x64.dmg) |
|
||||
| **Linux** | [Auto-Claude-2.7.6-beta.3-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.3/Auto-Claude-2.7.6-beta.3-linux-x86_64.AppImage) |
|
||||
| **Linux (Debian)** | [Auto-Claude-2.7.6-beta.3-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.3/Auto-Claude-2.7.6-beta.3-linux-amd64.deb) |
|
||||
| **Linux (Flatpak)** | [Auto-Claude-2.7.6-beta.3-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.3/Auto-Claude-2.7.6-beta.3-linux-x86_64.flatpak) |
|
||||
| **Windows** | [Auto-Claude-2.7.6-beta.4-win32-x64.exe](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.4/Auto-Claude-2.7.6-beta.4-win32-x64.exe) |
|
||||
| **macOS (Apple Silicon)** | [Auto-Claude-2.7.6-beta.4-darwin-arm64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.4/Auto-Claude-2.7.6-beta.4-darwin-arm64.dmg) |
|
||||
| **macOS (Intel)** | [Auto-Claude-2.7.6-beta.4-darwin-x64.dmg](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.4/Auto-Claude-2.7.6-beta.4-darwin-x64.dmg) |
|
||||
| **Linux** | [Auto-Claude-2.7.6-beta.4-linux-x86_64.AppImage](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.4/Auto-Claude-2.7.6-beta.4-linux-x86_64.AppImage) |
|
||||
| **Linux (Debian)** | [Auto-Claude-2.7.6-beta.4-linux-amd64.deb](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.4/Auto-Claude-2.7.6-beta.4-linux-amd64.deb) |
|
||||
| **Linux (Flatpak)** | [Auto-Claude-2.7.6-beta.4-linux-x86_64.flatpak](https://github.com/AndyMik90/Auto-Claude/releases/download/v2.7.6-beta.4/Auto-Claude-2.7.6-beta.4-linux-x86_64.flatpak) |
|
||||
<!-- BETA_DOWNLOADS_END -->
|
||||
|
||||
> All releases include SHA256 checksums and VirusTotal scan results for security verification.
|
||||
|
||||
@@ -62,5 +62,9 @@ Thumbs.db
|
||||
# Tests (development only)
|
||||
tests/
|
||||
|
||||
# Exception: Allow colocated tests within integrations/graphiti
|
||||
!integrations/graphiti/tests/
|
||||
|
||||
# Auto Claude data directory
|
||||
.auto-claude/
|
||||
coverage.json
|
||||
|
||||
@@ -19,5 +19,5 @@ Quick Start:
|
||||
See README.md for full documentation.
|
||||
"""
|
||||
|
||||
__version__ = "2.7.6-beta.3"
|
||||
__version__ = "2.7.7"
|
||||
__author__ = "Auto Claude Team"
|
||||
|
||||
@@ -292,6 +292,14 @@ AGENT_CONFIGS = {
|
||||
"auto_claude_tools": [],
|
||||
"thinking_default": "high",
|
||||
},
|
||||
"pr_followup_extraction": {
|
||||
# Lightweight extraction call for recovering data when structured output fails
|
||||
# Pure structured output extraction, no tools needed
|
||||
"tools": [],
|
||||
"mcp_servers": [],
|
||||
"auto_claude_tools": [],
|
||||
"thinking_default": "low",
|
||||
},
|
||||
"pr_finding_validator": {
|
||||
# Standalone validator for re-checking findings against actual code
|
||||
# Called separately from orchestrator to validate findings with fresh context
|
||||
|
||||
@@ -186,14 +186,12 @@ def _before_send(event: dict, hint: dict) -> dict | None:
|
||||
|
||||
def init_sentry(
|
||||
component: str = "backend",
|
||||
force_enable: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
Initialize Sentry for the Python backend.
|
||||
|
||||
Args:
|
||||
component: Component name for tagging (e.g., "backend", "github-runner")
|
||||
force_enable: Force enable even without packaged app detection
|
||||
|
||||
Returns:
|
||||
True if Sentry was initialized, False otherwise
|
||||
@@ -212,20 +210,11 @@ def init_sentry(
|
||||
logger.debug("[Sentry] No SENTRY_DSN configured - error reporting disabled")
|
||||
return False
|
||||
|
||||
# Check if we should enable Sentry
|
||||
# Enable if:
|
||||
# - Running from packaged app (detected by __compiled__ or frozen)
|
||||
# - SENTRY_DEV=true is set
|
||||
# - force_enable is True
|
||||
# DSN is present (checked above), so Sentry should be enabled.
|
||||
# The Electron main process only passes SENTRY_DSN to subprocesses in
|
||||
# production builds, so its presence is sufficient to gate activation.
|
||||
# In dev, set SENTRY_DSN in your environment to opt-in.
|
||||
is_packaged = getattr(sys, "frozen", False) or hasattr(sys, "__compiled__")
|
||||
sentry_dev = os.environ.get("SENTRY_DEV", "").lower() in ("true", "1", "yes")
|
||||
should_enable = is_packaged or sentry_dev or force_enable
|
||||
|
||||
if not should_enable:
|
||||
logger.debug(
|
||||
"[Sentry] Development mode - error reporting disabled (set SENTRY_DEV=true to enable)"
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
import sentry_sdk
|
||||
|
||||
@@ -624,7 +624,10 @@ def get_graphiti_status() -> dict:
|
||||
|
||||
# CRITICAL FIX: Actually verify packages are importable before reporting available
|
||||
# Don't just check config.is_valid() - actually try to import the module
|
||||
if not config.is_valid():
|
||||
# Note: This branch is currently unreachable because is_valid() returns True
|
||||
# whenever enabled is True. Kept for defensive purposes in case is_valid()
|
||||
# logic changes in the future.
|
||||
if not config.is_valid(): # pragma: no cover
|
||||
status["reason"] = errors[0] if errors else "Configuration invalid"
|
||||
return status
|
||||
|
||||
@@ -635,7 +638,7 @@ def get_graphiti_status() -> dict:
|
||||
from graphiti_core.driver.falkordb_driver import FalkorDriver # noqa: F401
|
||||
|
||||
# If we got here, packages are importable
|
||||
status["available"] = True
|
||||
status["available"] = True # pragma: no cover
|
||||
except ImportError as e:
|
||||
status["available"] = False
|
||||
status["reason"] = f"Graphiti packages not installed: {e}"
|
||||
|
||||
@@ -72,6 +72,8 @@ async def test_graphiti_connection() -> tuple[bool, str]:
|
||||
"""
|
||||
Test if LadybugDB is available and Graphiti can connect.
|
||||
|
||||
Uses the embedded LadybugDB via the patched KuzuDriver (no remote connection).
|
||||
|
||||
Returns:
|
||||
Tuple of (success: bool, message: str)
|
||||
"""
|
||||
@@ -87,43 +89,48 @@ async def test_graphiti_connection() -> tuple[bool, str]:
|
||||
|
||||
try:
|
||||
from graphiti_core import Graphiti
|
||||
from graphiti_core.driver.falkordb_driver import FalkorDriver
|
||||
from graphiti_providers import ProviderError, create_embedder, create_llm_client
|
||||
|
||||
# Import the patched driver creator (handles LadybugDB monkeypatch internally)
|
||||
from integrations.graphiti.queries_pkg.client import _apply_ladybug_monkeypatch
|
||||
from integrations.graphiti.queries_pkg.kuzu_driver_patched import (
|
||||
create_patched_kuzu_driver,
|
||||
)
|
||||
|
||||
# Create providers
|
||||
try:
|
||||
llm_client = create_llm_client(config)
|
||||
embedder = create_embedder(config)
|
||||
llm_client = create_llm_client(config) # pragma: no cover
|
||||
embedder = create_embedder(config) # pragma: no cover
|
||||
except ProviderError as e:
|
||||
return False, f"Provider error: {e}"
|
||||
|
||||
# Try to connect
|
||||
driver = FalkorDriver(
|
||||
host=config.falkordb_host,
|
||||
port=config.falkordb_port,
|
||||
password=config.falkordb_password or None,
|
||||
database=config.database,
|
||||
)
|
||||
# Apply LadybugDB monkeypatch for embedded database
|
||||
if not _apply_ladybug_monkeypatch(): # pragma: no cover
|
||||
return False, "LadybugDB not installed (requires Python 3.12+)"
|
||||
|
||||
graphiti = Graphiti(
|
||||
# Create embedded database driver
|
||||
db_path = config.get_db_path()
|
||||
driver = create_patched_kuzu_driver(db=str(db_path)) # pragma: no cover
|
||||
|
||||
graphiti = Graphiti( # pragma: no cover
|
||||
graph_driver=driver,
|
||||
llm_client=llm_client,
|
||||
embedder=embedder,
|
||||
)
|
||||
|
||||
# Try a simple operation
|
||||
await graphiti.build_indices_and_constraints()
|
||||
await graphiti.close()
|
||||
await graphiti.build_indices_and_constraints() # pragma: no cover
|
||||
await graphiti.close() # pragma: no cover
|
||||
|
||||
return True, (
|
||||
f"Connected to LadybugDB at {config.falkordb_host}:{config.falkordb_port} "
|
||||
return True, ( # pragma: no cover
|
||||
f"Connected to LadybugDB at {db_path} "
|
||||
f"(providers: {config.get_provider_summary()})"
|
||||
)
|
||||
|
||||
except ImportError as e:
|
||||
return False, f"Graphiti packages not installed: {e}"
|
||||
|
||||
except Exception as e:
|
||||
except Exception as e: # pragma: no cover
|
||||
return False, f"Connection failed: {e}"
|
||||
|
||||
|
||||
|
||||
@@ -15,7 +15,10 @@ from typing import Any
|
||||
# Import kuzu (might be real_ladybug via monkeypatch)
|
||||
try:
|
||||
import kuzu
|
||||
except ImportError:
|
||||
except ImportError: # pragma: no cover
|
||||
# Fallback to real_ladybug if kuzu is not available.
|
||||
# This import-time fallback is hard to test in normal unit tests
|
||||
# since the module is imported once before tests can mock anything.
|
||||
import real_ladybug as kuzu # type: ignore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -67,7 +67,8 @@ class GraphitiSearch:
|
||||
Args:
|
||||
query: Search query
|
||||
num_results: Maximum number of results to return
|
||||
include_project_context: If True and in PROJECT mode, search project-wide
|
||||
include_project_context: If True and in SPEC mode, also search project-wide
|
||||
min_score: Minimum relevance score threshold (0.0 to 1.0)
|
||||
|
||||
Returns:
|
||||
List of relevant context items with content, score, and type
|
||||
@@ -101,10 +102,14 @@ class GraphitiSearch:
|
||||
or str(result)
|
||||
)
|
||||
|
||||
# Normalize score to float, treating None as 0.0
|
||||
raw_score = getattr(result, "score", None)
|
||||
score = raw_score if raw_score is not None else 0.0
|
||||
|
||||
context_items.append(
|
||||
{
|
||||
"content": content,
|
||||
"score": getattr(result, "score", 0.0),
|
||||
"score": score,
|
||||
"type": getattr(result, "type", "unknown"),
|
||||
}
|
||||
)
|
||||
@@ -112,7 +117,9 @@ class GraphitiSearch:
|
||||
# Filter by minimum score if specified
|
||||
if min_score > 0:
|
||||
context_items = [
|
||||
item for item in context_items if item.get("score", 0) >= min_score
|
||||
item
|
||||
for item in context_items
|
||||
if (item.get("score", 0.0)) >= min_score
|
||||
]
|
||||
|
||||
logger.info(
|
||||
@@ -225,12 +232,14 @@ class GraphitiSearch:
|
||||
if not isinstance(data, dict):
|
||||
continue
|
||||
if data.get("type") == EPISODE_TYPE_TASK_OUTCOME:
|
||||
raw_score = getattr(result, "score", None)
|
||||
score = raw_score if raw_score is not None else 0.0
|
||||
outcomes.append(
|
||||
{
|
||||
"task_id": data.get("task_id"),
|
||||
"success": data.get("success"),
|
||||
"outcome": data.get("outcome"),
|
||||
"score": getattr(result, "score", 0.0),
|
||||
"score": score,
|
||||
}
|
||||
)
|
||||
except (json.JSONDecodeError, TypeError, AttributeError):
|
||||
@@ -284,7 +293,8 @@ class GraphitiSearch:
|
||||
content = getattr(result, "content", None) or getattr(
|
||||
result, "fact", None
|
||||
)
|
||||
score = getattr(result, "score", 0.0)
|
||||
raw_score = getattr(result, "score", None)
|
||||
score = raw_score if raw_score is not None else 0.0
|
||||
|
||||
if score < min_score:
|
||||
continue
|
||||
@@ -320,7 +330,8 @@ class GraphitiSearch:
|
||||
content = getattr(result, "content", None) or getattr(
|
||||
result, "fact", None
|
||||
)
|
||||
score = getattr(result, "score", 0.0)
|
||||
raw_score = getattr(result, "score", None)
|
||||
score = raw_score if raw_score is not None else 0.0
|
||||
|
||||
if score < min_score:
|
||||
continue
|
||||
|
||||
@@ -0,0 +1,716 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test Script for Memory Integration with LadybugDB
|
||||
=================================================
|
||||
|
||||
This script tests the memory layer (graph + semantic search) to verify
|
||||
data is being saved and retrieved correctly from LadybugDB (embedded Kuzu).
|
||||
|
||||
LadybugDB is an embedded graph database - no Docker required!
|
||||
|
||||
Usage:
|
||||
# Set environment variables first (or in .env file):
|
||||
export GRAPHITI_ENABLED=true
|
||||
export GRAPHITI_EMBEDDER_PROVIDER=ollama # or: openai, voyage, azure_openai, google
|
||||
|
||||
# For Ollama (recommended - free, local):
|
||||
export OLLAMA_EMBEDDING_MODEL=embeddinggemma
|
||||
export OLLAMA_EMBEDDING_DIM=768
|
||||
|
||||
# For OpenAI:
|
||||
export OPENAI_API_KEY=sk-...
|
||||
|
||||
# Run the test:
|
||||
cd auto-claude
|
||||
python integrations/graphiti/run_graphiti_memory_test.py
|
||||
|
||||
# Or run specific tests:
|
||||
python integrations/graphiti/run_graphiti_memory_test.py --test connection
|
||||
python integrations/graphiti/run_graphiti_memory_test.py --test save
|
||||
python integrations/graphiti/run_graphiti_memory_test.py --test search
|
||||
python integrations/graphiti/run_graphiti_memory_test.py --test ollama
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
# Load .env file
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
|
||||
env_file = Path(__file__).parent.parent.parent.parent / ".env"
|
||||
if env_file.exists():
|
||||
load_dotenv(env_file)
|
||||
print(f"Loaded .env from {env_file}")
|
||||
except ImportError:
|
||||
print("Note: python-dotenv not installed, using environment variables only")
|
||||
|
||||
|
||||
def apply_ladybug_monkeypatch():
|
||||
"""Apply LadybugDB monkeypatch for embedded database support."""
|
||||
try:
|
||||
import real_ladybug
|
||||
|
||||
sys.modules["kuzu"] = real_ladybug
|
||||
return True
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Try native kuzu as fallback
|
||||
try:
|
||||
import kuzu # noqa: F401
|
||||
|
||||
return True
|
||||
except ImportError:
|
||||
return False
|
||||
|
||||
|
||||
def print_header(title: str):
|
||||
"""Print a section header."""
|
||||
print("\n" + "=" * 60)
|
||||
print(f" {title}")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
|
||||
def print_result(label: str, value: str, success: bool = True):
|
||||
"""Print a result line."""
|
||||
status = "✅" if success else "❌"
|
||||
print(f" {status} {label}: {value}")
|
||||
|
||||
|
||||
def print_info(message: str):
|
||||
"""Print an info line."""
|
||||
print(f" ℹ️ {message}")
|
||||
|
||||
|
||||
async def test_ladybugdb_connection(db_path: str, database: str) -> bool:
|
||||
"""Test basic LadybugDB connection."""
|
||||
print_header("1. Testing LadybugDB Connection")
|
||||
|
||||
print(f" Database path: {db_path}")
|
||||
print(f" Database name: {database}")
|
||||
print()
|
||||
|
||||
if not apply_ladybug_monkeypatch():
|
||||
print_result("LadybugDB", "Not installed (pip install real-ladybug)", False)
|
||||
return False
|
||||
|
||||
print_result("LadybugDB", "Installed", True)
|
||||
|
||||
try:
|
||||
import kuzu # This is real_ladybug via monkeypatch
|
||||
|
||||
# Ensure parent directory exists (database will create its own structure)
|
||||
full_path = Path(db_path) / database
|
||||
full_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Create database and connection
|
||||
db = kuzu.Database(str(full_path))
|
||||
conn = kuzu.Connection(db)
|
||||
|
||||
# Test basic query
|
||||
result = conn.execute("RETURN 1 + 1 as test")
|
||||
df = result.get_as_df()
|
||||
test_value = df["test"].iloc[0] if len(df) > 0 else None
|
||||
|
||||
if test_value == 2:
|
||||
print_result("Connection", "SUCCESS - Database responds correctly", True)
|
||||
return True
|
||||
else:
|
||||
print_result("Connection", f"Unexpected result: {test_value}", False)
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print_result("Connection", f"FAILED: {e}", False)
|
||||
return False
|
||||
|
||||
|
||||
async def test_save_episode(db_path: str, database: str) -> tuple[str, str]:
|
||||
"""Test saving an episode to the graph."""
|
||||
print_header("2. Testing Episode Save")
|
||||
|
||||
try:
|
||||
from integrations.graphiti.config import GraphitiConfig
|
||||
from integrations.graphiti.queries_pkg.client import GraphitiClient
|
||||
|
||||
# Create config
|
||||
config = GraphitiConfig.from_env()
|
||||
config.db_path = db_path
|
||||
config.database = database
|
||||
config.enabled = True
|
||||
|
||||
print(f" Embedder provider: {config.embedder_provider}")
|
||||
print()
|
||||
|
||||
# Initialize client
|
||||
client = GraphitiClient(config)
|
||||
initialized = await client.initialize()
|
||||
|
||||
if not initialized:
|
||||
print_result("Client Init", "Failed to initialize", False)
|
||||
return None, None
|
||||
|
||||
print_result("Client Init", "SUCCESS", True)
|
||||
|
||||
# Create test episode data
|
||||
test_data = {
|
||||
"type": "test_episode",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
"test_field": "Hello from LadybugDB test!",
|
||||
"test_number": 42,
|
||||
"embedder": config.embedder_provider,
|
||||
}
|
||||
|
||||
episode_name = (
|
||||
f"test_episode_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}"
|
||||
)
|
||||
group_id = "ladybug_test_group"
|
||||
|
||||
print(f" Episode name: {episode_name}")
|
||||
print(f" Group ID: {group_id}")
|
||||
print(f" Data: {json.dumps(test_data, indent=4)}")
|
||||
print()
|
||||
|
||||
# Save using Graphiti
|
||||
from graphiti_core.nodes import EpisodeType
|
||||
|
||||
print(" Saving episode...")
|
||||
await client.graphiti.add_episode(
|
||||
name=episode_name,
|
||||
episode_body=json.dumps(test_data),
|
||||
source=EpisodeType.text,
|
||||
source_description="Test episode from run_graphiti_memory_test.py",
|
||||
reference_time=datetime.now(timezone.utc),
|
||||
group_id=group_id,
|
||||
)
|
||||
|
||||
print_result("Episode Save", "SUCCESS", True)
|
||||
|
||||
await client.close()
|
||||
return episode_name, group_id
|
||||
|
||||
except ImportError as e:
|
||||
print_result("Import", f"Missing dependency: {e}", False)
|
||||
return None, None
|
||||
except Exception as e:
|
||||
print_result("Episode Save", f"FAILED: {e}", False)
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return None, None
|
||||
|
||||
|
||||
async def test_keyword_search(db_path: str, database: str) -> bool:
|
||||
"""Test keyword search (works without embeddings)."""
|
||||
print_header("3. Testing Keyword Search")
|
||||
|
||||
if not apply_ladybug_monkeypatch():
|
||||
print_result("LadybugDB", "Not installed", False)
|
||||
return False
|
||||
|
||||
try:
|
||||
import kuzu
|
||||
|
||||
full_path = Path(db_path) / database
|
||||
if not full_path.exists():
|
||||
print_info("Database doesn't exist yet - run save test first")
|
||||
return True
|
||||
|
||||
db = kuzu.Database(str(full_path))
|
||||
conn = kuzu.Connection(db)
|
||||
|
||||
# Search for test episodes
|
||||
search_query = "test"
|
||||
print(f" Search query: '{search_query}'")
|
||||
print()
|
||||
|
||||
query = f"""
|
||||
MATCH (e:Episodic)
|
||||
WHERE toLower(e.name) CONTAINS '{search_query}'
|
||||
OR toLower(e.content) CONTAINS '{search_query}'
|
||||
RETURN e.name as name, e.content as content
|
||||
LIMIT 5
|
||||
"""
|
||||
|
||||
try:
|
||||
result = conn.execute(query)
|
||||
df = result.get_as_df()
|
||||
|
||||
print(f" Found {len(df)} results:")
|
||||
for _, row in df.iterrows():
|
||||
name = row.get("name", "unknown")[:50]
|
||||
content = str(row.get("content", ""))[:60]
|
||||
print(f" - {name}: {content}...")
|
||||
|
||||
print_result("Keyword Search", f"Found {len(df)} results", True)
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
if "Episodic" in str(e) and "not exist" in str(e).lower():
|
||||
print_info("Episodic table doesn't exist yet - run save test first")
|
||||
return True
|
||||
raise
|
||||
|
||||
except Exception as e:
|
||||
print_result("Keyword Search", f"FAILED: {e}", False)
|
||||
return False
|
||||
|
||||
|
||||
async def test_semantic_search(db_path: str, database: str, group_id: str) -> bool:
|
||||
"""Test semantic search using embeddings."""
|
||||
print_header("4. Testing Semantic Search")
|
||||
|
||||
if not group_id:
|
||||
print_info("Skipping - no group_id from save test")
|
||||
return True
|
||||
|
||||
try:
|
||||
from integrations.graphiti.config import GraphitiConfig
|
||||
from integrations.graphiti.queries_pkg.client import GraphitiClient
|
||||
|
||||
# Create config
|
||||
config = GraphitiConfig.from_env()
|
||||
config.db_path = db_path
|
||||
config.database = database
|
||||
config.enabled = True
|
||||
|
||||
if not config.embedder_provider:
|
||||
print_info("No embedder configured - semantic search requires embeddings")
|
||||
return True
|
||||
|
||||
print(f" Embedder: {config.embedder_provider}")
|
||||
print()
|
||||
|
||||
# Initialize client
|
||||
client = GraphitiClient(config)
|
||||
initialized = await client.initialize()
|
||||
|
||||
if not initialized:
|
||||
print_result("Client Init", "Failed", False)
|
||||
return False
|
||||
|
||||
# Search
|
||||
query = "test episode hello LadybugDB"
|
||||
print(f" Query: '{query}'")
|
||||
print(f" Group ID: {group_id}")
|
||||
print()
|
||||
|
||||
print(" Searching...")
|
||||
results = await client.graphiti.search(
|
||||
query=query,
|
||||
group_ids=[group_id],
|
||||
num_results=10,
|
||||
)
|
||||
|
||||
print(f" Found {len(results)} results:")
|
||||
for i, result in enumerate(results[:5]):
|
||||
# Print available attributes
|
||||
if hasattr(result, "fact") and result.fact:
|
||||
print(f" {i + 1}. [fact] {str(result.fact)[:80]}...")
|
||||
elif hasattr(result, "content") and result.content:
|
||||
print(f" {i + 1}. [content] {str(result.content)[:80]}...")
|
||||
elif hasattr(result, "name"):
|
||||
print(f" {i + 1}. [name] {str(result.name)[:80]}...")
|
||||
|
||||
await client.close()
|
||||
|
||||
if results:
|
||||
print_result(
|
||||
"Semantic Search", f"SUCCESS - Found {len(results)} results", True
|
||||
)
|
||||
else:
|
||||
print_result(
|
||||
"Semantic Search", "No results (may need time for embedding)", False
|
||||
)
|
||||
|
||||
return len(results) > 0
|
||||
|
||||
except Exception as e:
|
||||
print_result("Semantic Search", f"FAILED: {e}", False)
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
async def test_ollama_embeddings() -> bool:
|
||||
"""Test Ollama embedding generation directly."""
|
||||
print_header("5. Testing Ollama Embeddings")
|
||||
|
||||
ollama_model = os.environ.get("OLLAMA_EMBEDDING_MODEL", "embeddinggemma")
|
||||
ollama_base_url = os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434")
|
||||
|
||||
print(f" Model: {ollama_model}")
|
||||
print(f" Base URL: {ollama_base_url}")
|
||||
print()
|
||||
|
||||
try:
|
||||
import requests
|
||||
|
||||
# Check Ollama status
|
||||
print(" Checking Ollama status...")
|
||||
try:
|
||||
resp = requests.get(f"{ollama_base_url}/api/tags", timeout=5)
|
||||
if resp.status_code != 200:
|
||||
print_result(
|
||||
"Ollama", f"Not responding (status {resp.status_code})", False
|
||||
)
|
||||
return False
|
||||
|
||||
models = [m["name"] for m in resp.json().get("models", [])]
|
||||
embedding_models = [
|
||||
m for m in models if "embed" in m.lower() or "gemma" in m.lower()
|
||||
]
|
||||
print_result("Ollama", f"Running with {len(models)} models", True)
|
||||
print(f" Embedding models: {embedding_models}")
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
print_result("Ollama", "Not running - start with 'ollama serve'", False)
|
||||
return False
|
||||
|
||||
# Test embedding generation
|
||||
print()
|
||||
print(" Generating test embedding...")
|
||||
|
||||
test_text = (
|
||||
"This is a test embedding for Auto Claude memory system using LadybugDB."
|
||||
)
|
||||
|
||||
resp = requests.post(
|
||||
f"{ollama_base_url}/api/embeddings",
|
||||
json={"model": ollama_model, "prompt": test_text},
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
if resp.status_code == 200:
|
||||
data = resp.json()
|
||||
embedding = data.get("embedding", [])
|
||||
print_result("Embedding", f"SUCCESS - {len(embedding)} dimensions", True)
|
||||
print(f" First 5 values: {embedding[:5]}")
|
||||
|
||||
# Verify dimension matches config
|
||||
expected_dim = int(os.environ.get("OLLAMA_EMBEDDING_DIM", 768))
|
||||
if len(embedding) == expected_dim:
|
||||
print_result("Dimension", f"Matches expected ({expected_dim})", True)
|
||||
else:
|
||||
print_result(
|
||||
"Dimension",
|
||||
f"Mismatch! Got {len(embedding)}, expected {expected_dim}",
|
||||
False,
|
||||
)
|
||||
print_info(
|
||||
f"Update OLLAMA_EMBEDDING_DIM={len(embedding)} in your config"
|
||||
)
|
||||
|
||||
return True
|
||||
else:
|
||||
print_result(
|
||||
"Embedding", f"FAILED: {resp.status_code} - {resp.text}", False
|
||||
)
|
||||
return False
|
||||
|
||||
except ImportError:
|
||||
print_result("requests", "Not installed (pip install requests)", False)
|
||||
return False
|
||||
except Exception as e:
|
||||
print_result("Ollama Embeddings", f"FAILED: {e}", False)
|
||||
return False
|
||||
|
||||
|
||||
async def test_graphiti_memory_class(db_path: str, database: str) -> bool:
|
||||
"""Test the GraphitiMemory wrapper class."""
|
||||
print_header("6. Testing GraphitiMemory Class")
|
||||
|
||||
try:
|
||||
from integrations.graphiti.memory import GraphitiMemory
|
||||
|
||||
# Create temporary directories for testing
|
||||
test_spec_dir = Path(tempfile.mkdtemp(prefix="graphiti_test_spec_"))
|
||||
test_project_dir = Path(tempfile.mkdtemp(prefix="graphiti_test_project_"))
|
||||
|
||||
print(f" Spec dir: {test_spec_dir}")
|
||||
print(f" Project dir: {test_project_dir}")
|
||||
print()
|
||||
|
||||
# Override database path via environment
|
||||
os.environ["GRAPHITI_DB_PATH"] = db_path
|
||||
os.environ["GRAPHITI_DATABASE"] = database
|
||||
|
||||
# Create memory instance
|
||||
memory = GraphitiMemory(test_spec_dir, test_project_dir)
|
||||
|
||||
print(f" Is enabled: {memory.is_enabled}")
|
||||
print(f" Group ID: {memory.group_id}")
|
||||
print()
|
||||
|
||||
if not memory.is_enabled:
|
||||
print_info("GraphitiMemory not enabled - check GRAPHITI_ENABLED=true")
|
||||
return True
|
||||
|
||||
# Initialize
|
||||
print(" Initializing...")
|
||||
init_result = await memory.initialize()
|
||||
|
||||
if not init_result:
|
||||
print_result("Initialize", "Failed", False)
|
||||
return False
|
||||
|
||||
print_result("Initialize", "SUCCESS", True)
|
||||
|
||||
# Test save_session_insights
|
||||
print()
|
||||
print(" Testing save_session_insights...")
|
||||
insights = {
|
||||
"subtasks_completed": ["test-subtask-1"],
|
||||
"discoveries": {
|
||||
"files_understood": {"test.py": "Test file"},
|
||||
"patterns_found": ["Pattern: LadybugDB works!"],
|
||||
"gotchas_encountered": [],
|
||||
},
|
||||
"what_worked": ["Using embedded database"],
|
||||
"what_failed": [],
|
||||
"recommendations_for_next_session": ["Continue testing"],
|
||||
}
|
||||
|
||||
save_result = await memory.save_session_insights(
|
||||
session_num=1, insights=insights
|
||||
)
|
||||
print_result(
|
||||
"save_session_insights", "SUCCESS" if save_result else "FAILED", save_result
|
||||
)
|
||||
|
||||
# Test save_pattern
|
||||
print()
|
||||
print(" Testing save_pattern...")
|
||||
pattern_result = await memory.save_pattern(
|
||||
"LadybugDB pattern: Embedded graph database works without Docker"
|
||||
)
|
||||
print_result(
|
||||
"save_pattern", "SUCCESS" if pattern_result else "FAILED", pattern_result
|
||||
)
|
||||
|
||||
# Test get_relevant_context
|
||||
print()
|
||||
print(" Testing get_relevant_context...")
|
||||
await asyncio.sleep(1) # Brief wait for processing
|
||||
|
||||
context = await memory.get_relevant_context("LadybugDB embedded database")
|
||||
print(f" Found {len(context)} context items")
|
||||
|
||||
for item in context[:3]:
|
||||
item_type = item.get("type", "unknown")
|
||||
content = str(item.get("content", ""))[:60]
|
||||
print(f" - [{item_type}] {content}...")
|
||||
|
||||
print_result("get_relevant_context", f"Found {len(context)} items", True)
|
||||
|
||||
# Get status
|
||||
print()
|
||||
print(" Status summary:")
|
||||
status = memory.get_status_summary()
|
||||
for key, value in status.items():
|
||||
print(f" {key}: {value}")
|
||||
|
||||
await memory.close()
|
||||
print_result("GraphitiMemory", "All tests passed", True)
|
||||
return True
|
||||
|
||||
except ImportError as e:
|
||||
print_result("Import", f"Missing: {e}", False)
|
||||
return False
|
||||
except Exception as e:
|
||||
print_result("GraphitiMemory", f"FAILED: {e}", False)
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
async def test_database_contents(db_path: str, database: str) -> bool:
|
||||
"""Show what's in the database (debug)."""
|
||||
print_header("7. Database Contents (Debug)")
|
||||
|
||||
if not apply_ladybug_monkeypatch():
|
||||
print_result("LadybugDB", "Not installed", False)
|
||||
return False
|
||||
|
||||
try:
|
||||
import kuzu
|
||||
|
||||
full_path = Path(db_path) / database
|
||||
if not full_path.exists():
|
||||
print_info(f"Database doesn't exist at {full_path}")
|
||||
return True
|
||||
|
||||
db = kuzu.Database(str(full_path))
|
||||
conn = kuzu.Connection(db)
|
||||
|
||||
# Get table info
|
||||
print(" Checking tables...")
|
||||
|
||||
tables_to_check = ["Episodic", "Entity", "Community"]
|
||||
|
||||
for table in tables_to_check:
|
||||
try:
|
||||
result = conn.execute(f"MATCH (n:{table}) RETURN count(n) as count")
|
||||
df = result.get_as_df()
|
||||
count = df["count"].iloc[0] if len(df) > 0 else 0
|
||||
print(f" {table}: {count} nodes")
|
||||
except Exception as e:
|
||||
if "not exist" in str(e).lower() or "cannot" in str(e).lower():
|
||||
print(f" {table}: (table not created yet)")
|
||||
else:
|
||||
print(f" {table}: Error - {e}")
|
||||
|
||||
# Show sample episodic nodes
|
||||
print()
|
||||
print(" Sample Episodic nodes:")
|
||||
try:
|
||||
result = conn.execute("""
|
||||
MATCH (e:Episodic)
|
||||
RETURN e.name as name, e.created_at as created
|
||||
ORDER BY e.created_at DESC
|
||||
LIMIT 5
|
||||
""")
|
||||
df = result.get_as_df()
|
||||
|
||||
if len(df) == 0:
|
||||
print(" (none)")
|
||||
else:
|
||||
for _, row in df.iterrows():
|
||||
print(f" - {row.get('name', 'unknown')}")
|
||||
except Exception as e:
|
||||
if "Episodic" in str(e):
|
||||
print(" (table not created yet)")
|
||||
else:
|
||||
print(f" Error: {e}")
|
||||
|
||||
print_result("Database Contents", "Displayed", True)
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print_result("Database Contents", f"FAILED: {e}", False)
|
||||
return False
|
||||
|
||||
|
||||
async def main():
|
||||
"""Run all tests."""
|
||||
parser = argparse.ArgumentParser(description="Test Memory System with LadybugDB")
|
||||
parser.add_argument(
|
||||
"--test",
|
||||
choices=[
|
||||
"all",
|
||||
"connection",
|
||||
"save",
|
||||
"keyword",
|
||||
"semantic",
|
||||
"ollama",
|
||||
"memory",
|
||||
"contents",
|
||||
],
|
||||
default="all",
|
||||
help="Which test to run",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--db-path",
|
||||
default=os.path.expanduser("~/.auto-claude/memories"),
|
||||
help="Database path",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--database",
|
||||
default="test_memory",
|
||||
help="Database name (use 'test_memory' for testing)",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print(" MEMORY SYSTEM TEST SUITE (LadybugDB)")
|
||||
print("=" * 60)
|
||||
|
||||
# Configuration check
|
||||
print_header("0. Configuration Check")
|
||||
|
||||
print(f" Database path: {args.db_path}")
|
||||
print(f" Database name: {args.database}")
|
||||
print()
|
||||
|
||||
# Check environment
|
||||
graphiti_enabled = os.environ.get("GRAPHITI_ENABLED", "").lower() == "true"
|
||||
embedder_provider = os.environ.get("GRAPHITI_EMBEDDER_PROVIDER", "")
|
||||
|
||||
print_result("GRAPHITI_ENABLED", str(graphiti_enabled), graphiti_enabled)
|
||||
print_result(
|
||||
"GRAPHITI_EMBEDDER_PROVIDER",
|
||||
embedder_provider or "(not set)",
|
||||
bool(embedder_provider),
|
||||
)
|
||||
|
||||
if embedder_provider == "ollama":
|
||||
ollama_model = os.environ.get("OLLAMA_EMBEDDING_MODEL", "")
|
||||
ollama_dim = os.environ.get("OLLAMA_EMBEDDING_DIM", "")
|
||||
print_result(
|
||||
"OLLAMA_EMBEDDING_MODEL", ollama_model or "(not set)", bool(ollama_model)
|
||||
)
|
||||
print_result(
|
||||
"OLLAMA_EMBEDDING_DIM", ollama_dim or "(not set)", bool(ollama_dim)
|
||||
)
|
||||
elif embedder_provider == "openai":
|
||||
has_key = bool(os.environ.get("OPENAI_API_KEY"))
|
||||
print_result("OPENAI_API_KEY", "Set" if has_key else "Not set", has_key)
|
||||
|
||||
# Run tests based on selection
|
||||
test = args.test
|
||||
group_id = None
|
||||
|
||||
if test in ["all", "connection"]:
|
||||
await test_ladybugdb_connection(args.db_path, args.database)
|
||||
|
||||
if test in ["all", "ollama"]:
|
||||
await test_ollama_embeddings()
|
||||
|
||||
if test in ["all", "save"]:
|
||||
_, group_id = await test_save_episode(args.db_path, args.database)
|
||||
if group_id:
|
||||
print("\n Waiting 2 seconds for embedding processing...")
|
||||
await asyncio.sleep(2)
|
||||
|
||||
if test in ["all", "keyword"]:
|
||||
await test_keyword_search(args.db_path, args.database)
|
||||
|
||||
if test in ["all", "semantic"]:
|
||||
await test_semantic_search(
|
||||
args.db_path, args.database, group_id or "ladybug_test_group"
|
||||
)
|
||||
|
||||
if test in ["all", "memory"]:
|
||||
await test_graphiti_memory_class(args.db_path, args.database)
|
||||
|
||||
if test in ["all", "contents"]:
|
||||
await test_database_contents(args.db_path, args.database)
|
||||
|
||||
print_header("TEST SUMMARY")
|
||||
print(" Tests completed. Check the results above for any failures.")
|
||||
print()
|
||||
print(" Quick commands:")
|
||||
print(" # Run all tests:")
|
||||
print(" python integrations/graphiti/run_graphiti_memory_test.py")
|
||||
print()
|
||||
print(" # Test just Ollama embeddings:")
|
||||
print(" python integrations/graphiti/run_graphiti_memory_test.py --test ollama")
|
||||
print()
|
||||
print(" # Test with production database:")
|
||||
print(
|
||||
" python integrations/graphiti/run_graphiti_memory_test.py --database auto_claude_memory"
|
||||
)
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,862 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test Script for Ollama Embedding Memory Integration
|
||||
====================================================
|
||||
|
||||
This test validates that the memory system works correctly with local Ollama
|
||||
embedding models (like embeddinggemma, nomic-embed-text) for creating and
|
||||
retrieving memories in the hybrid RAG system.
|
||||
|
||||
The test covers:
|
||||
1. Ollama embedding generation (direct API test)
|
||||
2. Creating memories with Ollama embeddings via GraphitiMemory
|
||||
3. Retrieving memories via semantic search
|
||||
4. Verifying the full create → store → retrieve cycle
|
||||
|
||||
Prerequisites:
|
||||
1. Install Ollama: https://ollama.ai/
|
||||
2. Pull an embedding model:
|
||||
ollama pull embeddinggemma # 768 dimensions (lightweight)
|
||||
ollama pull nomic-embed-text # 768 dimensions (good quality)
|
||||
3. Pull an LLM model (for knowledge graph construction):
|
||||
ollama pull deepseek-r1:7b # or llama3.2:3b, mistral:7b
|
||||
4. Start Ollama server: ollama serve
|
||||
5. Configure environment:
|
||||
export GRAPHITI_ENABLED=true
|
||||
export GRAPHITI_LLM_PROVIDER=ollama
|
||||
export GRAPHITI_EMBEDDER_PROVIDER=ollama
|
||||
export OLLAMA_LLM_MODEL=deepseek-r1:7b
|
||||
export OLLAMA_EMBEDDING_MODEL=embeddinggemma
|
||||
export OLLAMA_EMBEDDING_DIM=768
|
||||
|
||||
NOTE: graphiti-core internally uses an OpenAI reranker for search ranking.
|
||||
For full offline operation, set a dummy key: export OPENAI_API_KEY=dummy
|
||||
The reranker will fail at search time, but embedding creation works.
|
||||
For production, use OpenAI API key for best search quality.
|
||||
|
||||
Usage:
|
||||
cd apps/backend
|
||||
python integrations/graphiti/run_ollama_embedding_test.py
|
||||
|
||||
# Run specific tests:
|
||||
python integrations/graphiti/run_ollama_embedding_test.py --test embeddings
|
||||
python integrations/graphiti/run_ollama_embedding_test.py --test create
|
||||
python integrations/graphiti/run_ollama_embedding_test.py --test retrieve
|
||||
python integrations/graphiti/run_ollama_embedding_test.py --test full-cycle
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
# Add backend to path
|
||||
backend_dir = Path(__file__).parent.parent.parent.parent
|
||||
sys.path.insert(0, str(backend_dir))
|
||||
|
||||
# Load .env file
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
|
||||
env_file = backend_dir / ".env"
|
||||
if env_file.exists():
|
||||
load_dotenv(env_file)
|
||||
print(f"Loaded .env from {env_file}")
|
||||
except ImportError:
|
||||
print("Note: python-dotenv not installed, using environment variables only")
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Helper Functions
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def print_header(title: str):
|
||||
"""Print a section header."""
|
||||
print("\n" + "=" * 70)
|
||||
print(f" {title}")
|
||||
print("=" * 70 + "\n")
|
||||
|
||||
|
||||
def print_result(label: str, value: str, success: bool = True):
|
||||
"""Print a result line."""
|
||||
status = "PASS" if success else "FAIL"
|
||||
print(f" [{status}] {label}: {value}")
|
||||
|
||||
|
||||
def print_info(message: str):
|
||||
"""Print an info line."""
|
||||
print(f" INFO: {message}")
|
||||
|
||||
|
||||
def print_step(step: int, message: str):
|
||||
"""Print a step indicator."""
|
||||
print(f"\n Step {step}: {message}")
|
||||
|
||||
|
||||
def apply_ladybug_monkeypatch():
|
||||
"""Apply LadybugDB monkeypatch for embedded database support."""
|
||||
try:
|
||||
import real_ladybug
|
||||
|
||||
sys.modules["kuzu"] = real_ladybug
|
||||
return True
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Try native kuzu as fallback
|
||||
try:
|
||||
import kuzu # noqa: F401
|
||||
|
||||
return True
|
||||
except ImportError:
|
||||
return False
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Test 1: Ollama Embedding Generation
|
||||
# ============================================================================
|
||||
|
||||
|
||||
async def test_ollama_embeddings() -> bool:
|
||||
"""
|
||||
Test Ollama embedding generation directly via API.
|
||||
|
||||
This validates that Ollama is running and can generate embeddings
|
||||
with the configured model.
|
||||
"""
|
||||
print_header("Test 1: Ollama Embedding Generation")
|
||||
|
||||
ollama_model = os.environ.get("OLLAMA_EMBEDDING_MODEL", "embeddinggemma")
|
||||
ollama_base_url = os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434")
|
||||
expected_dim = int(os.environ.get("OLLAMA_EMBEDDING_DIM", "768"))
|
||||
|
||||
print(f" Ollama Model: {ollama_model}")
|
||||
print(f" Base URL: {ollama_base_url}")
|
||||
print(f" Expected Dimension: {expected_dim}")
|
||||
print()
|
||||
|
||||
try:
|
||||
import requests
|
||||
except ImportError:
|
||||
print_result("requests library", "Not installed - pip install requests", False)
|
||||
return False
|
||||
|
||||
# Step 1: Check Ollama is running
|
||||
print_step(1, "Checking Ollama server status")
|
||||
try:
|
||||
resp = requests.get(f"{ollama_base_url}/api/tags", timeout=10)
|
||||
if resp.status_code != 200:
|
||||
print_result(
|
||||
"Ollama server",
|
||||
f"Not responding (status {resp.status_code})",
|
||||
False,
|
||||
)
|
||||
return False
|
||||
|
||||
models = resp.json().get("models", [])
|
||||
model_names = [m.get("name", "") for m in models]
|
||||
print_result("Ollama server", f"Running with {len(models)} models", True)
|
||||
|
||||
# Check if embedding model is available
|
||||
embedding_model_found = any(
|
||||
ollama_model in name or ollama_model.split(":")[0] in name
|
||||
for name in model_names
|
||||
)
|
||||
if not embedding_model_found:
|
||||
print_info(f"Model '{ollama_model}' not found. Available: {model_names}")
|
||||
print_info(f"Pull it with: ollama pull {ollama_model}")
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
print_result(
|
||||
"Ollama server",
|
||||
"Not running - start with 'ollama serve'",
|
||||
False,
|
||||
)
|
||||
return False
|
||||
|
||||
# Step 2: Generate test embedding
|
||||
print_step(2, "Generating test embeddings")
|
||||
|
||||
test_texts = [
|
||||
"This is a test memory about implementing OAuth authentication.",
|
||||
"The user prefers using TypeScript for frontend development.",
|
||||
"A gotcha discovered: always validate JWT tokens on the server side.",
|
||||
]
|
||||
|
||||
embeddings = []
|
||||
for i, text in enumerate(test_texts):
|
||||
resp = requests.post(
|
||||
f"{ollama_base_url}/api/embeddings",
|
||||
json={"model": ollama_model, "prompt": text},
|
||||
timeout=60,
|
||||
)
|
||||
|
||||
if resp.status_code != 200:
|
||||
print_result(
|
||||
f"Embedding {i + 1}",
|
||||
f"Failed: {resp.status_code} - {resp.text[:100]}",
|
||||
False,
|
||||
)
|
||||
return False
|
||||
|
||||
data = resp.json()
|
||||
embedding = data.get("embedding", [])
|
||||
embeddings.append(embedding)
|
||||
|
||||
print_result(
|
||||
f"Embedding {i + 1}",
|
||||
f"Generated {len(embedding)} dimensions",
|
||||
True,
|
||||
)
|
||||
|
||||
# Step 3: Validate embedding dimensions
|
||||
print_step(3, "Validating embedding dimensions")
|
||||
|
||||
for i, embedding in enumerate(embeddings):
|
||||
if len(embedding) != expected_dim:
|
||||
print_result(
|
||||
f"Embedding {i + 1} dimension",
|
||||
f"Mismatch! Got {len(embedding)}, expected {expected_dim}",
|
||||
False,
|
||||
)
|
||||
print_info(f"Update OLLAMA_EMBEDDING_DIM={len(embedding)} in your config")
|
||||
return False
|
||||
print_result(
|
||||
f"Embedding {i + 1} dimension", f"{len(embedding)} matches expected", True
|
||||
)
|
||||
|
||||
# Step 4: Test embedding similarity (basic sanity check)
|
||||
print_step(4, "Testing embedding similarity")
|
||||
|
||||
def cosine_similarity(a, b):
|
||||
"""Calculate cosine similarity between two vectors."""
|
||||
dot_product = sum(x * y for x, y in zip(a, b))
|
||||
norm_a = sum(x * x for x in a) ** 0.5
|
||||
norm_b = sum(x * x for x in b) ** 0.5
|
||||
return dot_product / (norm_a * norm_b) if norm_a and norm_b else 0
|
||||
|
||||
# Generate embedding for a similar query
|
||||
query = "OAuth authentication implementation"
|
||||
resp = requests.post(
|
||||
f"{ollama_base_url}/api/embeddings",
|
||||
json={"model": ollama_model, "prompt": query},
|
||||
timeout=60,
|
||||
)
|
||||
query_embedding = resp.json().get("embedding", [])
|
||||
|
||||
similarities = [cosine_similarity(query_embedding, emb) for emb in embeddings]
|
||||
|
||||
print(f" Query: '{query}'")
|
||||
print(" Similarities to test texts:")
|
||||
for i, (text, sim) in enumerate(zip(test_texts, similarities)):
|
||||
print(f" {i + 1}. {sim:.4f} - '{text[:50]}...'")
|
||||
|
||||
# First text (about OAuth) should have highest similarity to OAuth query
|
||||
if similarities[0] > similarities[1] and similarities[0] > similarities[2]:
|
||||
print_result("Semantic similarity", "OAuth query matches OAuth text best", True)
|
||||
else:
|
||||
print_info("Similarity ordering may vary - embeddings are still working")
|
||||
|
||||
print()
|
||||
print_result("Ollama Embeddings", "All tests passed", True)
|
||||
return True
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Test 2: Memory Creation with Ollama
|
||||
# ============================================================================
|
||||
|
||||
|
||||
async def test_memory_creation(test_db_path: Path) -> tuple[Path, Path, bool]:
|
||||
"""
|
||||
Test creating memories using GraphitiMemory with Ollama embeddings.
|
||||
|
||||
Returns:
|
||||
Tuple of (spec_dir, project_dir, success)
|
||||
"""
|
||||
print_header("Test 2: Memory Creation with Ollama Embeddings")
|
||||
|
||||
# Create test directories
|
||||
spec_dir = test_db_path / "test_spec"
|
||||
project_dir = test_db_path / "test_project"
|
||||
spec_dir.mkdir(parents=True, exist_ok=True)
|
||||
project_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
print(f" Spec dir: {spec_dir}")
|
||||
print(f" Project dir: {project_dir}")
|
||||
print(f" Database path: {test_db_path}")
|
||||
print()
|
||||
|
||||
# Override database path for testing
|
||||
os.environ["GRAPHITI_DB_PATH"] = str(test_db_path / "graphiti_db")
|
||||
os.environ["GRAPHITI_DATABASE"] = "test_ollama_memory"
|
||||
|
||||
try:
|
||||
from integrations.graphiti.memory import GraphitiMemory
|
||||
except ImportError as e:
|
||||
print_result("Import GraphitiMemory", f"Failed: {e}", False)
|
||||
return spec_dir, project_dir, False
|
||||
|
||||
# Step 1: Initialize GraphitiMemory
|
||||
print_step(1, "Initializing GraphitiMemory")
|
||||
|
||||
memory = GraphitiMemory(spec_dir, project_dir)
|
||||
print(f" Is enabled: {memory.is_enabled}")
|
||||
print(f" Group ID: {memory.group_id}")
|
||||
|
||||
if not memory.is_enabled:
|
||||
print_result(
|
||||
"GraphitiMemory",
|
||||
"Not enabled - check GRAPHITI_ENABLED=true",
|
||||
False,
|
||||
)
|
||||
return spec_dir, project_dir, False
|
||||
|
||||
init_result = await memory.initialize()
|
||||
if not init_result:
|
||||
print_result("Initialize", "Failed to initialize", False)
|
||||
return spec_dir, project_dir, False
|
||||
|
||||
print_result("Initialize", "SUCCESS", True)
|
||||
|
||||
# Step 2: Save session insights
|
||||
print_step(2, "Saving session insights")
|
||||
|
||||
session_insights = {
|
||||
"subtasks_completed": ["implement-oauth-login", "add-jwt-validation"],
|
||||
"discoveries": {
|
||||
"files_understood": {
|
||||
"auth/oauth.py": "OAuth 2.0 flow implementation with Google/GitHub",
|
||||
"auth/jwt.py": "JWT token generation and validation utilities",
|
||||
},
|
||||
"patterns_found": [
|
||||
"Pattern: Use refresh tokens for long-lived sessions",
|
||||
"Pattern: Store tokens in httpOnly cookies for security",
|
||||
],
|
||||
"gotchas_encountered": [
|
||||
"Gotcha: Always validate JWT signature on server side",
|
||||
"Gotcha: OAuth state parameter prevents CSRF attacks",
|
||||
],
|
||||
},
|
||||
"what_worked": [
|
||||
"Using PyJWT for token handling",
|
||||
"Separating OAuth providers into individual modules",
|
||||
],
|
||||
"what_failed": [],
|
||||
"recommendations_for_next_session": [
|
||||
"Consider adding refresh token rotation",
|
||||
"Add rate limiting to auth endpoints",
|
||||
],
|
||||
}
|
||||
|
||||
save_result = await memory.save_session_insights(
|
||||
session_num=1, insights=session_insights
|
||||
)
|
||||
print_result(
|
||||
"save_session_insights", "SUCCESS" if save_result else "FAILED", save_result
|
||||
)
|
||||
|
||||
# Step 3: Save patterns
|
||||
print_step(3, "Saving code patterns")
|
||||
|
||||
patterns = [
|
||||
"OAuth implementation uses authorization code flow for web apps",
|
||||
"JWT tokens include user ID, roles, and expiration in payload",
|
||||
"Token refresh happens automatically when access token expires",
|
||||
]
|
||||
|
||||
for i, pattern in enumerate(patterns):
|
||||
result = await memory.save_pattern(pattern)
|
||||
print_result(f"save_pattern {i + 1}", "SUCCESS" if result else "FAILED", result)
|
||||
|
||||
# Step 4: Save gotchas
|
||||
print_step(4, "Saving gotchas (pitfalls)")
|
||||
|
||||
gotchas = [
|
||||
"Never store config values in frontend code or files checked into git",
|
||||
"API redirect URIs must exactly match the registered URIs",
|
||||
"Cache expiration times should be short for performance (15 min default)",
|
||||
]
|
||||
|
||||
for i, gotcha in enumerate(gotchas):
|
||||
result = await memory.save_gotcha(gotcha)
|
||||
print_result(f"save_gotcha {i + 1}", "SUCCESS" if result else "FAILED", result)
|
||||
|
||||
# Step 5: Save codebase discoveries
|
||||
print_step(5, "Saving codebase discoveries")
|
||||
|
||||
discoveries = {
|
||||
"api/routes/users.py": "User management API endpoints (list, create, update)",
|
||||
"middleware/logging.py": "Request logging middleware for all routes",
|
||||
"models/user.py": "User model with profile data and role management",
|
||||
"services/notifications.py": "Notification service integrations (email, SMS, push)",
|
||||
}
|
||||
|
||||
discovery_result = await memory.save_codebase_discoveries(discoveries)
|
||||
print_result(
|
||||
"save_codebase_discoveries",
|
||||
"SUCCESS" if discovery_result else "FAILED",
|
||||
discovery_result,
|
||||
)
|
||||
|
||||
# Brief wait for embedding processing
|
||||
print()
|
||||
print_info("Waiting 3 seconds for embedding processing...")
|
||||
await asyncio.sleep(3)
|
||||
|
||||
await memory.close()
|
||||
|
||||
print()
|
||||
print_result("Memory Creation", "All memories saved successfully", True)
|
||||
return spec_dir, project_dir, True
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Test 3: Memory Retrieval with Semantic Search
|
||||
# ============================================================================
|
||||
|
||||
|
||||
async def test_memory_retrieval(spec_dir: Path, project_dir: Path) -> bool:
|
||||
"""
|
||||
Test retrieving memories using semantic search with Ollama embeddings.
|
||||
|
||||
This validates that saved memories can be found via semantic similarity.
|
||||
"""
|
||||
print_header("Test 3: Memory Retrieval with Semantic Search")
|
||||
|
||||
try:
|
||||
from integrations.graphiti.memory import GraphitiMemory
|
||||
except ImportError as e:
|
||||
print_result("Import GraphitiMemory", f"Failed: {e}", False)
|
||||
return False
|
||||
|
||||
# Step 1: Initialize memory (reconnect)
|
||||
print_step(1, "Reconnecting to GraphitiMemory")
|
||||
|
||||
memory = GraphitiMemory(spec_dir, project_dir)
|
||||
init_result = await memory.initialize()
|
||||
|
||||
if not init_result:
|
||||
print_result("Initialize", "Failed to reconnect", False)
|
||||
return False
|
||||
|
||||
print_result("Initialize", "Reconnected successfully", True)
|
||||
|
||||
# Step 2: Semantic search for API-related content
|
||||
print_step(2, "Searching for API-related memories")
|
||||
|
||||
api_query = "How do the API endpoints work in this project?"
|
||||
results = await memory.get_relevant_context(api_query, num_results=5)
|
||||
|
||||
print(f" Query: '{api_query}'")
|
||||
print(f" Found {len(results)} results:")
|
||||
|
||||
api_found = False
|
||||
for i, result in enumerate(results):
|
||||
content = result.get("content", "")[:100]
|
||||
result_type = result.get("type", "unknown")
|
||||
score = result.get("score", 0)
|
||||
print(f" {i + 1}. [{result_type}] (score: {score:.4f}) {content}...")
|
||||
if "api" in content.lower() or "routes" in content.lower():
|
||||
api_found = True
|
||||
|
||||
if api_found:
|
||||
print_result("API search", "Found API-related content", True)
|
||||
else:
|
||||
print_info("API content may not be in top results - checking other queries")
|
||||
|
||||
# Step 3: Search for middleware-related content
|
||||
print_step(3, "Searching for middleware patterns")
|
||||
|
||||
middleware_query = "middleware and request handling best practices"
|
||||
results = await memory.get_relevant_context(middleware_query, num_results=5)
|
||||
|
||||
print(f" Query: '{middleware_query}'")
|
||||
print(f" Found {len(results)} results:")
|
||||
|
||||
middleware_found = False
|
||||
for i, result in enumerate(results):
|
||||
content = result.get("content", "")[:100]
|
||||
result_type = result.get("type", "unknown")
|
||||
score = result.get("score", 0)
|
||||
print(f" {i + 1}. [{result_type}] (score: {score:.4f}) {content}...")
|
||||
if "middleware" in content.lower() or "routes" in content.lower():
|
||||
middleware_found = True
|
||||
|
||||
print_result(
|
||||
"Middleware search",
|
||||
"Found middleware-related content" if middleware_found else "No direct matches",
|
||||
middleware_found or len(results) > 0,
|
||||
)
|
||||
|
||||
# Step 4: Get session history
|
||||
print_step(4, "Retrieving session history")
|
||||
|
||||
history = await memory.get_session_history(limit=3)
|
||||
print(f" Found {len(history)} session records:")
|
||||
|
||||
for i, session in enumerate(history):
|
||||
session_num = session.get("session_number", "?")
|
||||
subtasks = session.get("subtasks_completed", [])
|
||||
print(f" Session {session_num}: {len(subtasks)} subtasks completed")
|
||||
for subtask in subtasks[:3]:
|
||||
print(f" - {subtask}")
|
||||
|
||||
print_result(
|
||||
"Session history", f"Retrieved {len(history)} sessions", len(history) > 0
|
||||
)
|
||||
|
||||
# Step 5: Get status summary
|
||||
print_step(5, "Memory status summary")
|
||||
|
||||
status = memory.get_status_summary()
|
||||
for key, value in status.items():
|
||||
print(f" {key}: {value}")
|
||||
|
||||
await memory.close()
|
||||
|
||||
print()
|
||||
all_passed = len(results) > 0 and len(history) > 0
|
||||
print_result(
|
||||
"Memory Retrieval",
|
||||
"All retrieval tests passed" if all_passed else "Some tests had issues",
|
||||
all_passed,
|
||||
)
|
||||
return all_passed
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Test 4: Full Create → Store → Retrieve Cycle
|
||||
# ============================================================================
|
||||
|
||||
|
||||
async def test_full_cycle(test_db_path: Path) -> bool:
|
||||
"""
|
||||
Test the complete memory lifecycle:
|
||||
1. Create unique test data
|
||||
2. Store in graph database with Ollama embeddings
|
||||
3. Search and retrieve via semantic similarity
|
||||
4. Verify retrieved data matches what was stored
|
||||
"""
|
||||
print_header("Test 4: Full Create-Store-Retrieve Cycle")
|
||||
|
||||
# Create fresh test directories
|
||||
spec_dir = test_db_path / "cycle_test_spec"
|
||||
project_dir = test_db_path / "cycle_test_project"
|
||||
spec_dir.mkdir(parents=True, exist_ok=True)
|
||||
project_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Override database path for testing
|
||||
os.environ["GRAPHITI_DB_PATH"] = str(test_db_path / "graphiti_db")
|
||||
os.environ["GRAPHITI_DATABASE"] = "test_full_cycle"
|
||||
|
||||
try:
|
||||
from integrations.graphiti.memory import GraphitiMemory
|
||||
except ImportError as e:
|
||||
print_result("Import", f"Failed: {e}", False)
|
||||
return False
|
||||
|
||||
# Step 1: Create unique test content
|
||||
print_step(1, "Creating unique test content")
|
||||
|
||||
unique_id = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
unique_pattern = (
|
||||
f"Unique pattern {unique_id}: Use dependency injection for database connections"
|
||||
)
|
||||
unique_gotcha = f"Unique gotcha {unique_id}: Always close database connections in finally blocks"
|
||||
|
||||
print(f" Unique ID: {unique_id}")
|
||||
print(f" Pattern: {unique_pattern[:60]}...")
|
||||
print(f" Gotcha: {unique_gotcha[:60]}...")
|
||||
|
||||
# Step 2: Store the content
|
||||
print_step(2, "Storing content in memory system")
|
||||
|
||||
memory = GraphitiMemory(spec_dir, project_dir)
|
||||
init_result = await memory.initialize()
|
||||
|
||||
if not init_result:
|
||||
print_result("Initialize", "Failed", False)
|
||||
return False
|
||||
|
||||
print_result("Initialize", "SUCCESS", True)
|
||||
|
||||
pattern_result = await memory.save_pattern(unique_pattern)
|
||||
print_result(
|
||||
"save_pattern", "SUCCESS" if pattern_result else "FAILED", pattern_result
|
||||
)
|
||||
|
||||
gotcha_result = await memory.save_gotcha(unique_gotcha)
|
||||
print_result("save_gotcha", "SUCCESS" if gotcha_result else "FAILED", gotcha_result)
|
||||
|
||||
# Wait for embedding processing
|
||||
print()
|
||||
print_info("Waiting 4 seconds for embedding processing and indexing...")
|
||||
await asyncio.sleep(4)
|
||||
|
||||
# Step 3: Search for the unique content
|
||||
print_step(3, "Searching for unique content")
|
||||
|
||||
# Search for the pattern
|
||||
pattern_query = "dependency injection database connections"
|
||||
pattern_results = await memory.get_relevant_context(pattern_query, num_results=5)
|
||||
|
||||
print(f" Query: '{pattern_query}'")
|
||||
print(f" Found {len(pattern_results)} results")
|
||||
|
||||
pattern_found = False
|
||||
for result in pattern_results:
|
||||
content = result.get("content", "")
|
||||
if unique_id in content:
|
||||
pattern_found = True
|
||||
print(f" MATCH: {content[:80]}...")
|
||||
|
||||
print_result(
|
||||
"Pattern retrieval",
|
||||
f"Found unique pattern (ID: {unique_id})"
|
||||
if pattern_found
|
||||
else "Unique pattern not in top results",
|
||||
pattern_found,
|
||||
)
|
||||
|
||||
# Search for the gotcha
|
||||
gotcha_query = "database connection cleanup finally block"
|
||||
gotcha_results = await memory.get_relevant_context(gotcha_query, num_results=5)
|
||||
|
||||
print(f" Query: '{gotcha_query}'")
|
||||
print(f" Found {len(gotcha_results)} results")
|
||||
|
||||
gotcha_found = False
|
||||
for result in gotcha_results:
|
||||
content = result.get("content", "")
|
||||
if unique_id in content:
|
||||
gotcha_found = True
|
||||
print(f" MATCH: {content[:80]}...")
|
||||
|
||||
print_result(
|
||||
"Gotcha retrieval",
|
||||
f"Found unique gotcha (ID: {unique_id})"
|
||||
if gotcha_found
|
||||
else "Unique gotcha not in top results",
|
||||
gotcha_found,
|
||||
)
|
||||
|
||||
# Step 4: Verify semantic similarity works
|
||||
print_step(4, "Verifying semantic similarity")
|
||||
|
||||
# Search with semantically similar but different wording
|
||||
alt_query = "closing connections properly in error handling"
|
||||
alt_results = await memory.get_relevant_context(alt_query, num_results=3)
|
||||
|
||||
print(f" Alternative query: '{alt_query}'")
|
||||
print(f" Found {len(alt_results)} semantically similar results:")
|
||||
|
||||
for i, result in enumerate(alt_results):
|
||||
content = result.get("content", "")[:80]
|
||||
score = result.get("score", 0)
|
||||
print(f" {i + 1}. (score: {score:.4f}) {content}...")
|
||||
|
||||
semantic_works = len(alt_results) > 0
|
||||
print_result(
|
||||
"Semantic similarity",
|
||||
"Working - found related content" if semantic_works else "No results",
|
||||
semantic_works,
|
||||
)
|
||||
|
||||
await memory.close()
|
||||
|
||||
# Summary
|
||||
print()
|
||||
cycle_passed = (
|
||||
pattern_result
|
||||
and gotcha_result
|
||||
and (pattern_found or gotcha_found or len(alt_results) > 0)
|
||||
)
|
||||
print_result(
|
||||
"Full Cycle Test",
|
||||
"Create-Store-Retrieve cycle verified"
|
||||
if cycle_passed
|
||||
else "Some steps had issues",
|
||||
cycle_passed,
|
||||
)
|
||||
|
||||
return cycle_passed
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Main Entry Point
|
||||
# ============================================================================
|
||||
|
||||
|
||||
async def main():
|
||||
"""Run Ollama embedding memory tests."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Test Ollama Embedding Memory Integration"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--test",
|
||||
choices=["all", "embeddings", "create", "retrieve", "full-cycle"],
|
||||
default="all",
|
||||
help="Which test to run",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--keep-db",
|
||||
action="store_true",
|
||||
help="Keep test database after completion (default: cleanup)",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print(" OLLAMA EMBEDDING MEMORY TEST SUITE")
|
||||
print("=" * 70)
|
||||
|
||||
# Configuration check
|
||||
print_header("Configuration Check")
|
||||
|
||||
config_items = {
|
||||
"GRAPHITI_ENABLED": os.environ.get("GRAPHITI_ENABLED", ""),
|
||||
"GRAPHITI_LLM_PROVIDER": os.environ.get("GRAPHITI_LLM_PROVIDER", ""),
|
||||
"GRAPHITI_EMBEDDER_PROVIDER": os.environ.get("GRAPHITI_EMBEDDER_PROVIDER", ""),
|
||||
"OLLAMA_LLM_MODEL": os.environ.get("OLLAMA_LLM_MODEL", ""),
|
||||
"OLLAMA_EMBEDDING_MODEL": os.environ.get("OLLAMA_EMBEDDING_MODEL", ""),
|
||||
"OLLAMA_EMBEDDING_DIM": os.environ.get("OLLAMA_EMBEDDING_DIM", ""),
|
||||
"OLLAMA_BASE_URL": os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434"),
|
||||
"OPENAI_API_KEY": "(set)"
|
||||
if os.environ.get("OPENAI_API_KEY")
|
||||
else "(not set - needed for reranker)",
|
||||
}
|
||||
|
||||
all_configured = True
|
||||
required_keys = [
|
||||
"GRAPHITI_ENABLED",
|
||||
"GRAPHITI_LLM_PROVIDER",
|
||||
"GRAPHITI_EMBEDDER_PROVIDER",
|
||||
"OLLAMA_LLM_MODEL",
|
||||
"OLLAMA_EMBEDDING_MODEL",
|
||||
]
|
||||
|
||||
for key, value in config_items.items():
|
||||
is_optional = key in [
|
||||
"OLLAMA_BASE_URL",
|
||||
"OPENAI_API_KEY",
|
||||
"OLLAMA_EMBEDDING_DIM",
|
||||
]
|
||||
is_set = bool(value) if not is_optional else True
|
||||
display_value = value or "(not set)"
|
||||
if key == "OPENAI_API_KEY":
|
||||
display_value = value # Already formatted above
|
||||
is_set = True # Optional for testing
|
||||
print_result(key, display_value, is_set)
|
||||
if key in required_keys and not bool(os.environ.get(key)):
|
||||
all_configured = False
|
||||
|
||||
if not all_configured:
|
||||
print()
|
||||
print(" Missing required configuration. Please set:")
|
||||
print(" export GRAPHITI_ENABLED=true")
|
||||
print(" export GRAPHITI_LLM_PROVIDER=ollama")
|
||||
print(" export GRAPHITI_EMBEDDER_PROVIDER=ollama")
|
||||
print(" export OLLAMA_LLM_MODEL=deepseek-r1:7b")
|
||||
print(" export OLLAMA_EMBEDDING_MODEL=embeddinggemma")
|
||||
print(" export OLLAMA_EMBEDDING_DIM=768")
|
||||
print(" export OPENAI_API_KEY=dummy # For graphiti-core reranker")
|
||||
print()
|
||||
return
|
||||
|
||||
# Check LadybugDB
|
||||
if not apply_ladybug_monkeypatch():
|
||||
print()
|
||||
print_result("LadybugDB", "Not installed - pip install real-ladybug", False)
|
||||
return
|
||||
|
||||
print_result("LadybugDB", "Installed", True)
|
||||
|
||||
# Create temp directory for test database
|
||||
test_db_path = Path(tempfile.mkdtemp(prefix="ollama_memory_test_"))
|
||||
print()
|
||||
print_info(f"Test database: {test_db_path}")
|
||||
|
||||
# Run tests
|
||||
test = args.test
|
||||
results = {}
|
||||
|
||||
try:
|
||||
if test in ["all", "embeddings"]:
|
||||
results["embeddings"] = await test_ollama_embeddings()
|
||||
|
||||
spec_dir = None
|
||||
project_dir = None
|
||||
|
||||
if test in ["all", "create"]:
|
||||
spec_dir, project_dir, results["create"] = await test_memory_creation(
|
||||
test_db_path
|
||||
)
|
||||
|
||||
if test in ["all", "retrieve"]:
|
||||
if spec_dir and project_dir:
|
||||
results["retrieve"] = await test_memory_retrieval(spec_dir, project_dir)
|
||||
else:
|
||||
print_info(
|
||||
"Skipping retrieve test - no spec/project dir from create test"
|
||||
)
|
||||
|
||||
if test in ["all", "full-cycle"]:
|
||||
results["full-cycle"] = await test_full_cycle(test_db_path)
|
||||
|
||||
finally:
|
||||
# Cleanup unless --keep-db specified
|
||||
if not args.keep_db and test_db_path.exists():
|
||||
print()
|
||||
print_info(f"Cleaning up test database: {test_db_path}")
|
||||
shutil.rmtree(test_db_path, ignore_errors=True)
|
||||
|
||||
# Summary
|
||||
print_header("TEST SUMMARY")
|
||||
|
||||
all_passed = True
|
||||
for test_name, passed in results.items():
|
||||
status = "PASSED" if passed else "FAILED"
|
||||
print(f" {test_name}: {status}")
|
||||
if not passed:
|
||||
all_passed = False
|
||||
|
||||
print()
|
||||
if all_passed:
|
||||
print(" All tests PASSED!")
|
||||
print()
|
||||
print(" The memory system is working correctly with Ollama embeddings.")
|
||||
print(" Memories can be created and retrieved using semantic search.")
|
||||
else:
|
||||
print(" Some tests FAILED. Check the output above for details.")
|
||||
print()
|
||||
print(" Common issues:")
|
||||
print(" - Ollama not running: ollama serve")
|
||||
print(" - Model not pulled: ollama pull embeddinggemma")
|
||||
print(" - Wrong dimension: Update OLLAMA_EMBEDDING_DIM to match model")
|
||||
|
||||
print()
|
||||
print(" Commands:")
|
||||
print(" # Run all tests:")
|
||||
print(" python integrations/graphiti/run_ollama_embedding_test.py")
|
||||
print()
|
||||
print(" # Run specific test:")
|
||||
print(
|
||||
" python integrations/graphiti/run_ollama_embedding_test.py --test embeddings"
|
||||
)
|
||||
print(
|
||||
" python integrations/graphiti/run_ollama_embedding_test.py --test full-cycle"
|
||||
)
|
||||
print()
|
||||
print(" # Keep database for inspection:")
|
||||
print(" python integrations/graphiti/run_ollama_embedding_test.py --keep-db")
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1 @@
|
||||
"""Tests for Graphiti memory integration."""
|
||||
@@ -0,0 +1,610 @@
|
||||
"""
|
||||
Pytest configuration and fixtures for graphiti integration tests.
|
||||
|
||||
This module provides shared fixtures for testing the memory system integration,
|
||||
including mocks for external dependencies, test configurations, and client fixtures.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock, Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
# Add the backend directory to sys.path to allow imports
|
||||
backend_dir = Path(__file__).parent.parent.parent.parent
|
||||
sys.path.insert(0, str(backend_dir))
|
||||
|
||||
|
||||
def pytest_collection_modifyitems(config, items):
|
||||
"""
|
||||
Exclude validator functions from test collection.
|
||||
|
||||
The validators.py module contains functions named test_llm_connection and
|
||||
test_embedder_connection which are not pytest tests but validator functions.
|
||||
"""
|
||||
# Filter out items that are from validators.py and are not in test classes
|
||||
filtered_items = []
|
||||
for item in items:
|
||||
# Get the full path of the test
|
||||
item_path = str(item.fspath) if hasattr(item, "fspath") else str(item.path)
|
||||
|
||||
# Skip the standalone test_llm_connection and test_embedder_connection
|
||||
# functions from validators.py (they're not pytest tests)
|
||||
if item.name in [
|
||||
"test_llm_connection",
|
||||
"test_embedder_connection",
|
||||
"test_ollama_connection",
|
||||
]:
|
||||
# Check if it's from validators.py
|
||||
if "validators.py" in item_path or "test_providers.py" in item_path:
|
||||
# Only skip if it's a standalone function (not in a TestClass)
|
||||
if not item.parent.name.startswith("Test"):
|
||||
continue
|
||||
|
||||
filtered_items.append(item)
|
||||
|
||||
items[:] = filtered_items
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# External Dependency Mocks
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_graphiti_core():
|
||||
"""Mock graphiti_core.Graphiti and related classes.
|
||||
|
||||
Patches the graphiti_core library to prevent actual graph database connections
|
||||
during tests.
|
||||
|
||||
Yields:
|
||||
tuple: (mock_graphiti_class, mock_graphiti_instance)
|
||||
"""
|
||||
with patch(
|
||||
"integrations.graphiti.queries_pkg.graphiti.graphiti_core.Graphiti"
|
||||
) as mock_graphiti:
|
||||
# Configure the mock to return a mock instance
|
||||
mock_instance = MagicMock()
|
||||
mock_graphiti.return_value = mock_instance
|
||||
|
||||
# Mock common methods that might be called
|
||||
mock_instance.add_edges = AsyncMock()
|
||||
mock_instance.add_nodes = AsyncMock()
|
||||
mock_instance.search = AsyncMock(return_value=[])
|
||||
mock_instance.delete_graph = AsyncMock()
|
||||
mock_instance.close = AsyncMock()
|
||||
|
||||
yield mock_graphiti, mock_instance
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_falkor_driver():
|
||||
"""Mock graphiti_core.driver.falkordb_driver.FalkorDriver.
|
||||
|
||||
Prevents actual FalkorDB connections during tests.
|
||||
|
||||
Yields:
|
||||
tuple: (mock_driver_class, mock_driver_instance)
|
||||
"""
|
||||
with patch(
|
||||
"integrations.graphiti.queries_pkg.graphiti.graphiti_core.driver.falkordb_driver.FalkorDriver"
|
||||
) as mock_driver:
|
||||
mock_instance = MagicMock()
|
||||
mock_driver.return_value = mock_instance
|
||||
|
||||
# Mock driver methods
|
||||
mock_instance.close = MagicMock()
|
||||
mock_instance.execute_query = MagicMock(return_value=[])
|
||||
|
||||
yield mock_driver, mock_instance
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_graphiti_providers():
|
||||
"""Mock graphiti_providers module.
|
||||
|
||||
Patches the graphiti_providers module to prevent actual LLM/embedder calls.
|
||||
|
||||
Yields:
|
||||
tuple: (mock_get_client, mock_client_instance)
|
||||
"""
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.providers.get_client"
|
||||
) as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_get_client.return_value = mock_client
|
||||
yield mock_get_client, mock_client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_ladybug_db():
|
||||
"""Mock real_ladybug and kuzu database connections.
|
||||
|
||||
Prevents actual database connections during tests.
|
||||
|
||||
Yields:
|
||||
dict: Dictionary with 'ladybug' and 'kuzu' keys, each containing
|
||||
(mock_class, mock_instance) tuples.
|
||||
"""
|
||||
with (
|
||||
patch(
|
||||
"integrations.graphiti.queries_pkg.client.real_ladybug.Ladybug"
|
||||
) as mock_ladybug,
|
||||
patch("integrations.graphiti.queries_pkg.client.kuzu.Connection") as mock_kuzu,
|
||||
):
|
||||
# Mock Ladybug instance
|
||||
ladybug_instance = MagicMock()
|
||||
mock_ladybug.return_value = ladybug_instance
|
||||
ladybug_instance.close = MagicMock()
|
||||
|
||||
# Mock Kuzu connection
|
||||
kuzu_instance = MagicMock()
|
||||
mock_kuzu.return_value = kuzu_instance
|
||||
kuzu_instance.close = MagicMock()
|
||||
|
||||
yield {
|
||||
"ladybug": (mock_ladybug, ladybug_instance),
|
||||
"kuzu": (mock_kuzu, kuzu_instance),
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Config Fixtures
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config():
|
||||
"""Return a GraphitiConfig with test values.
|
||||
|
||||
Provides a test configuration that doesn't require real environment variables
|
||||
or database connections.
|
||||
|
||||
Returns:
|
||||
GraphitiConfig: Configuration with test values.
|
||||
"""
|
||||
from integrations.graphiti.config import GraphitiConfig
|
||||
|
||||
config = GraphitiConfig(
|
||||
enabled=True,
|
||||
database="test_dataset",
|
||||
db_path="/tmp/test_graphiti.db",
|
||||
llm_provider="openai",
|
||||
openai_model="gpt-5-mini",
|
||||
embedder_provider="openai",
|
||||
openai_embedding_model="text-embedding-3-small",
|
||||
openai_api_key="sk-test-key-for-testing",
|
||||
)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_env_vars(tmp_path):
|
||||
"""Set test environment variables for Graphiti configuration.
|
||||
|
||||
Sets up a clean environment with test values for all Graphiti-related
|
||||
environment variables.
|
||||
|
||||
Yields:
|
||||
dict: Dictionary of environment variables that were set.
|
||||
"""
|
||||
test_db_path = str(tmp_path / "test_graphiti.db")
|
||||
|
||||
env_vars = {
|
||||
"GRAPHITI_ENABLED": "true",
|
||||
"GRAPHITI_LLM_PROVIDER": "openai",
|
||||
"GRAPHITI_EMBEDDER_PROVIDER": "openai",
|
||||
"GRAPHITI_DATABASE": "test_dataset",
|
||||
"GRAPHITI_DB_PATH": test_db_path,
|
||||
"OPENAI_MODEL": "gpt-5-mini",
|
||||
"OPENAI_EMBEDDING_MODEL": "text-embedding-3-small",
|
||||
"OPENAI_API_KEY": "sk-test-key-for-testing",
|
||||
}
|
||||
|
||||
# Save original values
|
||||
original = {k: os.environ.get(k) for k in env_vars}
|
||||
|
||||
# Set test values
|
||||
for key, value in env_vars.items():
|
||||
os.environ[key] = value
|
||||
|
||||
yield env_vars
|
||||
|
||||
# Restore original values
|
||||
for key, original_value in original.items():
|
||||
if original_value is None:
|
||||
os.environ.pop(key, None)
|
||||
else:
|
||||
os.environ[key] = original_value
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Client Fixtures
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_graphiti_client():
|
||||
"""Mock GraphitiClient with all necessary methods.
|
||||
|
||||
Provides a mock client that simulates the behavior of the GraphitiClient
|
||||
without requiring actual graph database connections.
|
||||
|
||||
Returns:
|
||||
Mock: Mocked GraphitiClient with typical methods mocked.
|
||||
"""
|
||||
client = Mock()
|
||||
client.graphiti = Mock()
|
||||
|
||||
# Core client methods
|
||||
client.is_initialized = Mock(return_value=True)
|
||||
client.initialize = AsyncMock()
|
||||
client.get_session_id = Mock(return_value="test_session")
|
||||
client.get_user_id = Mock(return_value="test_user")
|
||||
client.get_project_id = Mock(return_value="test_project")
|
||||
|
||||
# Memory operations (async)
|
||||
client.add_episode = AsyncMock(return_value="episode_id_123")
|
||||
client.add_episodic_memories = AsyncMock(return_value=["mem_id_1", "mem_id_2"])
|
||||
client.add_abstract_memories = AsyncMock(return_value=["abstract_id_1"])
|
||||
client.search = AsyncMock(return_value=[])
|
||||
client.delete_graph = AsyncMock()
|
||||
|
||||
# Graphiti instance methods
|
||||
client.graphiti.search = AsyncMock(return_value=[])
|
||||
|
||||
# Configuration
|
||||
client.get_config = Mock(
|
||||
return_value=Mock(
|
||||
enabled=True, database="test_dataset", db_path="/tmp/test_graphiti.db"
|
||||
)
|
||||
)
|
||||
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_graphiti_instance():
|
||||
"""Mock the Graphiti instance from graphiti_core.
|
||||
|
||||
Provides a mock of the actual Graphiti core instance with all methods
|
||||
that might be called during operations.
|
||||
|
||||
Returns:
|
||||
Mock: Mocked Graphiti instance with typical methods mocked.
|
||||
"""
|
||||
instance = MagicMock()
|
||||
|
||||
# Search methods (async)
|
||||
instance.search = AsyncMock(return_value=[])
|
||||
instance.search_by_abstract = AsyncMock(return_value=[])
|
||||
instance.search_by_vector = AsyncMock(return_value=[])
|
||||
|
||||
# Add methods (async)
|
||||
instance.add_episode = AsyncMock(return_value="episode_id")
|
||||
instance.add_edges = AsyncMock()
|
||||
instance.add_nodes = AsyncMock()
|
||||
|
||||
# Graph management
|
||||
instance.delete_graph = AsyncMock()
|
||||
instance.close = AsyncMock()
|
||||
instance.get_graph_summary = Mock(return_value={"nodes": 0, "edges": 0})
|
||||
|
||||
# Configuration
|
||||
instance.database = "test_dataset"
|
||||
|
||||
return instance
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test Directory Fixtures
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_spec_dir(tmp_path):
|
||||
"""Create a temporary directory for spec testing.
|
||||
|
||||
Provides a temporary directory with spec-like structure for testing
|
||||
spec-related functionality.
|
||||
|
||||
Args:
|
||||
tmp_path: pytest's built-in tmp_path fixture.
|
||||
|
||||
Returns:
|
||||
Path: Path to the temporary spec directory.
|
||||
"""
|
||||
spec_dir = tmp_path / "spec_001_test"
|
||||
spec_dir.mkdir()
|
||||
|
||||
# Create common spec subdirectories
|
||||
(spec_dir / ".auto-claude").mkdir()
|
||||
(spec_dir / "context").mkdir()
|
||||
|
||||
return spec_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_project_dir(tmp_path):
|
||||
"""Create a temporary directory for project testing.
|
||||
|
||||
Provides a temporary directory with project-like structure for testing
|
||||
project-related functionality.
|
||||
|
||||
Args:
|
||||
tmp_path: pytest's built-in tmp_path fixture.
|
||||
|
||||
Returns:
|
||||
Path: Path to the temporary project directory.
|
||||
"""
|
||||
project_dir = tmp_path / "test_project"
|
||||
project_dir.mkdir()
|
||||
|
||||
# Create common project subdirectories
|
||||
(project_dir / "src").mkdir()
|
||||
(project_dir / "tests").mkdir()
|
||||
(project_dir / ".auto-claude").mkdir()
|
||||
|
||||
return project_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_db_path(tmp_path):
|
||||
"""Create a temporary path for test database.
|
||||
|
||||
Provides a temporary file path that can be used for database testing
|
||||
without affecting real databases.
|
||||
|
||||
Args:
|
||||
tmp_path: pytest's built-in tmp_path fixture.
|
||||
|
||||
Returns:
|
||||
str: Path to temporary database file.
|
||||
"""
|
||||
db_path = str(tmp_path / "test_graphiti.db")
|
||||
return db_path
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Provider Fixtures
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_llm_client():
|
||||
"""Mocked LLM client for testing.
|
||||
|
||||
Provides a mock client that simulates LLM responses without making
|
||||
actual API calls.
|
||||
|
||||
Returns:
|
||||
Mock: Mocked LLM client.
|
||||
"""
|
||||
client = Mock()
|
||||
|
||||
# Message methods
|
||||
client.messages = Mock()
|
||||
mock_response = Mock()
|
||||
mock_response.id = "msg_test_123"
|
||||
mock_response.content = []
|
||||
mock_response.model = "claude-3-5-sonnet-20241022"
|
||||
mock_response.role = "assistant"
|
||||
client.messages.create = Mock(return_value=mock_response)
|
||||
|
||||
# Streaming support
|
||||
client.messages.stream = Mock(return_value=iter([]))
|
||||
|
||||
# Token counting
|
||||
client.count_tokens = Mock(return_value=100)
|
||||
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_embedder():
|
||||
"""Mocked embedder with get_embedding() method.
|
||||
|
||||
Provides a mock embedder that returns fake embeddings without making
|
||||
actual API calls. Uses deterministic values for reproducibility.
|
||||
|
||||
Returns:
|
||||
tuple: (mock_embedder, test_embedding_list)
|
||||
"""
|
||||
embedder = Mock()
|
||||
|
||||
# Return a deterministic embedding vector (1536 dimensions is common for OpenAI)
|
||||
# Using 0.1 for all values makes tests reproducible
|
||||
test_embedding = [0.1] * 1536
|
||||
|
||||
embedder.get_embedding = Mock(return_value=test_embedding)
|
||||
embedder.get_embeddings = Mock(return_value=[test_embedding])
|
||||
|
||||
return embedder, test_embedding
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# State Fixtures
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_state():
|
||||
"""GraphitiState with test values.
|
||||
|
||||
Provides a mock state object with typical values for testing state-related
|
||||
functionality.
|
||||
|
||||
Returns:
|
||||
Mock: Mocked GraphitiState with test values.
|
||||
"""
|
||||
from integrations.graphiti.config import GraphitiState
|
||||
|
||||
state = GraphitiState(
|
||||
initialized=True,
|
||||
database="test_dataset",
|
||||
indices_built=True,
|
||||
llm_provider="openai",
|
||||
embedder_provider="openai",
|
||||
)
|
||||
|
||||
return state
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_empty_state():
|
||||
"""Empty GraphitiState.
|
||||
|
||||
Provides a mock state object with default/uninitialized values for testing
|
||||
initialization logic.
|
||||
|
||||
Returns:
|
||||
Mock: Mocked GraphitiState with empty/default values.
|
||||
"""
|
||||
from integrations.graphiti.config import GraphitiState
|
||||
|
||||
state = GraphitiState()
|
||||
|
||||
return state
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test Data Fixtures
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_episode_data():
|
||||
"""Sample episode data for testing.
|
||||
|
||||
Provides realistic episode data structure for testing memory operations.
|
||||
|
||||
Returns:
|
||||
dict: Sample episode data.
|
||||
"""
|
||||
return {
|
||||
"episode_id": "episode_123",
|
||||
"content": "Test episode content about a feature implementation",
|
||||
"metadata": {
|
||||
"task_id": "task_001",
|
||||
"timestamp": "2024-01-01T00:00:00Z",
|
||||
"type": "implementation",
|
||||
},
|
||||
"session_id": "test_session",
|
||||
"user_id": "test_user",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_memory_nodes():
|
||||
"""Sample memory nodes for testing.
|
||||
|
||||
Provides realistic node data for testing graph operations.
|
||||
|
||||
Returns:
|
||||
list: List of sample memory node dictionaries.
|
||||
"""
|
||||
return [
|
||||
{
|
||||
"uuid": "node_1",
|
||||
"name": "Feature Implementation",
|
||||
"label": "CONCEPT",
|
||||
"summary": "Implementation of new feature",
|
||||
"created_at": "2024-01-01T00:00:00Z",
|
||||
},
|
||||
{
|
||||
"uuid": "node_2",
|
||||
"name": "Bug Fix",
|
||||
"label": "CONCEPT",
|
||||
"summary": "Fixed critical bug",
|
||||
"created_at": "2024-01-02T00:00:00Z",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_search_results():
|
||||
"""Sample search results for testing.
|
||||
|
||||
Provides realistic search result data for testing search operations.
|
||||
|
||||
Returns:
|
||||
list: List of sample search result dictionaries.
|
||||
"""
|
||||
return [
|
||||
{
|
||||
"uuid": "result_1",
|
||||
"name": "Search Result 1",
|
||||
"summary": "First search result",
|
||||
"score": 0.95,
|
||||
},
|
||||
{
|
||||
"uuid": "result_2",
|
||||
"name": "Search Result 2",
|
||||
"summary": "Second search result",
|
||||
"score": 0.87,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Helper Fixtures
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def clean_env():
|
||||
"""Fixture to ensure clean environment for each test.
|
||||
|
||||
Removes all Graphiti-related environment variables before the test
|
||||
and restores them afterward.
|
||||
|
||||
Yields:
|
||||
dict: Dictionary of original environment values.
|
||||
"""
|
||||
# Store original env vars
|
||||
env_keys = [
|
||||
"GRAPHITI_ENABLED",
|
||||
"GRAPHITI_LLM_PROVIDER",
|
||||
"GRAPHITI_EMBEDDER_PROVIDER",
|
||||
"GRAPHITI_DATABASE",
|
||||
"GRAPHITI_DB_PATH",
|
||||
"OPENAI_API_KEY",
|
||||
"OPENAI_MODEL",
|
||||
"OPENAI_EMBEDDING_MODEL",
|
||||
"ANTHROPIC_API_KEY",
|
||||
"GRAPHITI_ANTHROPIC_MODEL",
|
||||
"AZURE_OPENAI_API_KEY",
|
||||
"AZURE_OPENAI_BASE_URL",
|
||||
"AZURE_OPENAI_LLM_DEPLOYMENT",
|
||||
"AZURE_OPENAI_EMBEDDING_DEPLOYMENT",
|
||||
"VOYAGE_API_KEY",
|
||||
"VOYAGE_EMBEDDING_MODEL",
|
||||
"GOOGLE_API_KEY",
|
||||
"GOOGLE_LLM_MODEL",
|
||||
"GOOGLE_EMBEDDING_MODEL",
|
||||
"OPENROUTER_API_KEY",
|
||||
"OPENROUTER_BASE_URL",
|
||||
"OPENROUTER_LLM_MODEL",
|
||||
"OPENROUTER_EMBEDDING_MODEL",
|
||||
"OLLAMA_BASE_URL",
|
||||
"OLLAMA_LLM_MODEL",
|
||||
"OLLAMA_EMBEDDING_MODEL",
|
||||
"OLLAMA_EMBEDDING_DIM",
|
||||
]
|
||||
|
||||
original = {}
|
||||
for key in env_keys:
|
||||
original[key] = os.environ.get(key)
|
||||
if key in os.environ:
|
||||
os.environ.pop(key)
|
||||
|
||||
yield original
|
||||
|
||||
# Restore original values
|
||||
for key, value in original.items():
|
||||
if value is not None:
|
||||
os.environ[key] = value
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,216 @@
|
||||
"""
|
||||
Tests for integrations.graphiti.providers_pkg.cross_encoder module.
|
||||
|
||||
Tests cover:
|
||||
1. create_cross_encoder():
|
||||
- Returns None for non-Ollama providers
|
||||
- Returns None when llm_client is None
|
||||
- Returns None on ImportError (graphiti_core not available)
|
||||
- Returns None on Exception during creation
|
||||
- Creates correct base_url for Ollama
|
||||
- Creates LLMConfig with correct parameters
|
||||
"""
|
||||
|
||||
import builtins
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
# =============================================================================
|
||||
# Test Fixtures
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config():
|
||||
"""Mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.llm_provider = "ollama"
|
||||
config.ollama_base_url = "http://localhost:11434"
|
||||
config.ollama_llm_model = "llama3.2"
|
||||
return config
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_llm_client():
|
||||
"""Mock LLM client."""
|
||||
return MagicMock()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def graphiti_core_mocks():
|
||||
"""Mock graphiti_core modules and capture LLMConfig calls."""
|
||||
captured_config = {}
|
||||
|
||||
def capture_llm_config(**kwargs):
|
||||
captured_config.update(kwargs)
|
||||
return MagicMock()
|
||||
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.cross_encoder": MagicMock(),
|
||||
"graphiti_core.cross_encoder.openai_reranker_client": MagicMock(),
|
||||
"graphiti_core.llm_client": MagicMock(),
|
||||
"graphiti_core.llm_client.config": MagicMock(),
|
||||
},
|
||||
):
|
||||
from graphiti_core.cross_encoder.openai_reranker_client import (
|
||||
OpenAIRerankerClient,
|
||||
)
|
||||
from graphiti_core.llm_client.config import LLMConfig
|
||||
|
||||
LLMConfig.side_effect = capture_llm_config
|
||||
OpenAIRerankerClient.return_value = MagicMock()
|
||||
|
||||
yield captured_config
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test create_cross_encoder()
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateCrossEncoder:
|
||||
"""Tests for create_cross_encoder() function."""
|
||||
|
||||
def test_returns_none_for_non_ollama_provider(self, mock_config, mock_llm_client):
|
||||
"""Test create_cross_encoder returns None for non-Ollama providers."""
|
||||
mock_config.llm_provider = "openai"
|
||||
|
||||
import integrations.graphiti.providers_pkg.cross_encoder as ce_module
|
||||
|
||||
# The function returns None for non-ollama providers
|
||||
result = ce_module.create_cross_encoder(mock_config, mock_llm_client)
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_returns_none_for_anthropic_provider(self, mock_config, mock_llm_client):
|
||||
"""Test create_cross_encoder returns None for Anthropic provider."""
|
||||
mock_config.llm_provider = "anthropic"
|
||||
|
||||
from integrations.graphiti.providers_pkg.cross_encoder import (
|
||||
create_cross_encoder,
|
||||
)
|
||||
|
||||
result = create_cross_encoder(mock_config, mock_llm_client)
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_returns_none_for_google_provider(self, mock_config, mock_llm_client):
|
||||
"""Test create_cross_encoder returns None for Google provider."""
|
||||
mock_config.llm_provider = "google"
|
||||
|
||||
from integrations.graphiti.providers_pkg.cross_encoder import (
|
||||
create_cross_encoder,
|
||||
)
|
||||
|
||||
result = create_cross_encoder(mock_config, mock_llm_client)
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_returns_none_when_llm_client_is_none(self, mock_config):
|
||||
"""Test create_cross_encoder returns None when llm_client is None."""
|
||||
from integrations.graphiti.providers_pkg.cross_encoder import (
|
||||
create_cross_encoder,
|
||||
)
|
||||
|
||||
result = create_cross_encoder(mock_config, llm_client=None)
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_base_url_without_v1_gets_suffix_added(
|
||||
self, mock_config, mock_llm_client, graphiti_core_mocks
|
||||
):
|
||||
"""Test that base_url without /v1 gets /v1 suffix added."""
|
||||
mock_config.ollama_base_url = "http://localhost:11434"
|
||||
|
||||
from integrations.graphiti.providers_pkg.cross_encoder import (
|
||||
create_cross_encoder,
|
||||
)
|
||||
|
||||
_ = create_cross_encoder(mock_config, mock_llm_client)
|
||||
|
||||
# Verify base_url was captured and has /v1 suffix added
|
||||
assert "base_url" in graphiti_core_mocks
|
||||
assert graphiti_core_mocks["base_url"] == "http://localhost:11434/v1"
|
||||
|
||||
def test_base_url_with_v1_is_preserved(
|
||||
self, mock_config, mock_llm_client, graphiti_core_mocks
|
||||
):
|
||||
"""Test that base_url with /v1 suffix is preserved."""
|
||||
mock_config.ollama_base_url = "http://localhost:11434/v1"
|
||||
|
||||
from integrations.graphiti.providers_pkg.cross_encoder import (
|
||||
create_cross_encoder,
|
||||
)
|
||||
|
||||
_ = create_cross_encoder(mock_config, mock_llm_client)
|
||||
|
||||
# Verify base_url was preserved with /v1 suffix
|
||||
assert "base_url" in graphiti_core_mocks
|
||||
assert graphiti_core_mocks["base_url"] == "http://localhost:11434/v1"
|
||||
|
||||
def test_import_error_returns_none(self, mock_config, mock_llm_client):
|
||||
"""Test create_cross_encoder returns None when graphiti_core modules not available."""
|
||||
from integrations.graphiti.providers_pkg.cross_encoder import (
|
||||
create_cross_encoder,
|
||||
)
|
||||
|
||||
# Mock the import to raise ImportError
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
if name == "graphiti_core.cross_encoder.openai_reranker_client":
|
||||
raise ImportError("graphiti_core not installed")
|
||||
if name == "graphiti_core.llm_client.config":
|
||||
raise ImportError("graphiti_core not installed")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
result = create_cross_encoder(mock_config, mock_llm_client)
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_exception_during_creation_returns_none(self, mock_config, mock_llm_client):
|
||||
"""Test create_cross_encoder returns None on exception during creation."""
|
||||
from integrations.graphiti.providers_pkg.cross_encoder import (
|
||||
create_cross_encoder,
|
||||
)
|
||||
|
||||
# Mock the graphiti_core modules but make LLMConfig raise an exception
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.cross_encoder": MagicMock(),
|
||||
"graphiti_core.cross_encoder.openai_reranker_client": MagicMock(),
|
||||
"graphiti_core.llm_client": MagicMock(),
|
||||
"graphiti_core.llm_client.config": MagicMock(),
|
||||
},
|
||||
):
|
||||
from graphiti_core.llm_client.config import LLMConfig
|
||||
|
||||
# Make LLMConfig raise an exception
|
||||
LLMConfig.side_effect = Exception("Config creation failed")
|
||||
|
||||
result = create_cross_encoder(mock_config, mock_llm_client)
|
||||
|
||||
assert result is None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test module exports
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestModuleExports:
|
||||
"""Tests for cross_encoder module exports."""
|
||||
|
||||
def test_create_cross_encoder_is_exported(self):
|
||||
"""Test that create_cross_encoder is exported from module."""
|
||||
from integrations.graphiti.providers_pkg import cross_encoder
|
||||
|
||||
assert hasattr(cross_encoder, "create_cross_encoder")
|
||||
assert callable(cross_encoder.create_cross_encoder)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,238 @@
|
||||
"""
|
||||
Tests for integrations.graphiti.__init__ module.
|
||||
|
||||
Tests cover:
|
||||
- __getattr__ lazy import functionality
|
||||
- Direct imports (GraphitiConfig, validate_graphiti_config)
|
||||
- Invalid attribute access raises AttributeError
|
||||
"""
|
||||
|
||||
import sys
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class TestInitModuleDirectImports:
|
||||
"""Test direct imports that don't require lazy loading."""
|
||||
|
||||
def test_import_graphiti_config_directly(self):
|
||||
"""Test GraphitiConfig can be imported directly."""
|
||||
from integrations.graphiti import GraphitiConfig
|
||||
|
||||
assert GraphitiConfig is not None
|
||||
|
||||
def test_import_validate_graphiti_config_directly(self):
|
||||
"""Test validate_graphiti_config can be imported directly."""
|
||||
from integrations.graphiti import validate_graphiti_config
|
||||
|
||||
assert validate_graphiti_config is not None
|
||||
|
||||
def test___all___exports(self):
|
||||
"""Test __all__ contains expected exports."""
|
||||
import integrations.graphiti as graphiti_module
|
||||
|
||||
expected_all = [
|
||||
"GraphitiConfig",
|
||||
"validate_graphiti_config",
|
||||
"GraphitiMemory",
|
||||
"create_llm_client",
|
||||
"create_embedder",
|
||||
]
|
||||
assert graphiti_module.__all__ == expected_all
|
||||
|
||||
|
||||
class TestInitModuleLazyImports:
|
||||
"""Test __getattr__ lazy import functionality."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_memory_module(self):
|
||||
"""Mock the memory module."""
|
||||
memory_mock = MagicMock()
|
||||
memory_mock.GraphitiMemory = MagicMock
|
||||
return memory_mock
|
||||
|
||||
@pytest.fixture
|
||||
def mock_providers_module(self):
|
||||
"""Mock the providers module."""
|
||||
providers_mock = MagicMock()
|
||||
providers_mock.create_llm_client = MagicMock(return_value=AsyncMock())
|
||||
providers_mock.create_embedder = MagicMock(return_value=AsyncMock())
|
||||
return providers_mock
|
||||
|
||||
def test_getattr_graphiti_memory_lazy_import(self, mock_memory_module):
|
||||
"""Test accessing GraphitiMemory triggers lazy import."""
|
||||
import integrations.graphiti as graphiti_module
|
||||
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"integrations.graphiti.memory": mock_memory_module,
|
||||
},
|
||||
):
|
||||
# Access the attribute via __getattr__
|
||||
result = graphiti_module.__getattr__("GraphitiMemory")
|
||||
|
||||
assert result == mock_memory_module.GraphitiMemory
|
||||
|
||||
def test_getattr_create_llm_client_lazy_import(self, mock_providers_module):
|
||||
"""Test accessing create_llm_client triggers lazy import."""
|
||||
import integrations.graphiti as graphiti_module
|
||||
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"integrations.graphiti.providers": mock_providers_module,
|
||||
},
|
||||
):
|
||||
result = graphiti_module.__getattr__("create_llm_client")
|
||||
|
||||
assert result == mock_providers_module.create_llm_client
|
||||
|
||||
def test_getattr_create_embedder_lazy_import(self, mock_providers_module):
|
||||
"""Test accessing create_embedder triggers lazy import."""
|
||||
import integrations.graphiti as graphiti_module
|
||||
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"integrations.graphiti.providers": mock_providers_module,
|
||||
},
|
||||
):
|
||||
result = graphiti_module.__getattr__("create_embedder")
|
||||
|
||||
assert result == mock_providers_module.create_embedder
|
||||
|
||||
def test_getattr_invalid_attribute_raises_attribute_error(self):
|
||||
"""Test accessing invalid attribute raises AttributeError."""
|
||||
import integrations.graphiti as graphiti_module
|
||||
|
||||
with pytest.raises(AttributeError) as exc_info:
|
||||
graphiti_module.__getattr__("NonExistentAttribute")
|
||||
|
||||
assert "has no attribute" in str(exc_info.value)
|
||||
assert "NonExistentAttribute" in str(exc_info.value)
|
||||
|
||||
def test_getattr_empty_string_attribute(self):
|
||||
"""Test accessing empty string attribute raises AttributeError."""
|
||||
import integrations.graphiti as graphiti_module
|
||||
|
||||
with pytest.raises(AttributeError):
|
||||
graphiti_module.__getattr__("")
|
||||
|
||||
def test_getattr_case_sensitive(self):
|
||||
"""Test that __getattr__ is case-sensitive."""
|
||||
import integrations.graphiti as graphiti_module
|
||||
|
||||
# lowercase should fail
|
||||
with pytest.raises(AttributeError):
|
||||
graphiti_module.__getattr__("graphitimemory")
|
||||
|
||||
# mixed case should fail
|
||||
with pytest.raises(AttributeError):
|
||||
graphiti_module.__getattr__("Graphiti_Memory")
|
||||
|
||||
|
||||
class TestInitModuleAccessPatterns:
|
||||
"""Test various access patterns for the init module."""
|
||||
|
||||
def test_hasattr_on_graphiti_memory(self):
|
||||
"""Test hasattr works correctly with lazy imports."""
|
||||
import integrations.graphiti as graphiti_module
|
||||
|
||||
# Mock the import
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"integrations.graphiti.memory": MagicMock(GraphitiMemory=MagicMock),
|
||||
},
|
||||
):
|
||||
# hasattr should call __getattr__ and not raise
|
||||
result = hasattr(graphiti_module, "GraphitiMemory")
|
||||
assert result is True
|
||||
|
||||
def test_hasattr_on_invalid_attribute(self):
|
||||
"""Test hasattr returns False for invalid attributes."""
|
||||
import integrations.graphiti as graphiti_module
|
||||
|
||||
result = hasattr(graphiti_module, "InvalidAttribute")
|
||||
assert result is False
|
||||
|
||||
def test_getattr_on_existing_direct_import(self):
|
||||
"""Test __getattr__ is not called for direct imports."""
|
||||
import integrations.graphiti as graphiti_module
|
||||
|
||||
# GraphitiConfig is imported directly, so __getattr__ shouldn't be called
|
||||
# This tests that the normal import mechanism works
|
||||
assert hasattr(graphiti_module, "GraphitiConfig")
|
||||
|
||||
def test_module_docstring(self):
|
||||
"""Test the module has a docstring."""
|
||||
import integrations.graphiti as graphiti_module
|
||||
|
||||
assert graphiti_module.__doc__ is not None
|
||||
assert "Graphiti" in graphiti_module.__doc__
|
||||
|
||||
|
||||
class TestInitModuleIntegration:
|
||||
"""Integration tests for the init module."""
|
||||
|
||||
def test_import_star(self):
|
||||
"""Test 'from integrations.graphiti import *' includes direct imports."""
|
||||
# Create a new namespace for the import
|
||||
namespace = {}
|
||||
exec("from integrations.graphiti import *", namespace)
|
||||
|
||||
# Direct imports should be available
|
||||
assert "GraphitiConfig" in namespace
|
||||
assert "validate_graphiti_config" in namespace
|
||||
|
||||
def test_reimport_does_not_fail(self):
|
||||
"""Test that re-importing the module doesn't cause issues."""
|
||||
import importlib
|
||||
|
||||
import integrations.graphiti
|
||||
|
||||
# Reload the module
|
||||
importlib.reload(integrations.graphiti)
|
||||
|
||||
# Should still work
|
||||
assert hasattr(integrations.graphiti, "GraphitiConfig")
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_concurrent_attribute_access(self):
|
||||
"""Test that concurrent attribute access doesn't cause issues."""
|
||||
import concurrent.futures
|
||||
|
||||
import integrations.graphiti as graphiti_module
|
||||
|
||||
# Mock the imports
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"integrations.graphiti.memory": MagicMock(GraphitiMemory=MagicMock),
|
||||
"integrations.graphiti.providers": MagicMock(
|
||||
create_llm_client=MagicMock(return_value=AsyncMock()),
|
||||
create_embedder=MagicMock(return_value=AsyncMock()),
|
||||
),
|
||||
},
|
||||
):
|
||||
|
||||
def access_attribute(attr_name):
|
||||
try:
|
||||
return getattr(graphiti_module, attr_name)
|
||||
except AttributeError:
|
||||
return None
|
||||
|
||||
# Access multiple attributes concurrently
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
||||
futures = [
|
||||
executor.submit(access_attribute, "GraphitiMemory"),
|
||||
executor.submit(access_attribute, "create_llm_client"),
|
||||
executor.submit(access_attribute, "create_embedder"),
|
||||
]
|
||||
results = [f.result() for f in concurrent.futures.as_completed(futures)]
|
||||
|
||||
# All should succeed
|
||||
assert len(results) == 3
|
||||
assert all(r is not None for r in results)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,425 @@
|
||||
"""
|
||||
Tests for integrations.graphiti.memory module.
|
||||
|
||||
This module is a backward compatibility facade that re-exports from
|
||||
queries_pkg and provides convenience functions.
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
# =============================================================================
|
||||
# Test Fixtures
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_spec_dir(tmp_path):
|
||||
"""Create a temporary spec directory."""
|
||||
spec_dir = tmp_path / "specs" / "001-test"
|
||||
spec_dir.mkdir(parents=True)
|
||||
return spec_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_project_dir(tmp_path):
|
||||
"""Create a temporary project directory."""
|
||||
project_dir = tmp_path / "project"
|
||||
project_dir.mkdir(parents=True)
|
||||
return project_dir
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Tests for module imports
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestModuleImports:
|
||||
"""Test that all expected exports are available."""
|
||||
|
||||
def test_import_GraphitiMemory(self):
|
||||
"""Test GraphitiMemory can be imported."""
|
||||
from integrations.graphiti.memory import GraphitiMemory
|
||||
|
||||
assert GraphitiMemory is not None
|
||||
|
||||
def test_import_GroupIdMode(self):
|
||||
"""Test GroupIdMode can be imported."""
|
||||
from integrations.graphiti.memory import GroupIdMode
|
||||
|
||||
assert GroupIdMode is not None
|
||||
assert hasattr(GroupIdMode, "SPEC")
|
||||
assert hasattr(GroupIdMode, "PROJECT")
|
||||
|
||||
def test_import_is_graphiti_enabled(self):
|
||||
"""Test is_graphiti_enabled can be imported."""
|
||||
from integrations.graphiti.memory import is_graphiti_enabled
|
||||
|
||||
assert is_graphiti_enabled is not None
|
||||
|
||||
def test_import_get_graphiti_memory(self):
|
||||
"""Test get_graphiti_memory can be imported."""
|
||||
from integrations.graphiti.memory import get_graphiti_memory
|
||||
|
||||
assert get_graphiti_memory is not None
|
||||
|
||||
def test_import_test_graphiti_connection(self):
|
||||
"""Test test_graphiti_connection can be imported."""
|
||||
from integrations.graphiti.memory import test_graphiti_connection
|
||||
|
||||
assert test_graphiti_connection is not None
|
||||
|
||||
def test_import_test_provider_configuration(self):
|
||||
"""Test test_provider_configuration can be imported."""
|
||||
from integrations.graphiti.memory import test_provider_configuration
|
||||
|
||||
assert test_provider_configuration is not None
|
||||
|
||||
def test_import_episode_types(self):
|
||||
"""Test all episode type constants can be imported."""
|
||||
from integrations.graphiti.memory import (
|
||||
EPISODE_TYPE_CODEBASE_DISCOVERY,
|
||||
EPISODE_TYPE_GOTCHA,
|
||||
EPISODE_TYPE_HISTORICAL_CONTEXT,
|
||||
EPISODE_TYPE_PATTERN,
|
||||
EPISODE_TYPE_QA_RESULT,
|
||||
EPISODE_TYPE_SESSION_INSIGHT,
|
||||
EPISODE_TYPE_TASK_OUTCOME,
|
||||
)
|
||||
|
||||
assert EPISODE_TYPE_SESSION_INSIGHT == "session_insight"
|
||||
assert EPISODE_TYPE_CODEBASE_DISCOVERY == "codebase_discovery"
|
||||
assert EPISODE_TYPE_PATTERN == "pattern"
|
||||
assert EPISODE_TYPE_GOTCHA == "gotcha"
|
||||
assert EPISODE_TYPE_TASK_OUTCOME == "task_outcome"
|
||||
assert EPISODE_TYPE_QA_RESULT == "qa_result"
|
||||
assert EPISODE_TYPE_HISTORICAL_CONTEXT == "historical_context"
|
||||
|
||||
def test_import_MAX_CONTEXT_RESULTS(self):
|
||||
"""Test MAX_CONTEXT_RESULTS can be imported."""
|
||||
from integrations.graphiti.memory import MAX_CONTEXT_RESULTS
|
||||
|
||||
assert MAX_CONTEXT_RESULTS is not None
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Tests for get_graphiti_memory()
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestGetGraphitiMemory:
|
||||
"""Tests for get_graphiti_memory convenience function."""
|
||||
|
||||
def test_returns_graphiti_memory_instance(self, mock_spec_dir, mock_project_dir):
|
||||
"""Test get_graphiti_memory returns GraphitiMemory instance."""
|
||||
from integrations.graphiti.memory import get_graphiti_memory
|
||||
|
||||
memory = get_graphiti_memory(mock_spec_dir, mock_project_dir)
|
||||
|
||||
assert memory is not None
|
||||
assert hasattr(memory, "spec_dir")
|
||||
assert hasattr(memory, "project_dir")
|
||||
|
||||
def test_default_group_id_mode_is_project(self, mock_spec_dir, mock_project_dir):
|
||||
"""Test default group_id_mode is PROJECT."""
|
||||
from integrations.graphiti.memory import get_graphiti_memory
|
||||
from integrations.graphiti.queries_pkg.schema import GroupIdMode
|
||||
|
||||
memory = get_graphiti_memory(mock_spec_dir, mock_project_dir)
|
||||
|
||||
# Check that group_id_mode defaults to PROJECT
|
||||
assert memory.group_id_mode == GroupIdMode.PROJECT
|
||||
|
||||
def test_spec_group_id_mode(self, mock_spec_dir, mock_project_dir):
|
||||
"""Test SPEC group_id_mode can be set."""
|
||||
from integrations.graphiti.memory import get_graphiti_memory
|
||||
from integrations.graphiti.queries_pkg.schema import GroupIdMode
|
||||
|
||||
memory = get_graphiti_memory(mock_spec_dir, mock_project_dir, GroupIdMode.SPEC)
|
||||
|
||||
assert memory.group_id_mode == GroupIdMode.SPEC
|
||||
|
||||
def test_project_group_id_mode(self, mock_spec_dir, mock_project_dir):
|
||||
"""Test PROJECT group_id_mode can be set."""
|
||||
from integrations.graphiti.memory import get_graphiti_memory
|
||||
from integrations.graphiti.queries_pkg.schema import GroupIdMode
|
||||
|
||||
memory = get_graphiti_memory(
|
||||
mock_spec_dir, mock_project_dir, GroupIdMode.PROJECT
|
||||
)
|
||||
|
||||
assert memory.group_id_mode == GroupIdMode.PROJECT
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Tests for test_graphiti_connection()
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestTestGraphitiConnection:
|
||||
"""Tests for test_graphiti_connection function."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_false_when_not_enabled(self):
|
||||
"""Test returns False when Graphiti not enabled."""
|
||||
from integrations.graphiti.memory import test_graphiti_connection
|
||||
|
||||
with patch("integrations.graphiti.memory.GraphitiConfig") as mock_config_class:
|
||||
mock_config = MagicMock()
|
||||
mock_config.enabled = False
|
||||
mock_config_class.from_env.return_value = mock_config
|
||||
|
||||
success, message = await test_graphiti_connection()
|
||||
|
||||
assert success is False
|
||||
assert "not enabled" in message.lower()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_false_with_validation_errors(self):
|
||||
"""Test returns False when config has validation errors."""
|
||||
from integrations.graphiti.memory import test_graphiti_connection
|
||||
|
||||
with patch("integrations.graphiti.memory.GraphitiConfig") as mock_config_class:
|
||||
mock_config = MagicMock()
|
||||
mock_config.enabled = True
|
||||
mock_config.get_validation_errors.return_value = ["API key missing"]
|
||||
mock_config_class.from_env.return_value = mock_config
|
||||
|
||||
success, message = await test_graphiti_connection()
|
||||
|
||||
assert success is False
|
||||
assert "Configuration errors" in message
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_false_on_import_error(self):
|
||||
"""Test returns False when graphiti_core not installed."""
|
||||
from integrations.graphiti.memory import test_graphiti_connection
|
||||
|
||||
with patch("integrations.graphiti.memory.GraphitiConfig") as mock_config_class:
|
||||
mock_config = MagicMock()
|
||||
mock_config.enabled = True
|
||||
mock_config.get_validation_errors.return_value = []
|
||||
mock_config_class.from_env.return_value = mock_config
|
||||
|
||||
# Only raise ImportError for graphiti_core imports
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def selective_import_error(name, *args, **kwargs):
|
||||
if "graphiti_core" in name:
|
||||
raise ImportError(f"No module named '{name}'")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=selective_import_error):
|
||||
success, message = await test_graphiti_connection()
|
||||
|
||||
assert success is False
|
||||
assert "not installed" in message.lower()
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_true_on_successful_connection(self):
|
||||
"""Test returns True when connection succeeds (requires graphiti_core)."""
|
||||
from integrations.graphiti.memory import test_graphiti_connection
|
||||
|
||||
# This test requires graphiti_core to be installed
|
||||
# Marked as slow since it connects to actual database
|
||||
try:
|
||||
success, message = await test_graphiti_connection()
|
||||
|
||||
# If graphiti_core is not installed, success will be False
|
||||
if "not installed" in message.lower():
|
||||
assert success is False
|
||||
# If installed but DB not available, check for connection error
|
||||
elif "connection failed" in message.lower():
|
||||
assert success is False
|
||||
# If everything is set up, should succeed
|
||||
else:
|
||||
# Concrete assertion for successful connection
|
||||
assert success is True, (
|
||||
f"Expected success=True, got {success} with message: {message}"
|
||||
)
|
||||
assert message, "Message should not be empty for successful connection"
|
||||
|
||||
except AssertionError as e:
|
||||
# Re-raise AssertionError to properly surface test failures
|
||||
raise
|
||||
except Exception as e:
|
||||
# If there's an unexpected error, fail the test with useful info
|
||||
pytest.skip(f"Graphiti connection test failed: {e}")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_handles_provider_error(self):
|
||||
"""Test handles ProviderError during provider creation."""
|
||||
from integrations.graphiti.memory import test_graphiti_connection
|
||||
from integrations.graphiti.providers_pkg.exceptions import ProviderError
|
||||
|
||||
with patch("integrations.graphiti.memory.GraphitiConfig") as mock_config_class:
|
||||
mock_config = MagicMock()
|
||||
mock_config.enabled = True
|
||||
mock_config.get_validation_errors.return_value = []
|
||||
mock_config_class.from_env.return_value = mock_config
|
||||
|
||||
# Mock graphiti_core imports to succeed
|
||||
mock_graphiti = MagicMock()
|
||||
mock_falkordb_driver = MagicMock()
|
||||
|
||||
# Mock provider creation to raise ProviderError
|
||||
with patch("graphiti_providers.create_llm_client") as mock_create_llm:
|
||||
mock_create_llm.side_effect = ProviderError("Test provider error")
|
||||
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(Graphiti=mock_graphiti),
|
||||
"graphiti_core.driver": MagicMock(),
|
||||
"graphiti_core.driver.falkordb_driver": mock_falkordb_driver,
|
||||
"graphiti_providers": MagicMock(
|
||||
ProviderError=ProviderError,
|
||||
create_embedder=MagicMock(),
|
||||
create_llm_client=mock_create_llm,
|
||||
),
|
||||
},
|
||||
):
|
||||
success, message = await test_graphiti_connection()
|
||||
|
||||
assert success is False
|
||||
assert "Provider error" in message
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Tests for test_provider_configuration()
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestTestProviderConfiguration:
|
||||
"""Tests for test_provider_configuration function."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_returns_configuration_status(self):
|
||||
"""Test returns dict with configuration status."""
|
||||
pytest.importorskip("graphiti_providers")
|
||||
from integrations.graphiti.memory import test_provider_configuration
|
||||
|
||||
with patch("integrations.graphiti.memory.GraphitiConfig") as mock_config_class:
|
||||
mock_config = MagicMock()
|
||||
mock_config.is_valid.return_value = True
|
||||
mock_config.get_validation_errors.return_value = []
|
||||
mock_config.llm_provider = "openai"
|
||||
mock_config.embedder_provider = "openai"
|
||||
mock_config_class.from_env.return_value = mock_config
|
||||
|
||||
# Mock the test functions
|
||||
with patch(
|
||||
"graphiti_providers.test_llm_connection",
|
||||
return_value=(True, "LLM OK"),
|
||||
):
|
||||
with patch(
|
||||
"graphiti_providers.test_embedder_connection",
|
||||
return_value=(True, "Embedder OK"),
|
||||
):
|
||||
results = await test_provider_configuration()
|
||||
|
||||
assert isinstance(results, dict)
|
||||
assert results["config_valid"] is True
|
||||
assert results["validation_errors"] == []
|
||||
assert results["llm_provider"] == "openai"
|
||||
assert results["embedder_provider"] == "openai"
|
||||
assert results["llm_test"]["success"] is True
|
||||
assert results["embedder_test"]["success"] is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_includes_ollama_test_when_ollama_provider(self):
|
||||
"""Test includes ollama_test when using ollama provider."""
|
||||
pytest.importorskip("graphiti_providers")
|
||||
from integrations.graphiti.memory import test_provider_configuration
|
||||
|
||||
with patch("integrations.graphiti.memory.GraphitiConfig") as mock_config_class:
|
||||
mock_config = MagicMock()
|
||||
mock_config.is_valid.return_value = True
|
||||
mock_config.get_validation_errors.return_value = []
|
||||
mock_config.llm_provider = "ollama"
|
||||
mock_config.embedder_provider = "openai"
|
||||
mock_config.ollama_base_url = "http://localhost:11434"
|
||||
mock_config_class.from_env.return_value = mock_config
|
||||
|
||||
with patch(
|
||||
"graphiti_providers.test_llm_connection",
|
||||
return_value=(True, "LLM OK"),
|
||||
):
|
||||
with patch(
|
||||
"graphiti_providers.test_embedder_connection",
|
||||
return_value=(True, "Embedder OK"),
|
||||
):
|
||||
with patch(
|
||||
"graphiti_providers.test_ollama_connection",
|
||||
return_value=(True, "Ollama OK"),
|
||||
):
|
||||
results = await test_provider_configuration()
|
||||
|
||||
assert "ollama_test" in results
|
||||
assert results["ollama_test"]["success"] is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_omits_ollama_test_when_not_ollama_provider(self):
|
||||
"""Test omits ollama_test when not using ollama provider."""
|
||||
pytest.importorskip("graphiti_providers")
|
||||
from integrations.graphiti.memory import test_provider_configuration
|
||||
|
||||
with patch("integrations.graphiti.memory.GraphitiConfig") as mock_config_class:
|
||||
mock_config = MagicMock()
|
||||
mock_config.is_valid.return_value = True
|
||||
mock_config.get_validation_errors.return_value = []
|
||||
mock_config.llm_provider = "openai"
|
||||
mock_config.embedder_provider = "openai"
|
||||
mock_config_class.from_env.return_value = mock_config
|
||||
|
||||
with patch(
|
||||
"graphiti_providers.test_llm_connection",
|
||||
return_value=(True, "LLM OK"),
|
||||
):
|
||||
with patch(
|
||||
"graphiti_providers.test_embedder_connection",
|
||||
return_value=(True, "Embedder OK"),
|
||||
):
|
||||
results = await test_provider_configuration()
|
||||
|
||||
assert "ollama_test" not in results
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Tests for __all__ export list
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestAllExports:
|
||||
"""Test __all__ contains expected exports."""
|
||||
|
||||
def test_all_exports_defined(self):
|
||||
"""Test __all__ is defined and contains expected items."""
|
||||
from integrations.graphiti import memory
|
||||
|
||||
assert hasattr(memory, "__all__")
|
||||
assert isinstance(memory.__all__, list)
|
||||
|
||||
expected_exports = [
|
||||
"GraphitiMemory",
|
||||
"GroupIdMode",
|
||||
"get_graphiti_memory",
|
||||
"is_graphiti_enabled",
|
||||
"test_graphiti_connection",
|
||||
"test_provider_configuration",
|
||||
"MAX_CONTEXT_RESULTS",
|
||||
"EPISODE_TYPE_SESSION_INSIGHT",
|
||||
"EPISODE_TYPE_CODEBASE_DISCOVERY",
|
||||
"EPISODE_TYPE_PATTERN",
|
||||
"EPISODE_TYPE_GOTCHA",
|
||||
"EPISODE_TYPE_TASK_OUTCOME",
|
||||
"EPISODE_TYPE_QA_RESULT",
|
||||
"EPISODE_TYPE_HISTORICAL_CONTEXT",
|
||||
]
|
||||
|
||||
for export in expected_exports:
|
||||
assert export in memory.__all__, f"{export} not in __all__"
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Quick test to demonstrate provider-specific database naming.
|
||||
|
||||
Shows how Auto Claude automatically generates provider-specific database names
|
||||
to prevent embedding dimension mismatches.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.config import GraphitiConfig
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"provider,model,dim",
|
||||
[
|
||||
("openai", None, None),
|
||||
("ollama", "embeddinggemma", 768),
|
||||
("ollama", "qwen3-embedding:0.6b", 1024),
|
||||
("voyage", None, None),
|
||||
("google", None, None),
|
||||
],
|
||||
)
|
||||
def test_provider_naming(provider, model, dim):
|
||||
"""Demonstrate provider-specific database naming."""
|
||||
# Create explicit config without relying on environment
|
||||
config = GraphitiConfig()
|
||||
config.embedder_provider = provider
|
||||
config.openai_embedding_model = "text-embedding-3-small"
|
||||
|
||||
if provider == "ollama" and model:
|
||||
config.ollama_embedding_model = model
|
||||
if dim is not None:
|
||||
config.ollama_embedding_dim = dim
|
||||
elif provider == "voyage":
|
||||
config.voyage_embedding_model = "voyage-3"
|
||||
elif provider == "google":
|
||||
config.google_embedding_model = "text-embedding-004"
|
||||
|
||||
# Get naming info
|
||||
dimension = config.get_embedding_dimension()
|
||||
signature = config.get_provider_signature()
|
||||
db_name = config.get_provider_specific_database_name("auto_claude_memory")
|
||||
|
||||
# Strengthened assertions with exact expected values where known
|
||||
if provider == "openai":
|
||||
assert dimension == 1536, f"OpenAI dimension should be 1536, got {dimension}"
|
||||
assert "openai" in signature.lower(), "OpenAI signature should contain 'openai'"
|
||||
# Signature format is provider_dimension for openai
|
||||
assert signature == "openai_1536", f"Expected 'openai_1536', got '{signature}'"
|
||||
elif provider == "ollama" and model == "embeddinggemma":
|
||||
assert dimension == 768, (
|
||||
f"Ollama gemma dimension should be 768, got {dimension}"
|
||||
)
|
||||
assert signature == f"ollama_{model}_{dimension}", (
|
||||
f"Expected 'ollama_{model}_{dimension}', got '{signature}'"
|
||||
)
|
||||
elif provider == "ollama" and model == "qwen3-embedding:0.6b":
|
||||
assert dimension == 1024, (
|
||||
f"Ollama qwen dimension should be 1024, got {dimension}"
|
||||
)
|
||||
# Colons in model names are replaced with underscores in signature
|
||||
assert signature == "ollama_qwen3-embedding_0_6b_1024", (
|
||||
f"Expected 'ollama_qwen3-embedding_0_6b_1024', got '{signature}'"
|
||||
)
|
||||
elif provider == "voyage":
|
||||
assert dimension == 1024, f"Voyage dimension should be 1024, got {dimension}"
|
||||
assert signature == "voyage_1024", f"Expected 'voyage_1024', got '{signature}'"
|
||||
elif provider == "google":
|
||||
assert dimension == 768, f"Google dimension should be 768, got {dimension}"
|
||||
assert signature == "google_768", f"Expected 'google_768', got '{signature}'"
|
||||
|
||||
# Verify signature appears in db_name
|
||||
assert signature is not None and signature != "", (
|
||||
f"Signature should be non-empty for {provider}"
|
||||
)
|
||||
assert signature in db_name, (
|
||||
f"Signature '{signature}' should appear in db_name '{db_name}' for {provider}"
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
Unit tests for Azure OpenAI embedder provider.
|
||||
|
||||
Tests cover:
|
||||
- create_azure_openai_embedder factory function
|
||||
- ProviderNotInstalled exception handling
|
||||
- ProviderError for missing configuration
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.providers_pkg.embedder_providers.azure_openai_embedder import (
|
||||
create_azure_openai_embedder,
|
||||
)
|
||||
from integrations.graphiti.providers_pkg.exceptions import (
|
||||
ProviderError,
|
||||
ProviderNotInstalled,
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Test create_azure_openai_embedder
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateAzureOpenAIEmbedder:
|
||||
"""Test create_azure_openai_embedder factory function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(self):
|
||||
"""Create a mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.azure_openai_api_key = "test-azure-key"
|
||||
config.azure_openai_base_url = "https://test.openai.azure.com"
|
||||
config.azure_openai_embedding_deployment = "test-embedding-deployment"
|
||||
return config
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_azure_openai_embedder_success(self, mock_config):
|
||||
"""Test create_azure_openai_embedder returns embedder with valid config."""
|
||||
mock_azure_client = MagicMock()
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.azure_openai_embedder.AsyncOpenAI",
|
||||
return_value=mock_azure_client,
|
||||
):
|
||||
with patch(
|
||||
"graphiti_core.embedder.azure_openai.AzureOpenAIEmbedderClient",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
result = create_azure_openai_embedder(mock_config)
|
||||
assert result == mock_embedder
|
||||
|
||||
def test_create_azure_openai_embedder_success_fast(self, mock_config):
|
||||
"""Fast test for create_azure_openai_embedder success path."""
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
# Mock the graphiti_core imports
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.embedder": MagicMock(),
|
||||
"graphiti_core.embedder.azure_openai": MagicMock(),
|
||||
},
|
||||
):
|
||||
from graphiti_core.embedder.azure_openai import AzureOpenAIEmbedderClient
|
||||
|
||||
AzureOpenAIEmbedderClient.return_value = mock_embedder
|
||||
|
||||
result = create_azure_openai_embedder(mock_config)
|
||||
|
||||
# Verify the embedder was created and returned
|
||||
AzureOpenAIEmbedderClient.assert_called_once()
|
||||
assert result == mock_embedder
|
||||
|
||||
def test_create_azure_openai_embedder_missing_api_key(self, mock_config):
|
||||
"""Test create_azure_openai_embedder raises ProviderError for missing API key."""
|
||||
mock_config.azure_openai_api_key = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_azure_openai_embedder(mock_config)
|
||||
|
||||
assert "AZURE_OPENAI_API_KEY" in str(exc_info.value)
|
||||
|
||||
def test_create_azure_openai_embedder_missing_base_url(self, mock_config):
|
||||
"""Test create_azure_openai_embedder raises ProviderError for missing base URL."""
|
||||
mock_config.azure_openai_base_url = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_azure_openai_embedder(mock_config)
|
||||
|
||||
assert "AZURE_OPENAI_BASE_URL" in str(exc_info.value)
|
||||
|
||||
def test_create_azure_openai_embedder_missing_deployment(self, mock_config):
|
||||
"""Test create_azure_openai_embedder raises ProviderError for missing deployment."""
|
||||
mock_config.azure_openai_embedding_deployment = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_azure_openai_embedder(mock_config)
|
||||
|
||||
assert "AZURE_OPENAI_EMBEDDING_DEPLOYMENT" in str(exc_info.value)
|
||||
|
||||
def test_create_azure_openai_embedder_import_error(self, mock_config):
|
||||
"""Test create_azure_openai_embedder raises ProviderNotInstalled on ImportError."""
|
||||
# Mock the import to raise ImportError
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
if name == "graphiti_core.embedder.azure_openai":
|
||||
raise ImportError("graphiti-core not installed")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
with pytest.raises(ProviderNotInstalled) as exc_info:
|
||||
create_azure_openai_embedder(mock_config)
|
||||
|
||||
assert "graphiti-core" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_azure_openai_embedder_passes_config_correctly(self, mock_config):
|
||||
"""Test create_azure_openai_embedder passes config values correctly."""
|
||||
mock_azure_client = MagicMock()
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.azure_openai_embedder.AsyncOpenAI",
|
||||
return_value=mock_azure_client,
|
||||
) as mock_openai:
|
||||
with patch(
|
||||
"graphiti_core.embedder.azure_openai.AzureOpenAIEmbedderClient",
|
||||
return_value=mock_embedder,
|
||||
) as mock_azure_embedder:
|
||||
create_azure_openai_embedder(mock_config)
|
||||
|
||||
# Verify AsyncOpenAI was called with correct arguments
|
||||
mock_openai.assert_called_once_with(
|
||||
base_url=mock_config.azure_openai_base_url,
|
||||
api_key=mock_config.azure_openai_api_key,
|
||||
)
|
||||
|
||||
# Verify AzureOpenAIEmbedderClient was called with correct arguments
|
||||
mock_azure_embedder.assert_called_once_with(
|
||||
azure_client=mock_azure_client,
|
||||
model=mock_config.azure_openai_embedding_deployment,
|
||||
)
|
||||
@@ -0,0 +1,252 @@
|
||||
"""
|
||||
Tests for integrations.graphiti.providers module.
|
||||
|
||||
This module is a re-export facade that re-exports all public APIs
|
||||
from the graphiti_providers package.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
# Expected exports from integrations.graphiti.providers module
|
||||
EXPECTED_EXPORTS = [
|
||||
"ProviderError",
|
||||
"ProviderNotInstalled",
|
||||
"create_llm_client",
|
||||
"create_embedder",
|
||||
"create_cross_encoder",
|
||||
"EMBEDDING_DIMENSIONS",
|
||||
"get_expected_embedding_dim",
|
||||
"validate_embedding_config",
|
||||
"test_llm_connection",
|
||||
"test_embedder_connection",
|
||||
"test_ollama_connection",
|
||||
"is_graphiti_enabled",
|
||||
"get_graph_hints",
|
||||
]
|
||||
|
||||
# =============================================================================
|
||||
# Tests for module imports
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestModuleImports:
|
||||
"""Test that all expected exports are available."""
|
||||
|
||||
def test_import_ProviderError(self):
|
||||
"""Test ProviderError can be imported."""
|
||||
from integrations.graphiti.providers import ProviderError
|
||||
|
||||
assert ProviderError is not None
|
||||
# Should be an exception class
|
||||
assert issubclass(ProviderError, Exception)
|
||||
|
||||
def test_import_ProviderNotInstalled(self):
|
||||
"""Test ProviderNotInstalled can be imported."""
|
||||
from integrations.graphiti.providers import ProviderNotInstalled
|
||||
|
||||
assert ProviderNotInstalled is not None
|
||||
# Should be an exception class
|
||||
assert issubclass(ProviderNotInstalled, Exception)
|
||||
|
||||
def test_import_create_llm_client(self):
|
||||
"""Test create_llm_client can be imported."""
|
||||
from integrations.graphiti.providers import create_llm_client
|
||||
|
||||
assert create_llm_client is not None
|
||||
assert callable(create_llm_client)
|
||||
|
||||
def test_import_create_embedder(self):
|
||||
"""Test create_embedder can be imported."""
|
||||
from integrations.graphiti.providers import create_embedder
|
||||
|
||||
assert create_embedder is not None
|
||||
assert callable(create_embedder)
|
||||
|
||||
def test_import_create_cross_encoder(self):
|
||||
"""Test create_cross_encoder can be imported."""
|
||||
from integrations.graphiti.providers import create_cross_encoder
|
||||
|
||||
assert create_cross_encoder is not None
|
||||
assert callable(create_cross_encoder)
|
||||
|
||||
def test_import_EMBEDDING_DIMENSIONS(self):
|
||||
"""Test EMBEDDING_DIMENSIONS can be imported."""
|
||||
from integrations.graphiti.providers import EMBEDDING_DIMENSIONS
|
||||
|
||||
assert EMBEDDING_DIMENSIONS is not None
|
||||
assert isinstance(EMBEDDING_DIMENSIONS, dict)
|
||||
|
||||
def test_import_get_expected_embedding_dim(self):
|
||||
"""Test get_expected_embedding_dim can be imported."""
|
||||
from integrations.graphiti.providers import get_expected_embedding_dim
|
||||
|
||||
assert get_expected_embedding_dim is not None
|
||||
assert callable(get_expected_embedding_dim)
|
||||
|
||||
def test_import_validate_embedding_config(self):
|
||||
"""Test validate_embedding_config can be imported."""
|
||||
from integrations.graphiti.providers import validate_embedding_config
|
||||
|
||||
assert validate_embedding_config is not None
|
||||
assert callable(validate_embedding_config)
|
||||
|
||||
def test_import_test_llm_connection(self):
|
||||
"""Test test_llm_connection can be imported."""
|
||||
from integrations.graphiti.providers import test_llm_connection
|
||||
|
||||
assert test_llm_connection is not None
|
||||
assert callable(test_llm_connection)
|
||||
|
||||
def test_import_test_embedder_connection(self):
|
||||
"""Test test_embedder_connection can be imported."""
|
||||
from integrations.graphiti.providers import test_embedder_connection
|
||||
|
||||
assert test_embedder_connection is not None
|
||||
assert callable(test_embedder_connection)
|
||||
|
||||
def test_import_test_ollama_connection(self):
|
||||
"""Test test_ollama_connection can be imported."""
|
||||
from integrations.graphiti.providers import test_ollama_connection
|
||||
|
||||
assert test_ollama_connection is not None
|
||||
assert callable(test_ollama_connection)
|
||||
|
||||
def test_import_is_graphiti_enabled(self):
|
||||
"""Test is_graphiti_enabled can be imported."""
|
||||
from integrations.graphiti.providers import is_graphiti_enabled
|
||||
|
||||
assert is_graphiti_enabled is not None
|
||||
assert callable(is_graphiti_enabled)
|
||||
|
||||
def test_import_get_graph_hints(self):
|
||||
"""Test get_graph_hints can be imported."""
|
||||
from integrations.graphiti.providers import get_graph_hints
|
||||
|
||||
assert get_graph_hints is not None
|
||||
assert callable(get_graph_hints)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Tests for __all__ export list
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestAllExports:
|
||||
"""Test __all__ contains expected exports."""
|
||||
|
||||
def test_all_exports_defined(self):
|
||||
"""Test __all__ is defined and contains expected items."""
|
||||
from integrations.graphiti import providers
|
||||
|
||||
assert hasattr(providers, "__all__")
|
||||
assert isinstance(providers.__all__, list)
|
||||
|
||||
for export in EXPECTED_EXPORTS:
|
||||
assert export in providers.__all__, f"{export} not in __all__"
|
||||
|
||||
def test_all_exports_count(self):
|
||||
"""Test __all__ contains the expected number of exports."""
|
||||
from integrations.graphiti import providers
|
||||
|
||||
# Should have same number of exports as EXPECTED_EXPORTS list
|
||||
assert len(providers.__all__) == len(EXPECTED_EXPORTS)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Tests for module docstring and metadata
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestModuleMetadata:
|
||||
"""Test module has proper documentation."""
|
||||
|
||||
def test_module_has_docstring(self):
|
||||
"""Test module has docstring."""
|
||||
import integrations.graphiti.providers
|
||||
|
||||
assert integrations.graphiti.providers.__doc__ is not None
|
||||
assert len(integrations.graphiti.providers.__doc__) > 0
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Tests for re-export behavior
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestReExportBehavior:
|
||||
"""Test that re-exports work correctly."""
|
||||
|
||||
def test_ProviderError_is_exception(self):
|
||||
"""Test ProviderError can be raised and caught."""
|
||||
from integrations.graphiti.providers import ProviderError
|
||||
|
||||
with pytest.raises(ProviderError):
|
||||
raise ProviderError("Test error")
|
||||
|
||||
def test_ProviderNotInstalled_is_exception(self):
|
||||
"""Test ProviderNotInstalled can be raised and caught."""
|
||||
from integrations.graphiti.providers import ProviderNotInstalled
|
||||
|
||||
with pytest.raises(ProviderNotInstalled):
|
||||
raise ProviderNotInstalled("Test error")
|
||||
|
||||
def test_ProviderNotInstalled_subclass_of_ProviderError(self):
|
||||
"""Test ProviderNotInstalled is a subclass of ProviderError."""
|
||||
from integrations.graphiti.providers import ProviderError, ProviderNotInstalled
|
||||
|
||||
assert issubclass(ProviderNotInstalled, ProviderError)
|
||||
|
||||
def test_EMBEDDING_DIMENSIONS_has_expected_keys(self):
|
||||
"""Test EMBEDDING_DIMENSIONS has expected model keys."""
|
||||
from integrations.graphiti.providers import EMBEDDING_DIMENSIONS
|
||||
|
||||
# Check that expected model names exist in EMBEDDING_DIMENSIONS
|
||||
# Note: EMBEDDING_DIMENSIONS is keyed by model name, not provider name
|
||||
expected_models = [
|
||||
"text-embedding-3-small", # OpenAI
|
||||
"voyage-3", # Voyage AI
|
||||
"nomic-embed-text", # Ollama
|
||||
"all-minilm", # Ollama
|
||||
]
|
||||
|
||||
for model in expected_models:
|
||||
assert model in EMBEDDING_DIMENSIONS, f"{model} not in EMBEDDING_DIMENSIONS"
|
||||
assert isinstance(EMBEDDING_DIMENSIONS[model], int)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Tests for namespace integrity
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestNamespaceIntegrity:
|
||||
"""Test module namespace remains consistent."""
|
||||
|
||||
def test_exports_are_accessible(self):
|
||||
"""Test all exports in __all__ are accessible."""
|
||||
from integrations.graphiti import providers
|
||||
|
||||
for name in providers.__all__:
|
||||
# Each export should be accessible
|
||||
assert hasattr(providers, name), f"{name} not accessible"
|
||||
|
||||
def test_import_from_module_works(self):
|
||||
"""Test 'from' imports work correctly."""
|
||||
# This tests the re-export mechanism
|
||||
from integrations.graphiti.providers import (
|
||||
ProviderError,
|
||||
create_embedder,
|
||||
create_llm_client,
|
||||
)
|
||||
|
||||
assert ProviderError is not None
|
||||
assert create_llm_client is not None
|
||||
assert create_embedder is not None
|
||||
|
||||
def test_module_level_import_works(self):
|
||||
"""Test module-level import works."""
|
||||
import integrations.graphiti.providers as providers
|
||||
|
||||
assert providers.ProviderError is not None
|
||||
assert providers.create_llm_client is not None
|
||||
assert providers.create_embedder is not None
|
||||
@@ -0,0 +1,256 @@
|
||||
"""
|
||||
Unit tests for Google embedder provider.
|
||||
|
||||
Tests cover:
|
||||
- create_google_embedder factory function
|
||||
- GoogleEmbedder class (create, create_batch methods)
|
||||
- ProviderNotInstalled exception handling
|
||||
- ProviderError for missing configuration
|
||||
"""
|
||||
|
||||
import sys
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.providers_pkg.embedder_providers.google_embedder import (
|
||||
DEFAULT_GOOGLE_EMBEDDING_MODEL,
|
||||
GoogleEmbedder,
|
||||
create_google_embedder,
|
||||
)
|
||||
from integrations.graphiti.providers_pkg.exceptions import (
|
||||
ProviderError,
|
||||
ProviderNotInstalled,
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Pytest fixtures
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def google_genai_mock():
|
||||
"""Mock google.generativeai module with common setup."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_genai.embed_content = MagicMock(return_value={"embedding": [0.1, 0.2, 0.3]})
|
||||
return mock_genai
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test GoogleEmbedder class
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestGoogleEmbedder:
|
||||
"""Test GoogleEmbedder class."""
|
||||
|
||||
def test_google_embedder_init_success(self, google_genai_mock):
|
||||
"""Test GoogleEmbedder initializes with API key and model."""
|
||||
# Inject mock into sys.modules before importing
|
||||
with patch.dict(sys.modules, {"google.generativeai": google_genai_mock}):
|
||||
embedder = GoogleEmbedder(api_key="test-key", model="test-model")
|
||||
|
||||
assert embedder.api_key == "test-key"
|
||||
assert embedder.model == "test-model"
|
||||
google_genai_mock.configure.assert_called_once_with(api_key="test-key")
|
||||
|
||||
def test_google_embedder_init_default_model(self, google_genai_mock):
|
||||
"""Test GoogleEmbedder uses default model when not specified."""
|
||||
# Inject mock into sys.modules before importing
|
||||
with patch.dict(sys.modules, {"google.generativeai": google_genai_mock}):
|
||||
embedder = GoogleEmbedder(api_key="test-key")
|
||||
|
||||
assert embedder.model == DEFAULT_GOOGLE_EMBEDDING_MODEL
|
||||
|
||||
def test_google_embedder_init_import_error(self):
|
||||
"""Test GoogleEmbedder raises ProviderNotInstalled on ImportError."""
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
if name == "google.generativeai" or name.startswith("google.generativeai."):
|
||||
raise ImportError("google-generativeai not installed")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
# Remove google.generativeai from sys.modules if present
|
||||
# to ensure the import actually goes through __import__
|
||||
with patch.dict(sys.modules, {"google.generativeai": None}):
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
with pytest.raises(ProviderNotInstalled) as exc_info:
|
||||
GoogleEmbedder(api_key="test-key")
|
||||
|
||||
assert "google-generativeai" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_embedder_create_with_string(self, google_genai_mock):
|
||||
"""Test GoogleEmbedder.create with string input."""
|
||||
with patch.dict(sys.modules, {"google.generativeai": google_genai_mock}):
|
||||
embedder = GoogleEmbedder(api_key="test-key")
|
||||
result = await embedder.create("test text")
|
||||
|
||||
assert result == [0.1, 0.2, 0.3]
|
||||
# Assert embed_content was called
|
||||
google_genai_mock.embed_content.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_embedder_create_with_list(self, google_genai_mock):
|
||||
"""Test GoogleEmbedder.create with list input."""
|
||||
with patch.dict(sys.modules, {"google.generativeai": google_genai_mock}):
|
||||
embedder = GoogleEmbedder(api_key="test-key")
|
||||
result = await embedder.create(["test", "text"])
|
||||
|
||||
assert result == [0.1, 0.2, 0.3]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_embedder_create_with_non_string_list(self, google_genai_mock):
|
||||
"""Test GoogleEmbedder.create with non-string list items (lines 71-73)."""
|
||||
with patch.dict(sys.modules, {"google.generativeai": google_genai_mock}):
|
||||
embedder = GoogleEmbedder(api_key="test-key")
|
||||
# List with non-string items - should convert to string
|
||||
result = await embedder.create([123, 456])
|
||||
|
||||
assert result == [0.1, 0.2, 0.3]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_embedder_create_with_empty_list(self, google_genai_mock):
|
||||
"""Test GoogleEmbedder.create with empty or invalid input (line 75)."""
|
||||
with patch.dict(sys.modules, {"google.generativeai": google_genai_mock}):
|
||||
embedder = GoogleEmbedder(api_key="test-key")
|
||||
# Empty list - should be converted to string
|
||||
result = await embedder.create([])
|
||||
|
||||
assert result == [0.1, 0.2, 0.3]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_embedder_create_batch(self, google_genai_mock):
|
||||
"""Test GoogleEmbedder.create_batch with multiple inputs (lines 100-127)."""
|
||||
# Override embed_content return value for batch test
|
||||
google_genai_mock.embed_content = MagicMock(
|
||||
return_value={"embedding": [[0.1, 0.2], [0.3, 0.4]]}
|
||||
)
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": google_genai_mock}):
|
||||
embedder = GoogleEmbedder(api_key="test-key")
|
||||
result = await embedder.create_batch(["text1", "text2"])
|
||||
|
||||
# Should handle nested list response (lines 122-125)
|
||||
assert len(result) == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_embedder_create_batch_single_response(
|
||||
self, google_genai_mock
|
||||
):
|
||||
"""Test GoogleEmbedder.create_batch with single embedding response (lines 124-125)."""
|
||||
# Override embed_content return value for single response test
|
||||
google_genai_mock.embed_content = MagicMock(
|
||||
return_value={"embedding": [0.1, 0.2, 0.3]}
|
||||
)
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": google_genai_mock}):
|
||||
embedder = GoogleEmbedder(api_key="test-key")
|
||||
result = await embedder.create_batch(["text1"])
|
||||
|
||||
# Should handle single embedding response (line 125)
|
||||
assert len(result) == 1
|
||||
assert result[0] == [0.1, 0.2, 0.3]
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_embedder_create_batch_large_input(self, google_genai_mock):
|
||||
"""Test GoogleEmbedder.create_batch with >100 items (batching)."""
|
||||
# Override embed_content return value for large batch test
|
||||
google_genai_mock.embed_content = MagicMock(
|
||||
return_value={"embedding": [[0.1, 0.2]]}
|
||||
)
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": google_genai_mock}):
|
||||
embedder = GoogleEmbedder(api_key="test-key")
|
||||
# Create 250 items - should be split into 3 batches (100, 100, 50)
|
||||
result = await embedder.create_batch([f"text{i}" for i in range(250)])
|
||||
|
||||
# Should call embed_content 3 times
|
||||
assert google_genai_mock.embed_content.call_count == 3
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test create_google_embedder
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateGoogleEmbedder:
|
||||
"""Test create_google_embedder factory function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(self):
|
||||
"""Create a mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.google_api_key = "test-google-key"
|
||||
config.google_embedding_model = None
|
||||
return config
|
||||
|
||||
def test_create_google_embedder_success(self, mock_config):
|
||||
"""Test create_google_embedder returns embedder with valid config."""
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.google_embedder.GoogleEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
result = create_google_embedder(mock_config)
|
||||
assert result == mock_embedder
|
||||
|
||||
def test_create_google_embedder_missing_api_key(self, mock_config):
|
||||
"""Test create_google_embedder raises ProviderError for missing API key."""
|
||||
mock_config.google_api_key = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_google_embedder(mock_config)
|
||||
|
||||
assert "GOOGLE_API_KEY" in str(exc_info.value)
|
||||
|
||||
def test_create_google_embedder_with_custom_model(self, mock_config):
|
||||
"""Test create_google_embedder uses custom model when specified."""
|
||||
mock_config.google_embedding_model = "custom-model"
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.google_embedder.GoogleEmbedder",
|
||||
return_value=mock_embedder,
|
||||
) as mock_google_embedder:
|
||||
create_google_embedder(mock_config)
|
||||
|
||||
mock_google_embedder.assert_called_once_with(
|
||||
api_key=mock_config.google_api_key,
|
||||
model="custom-model",
|
||||
)
|
||||
|
||||
def test_create_google_embedder_with_default_model(self, mock_config):
|
||||
"""Test create_google_embedder uses default model when not specified."""
|
||||
mock_config.google_embedding_model = None
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.google_embedder.GoogleEmbedder",
|
||||
return_value=mock_embedder,
|
||||
) as mock_google_embedder:
|
||||
create_google_embedder(mock_config)
|
||||
|
||||
mock_google_embedder.assert_called_once_with(
|
||||
api_key=mock_config.google_api_key,
|
||||
model=DEFAULT_GOOGLE_EMBEDDING_MODEL,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test Constants
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestGoogleEmbedderConstants:
|
||||
"""Test Google embedder constants."""
|
||||
|
||||
def test_default_google_embedding_model(self):
|
||||
# Note: This test verifies the default Google embedding model.
|
||||
# The value should match the model used in production.
|
||||
assert DEFAULT_GOOGLE_EMBEDDING_MODEL == "text-embedding-004"
|
||||
@@ -0,0 +1,146 @@
|
||||
"""
|
||||
Unit tests for Anthropic LLM provider.
|
||||
|
||||
Tests cover:
|
||||
- create_anthropic_llm_client factory function
|
||||
- ProviderNotInstalled exception handling
|
||||
- ProviderError for missing configuration
|
||||
"""
|
||||
|
||||
import sys
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.providers_pkg.exceptions import (
|
||||
ProviderError,
|
||||
ProviderNotInstalled,
|
||||
)
|
||||
from integrations.graphiti.providers_pkg.llm_providers.anthropic_llm import (
|
||||
create_anthropic_llm_client,
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Test create_anthropic_llm_client
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateAnthropicLLMClient:
|
||||
"""Test create_anthropic_llm_client factory function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(self):
|
||||
"""Create a mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.anthropic_api_key = "sk-ant-test-key"
|
||||
config.anthropic_model = "claude-sonnet-4-20250514"
|
||||
return config
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_anthropic_llm_client_success(self, mock_config):
|
||||
"""Test create_anthropic_llm_client returns client with valid config."""
|
||||
mock_client = MagicMock()
|
||||
|
||||
# Patch at the location where the import happens (local import inside function)
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.anthropic_llm.AnthropicClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
result = create_anthropic_llm_client(mock_config)
|
||||
assert result == mock_client
|
||||
|
||||
def test_create_anthropic_llm_client_success_fast(self, mock_config):
|
||||
"""Fast test for create_anthropic_llm_client success path."""
|
||||
mock_llm_client = MagicMock()
|
||||
|
||||
# Create the config mock
|
||||
mock_config_module = MagicMock()
|
||||
mock_config_module.LLMConfig = MagicMock
|
||||
|
||||
# Mock the graphiti_core imports
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.llm_client": MagicMock(),
|
||||
"graphiti_core.llm_client.anthropic_client": MagicMock(),
|
||||
"graphiti_core.llm_client.config": mock_config_module,
|
||||
},
|
||||
):
|
||||
from graphiti_core.llm_client.anthropic_client import AnthropicClient
|
||||
|
||||
AnthropicClient.return_value = mock_llm_client
|
||||
|
||||
result = create_anthropic_llm_client(mock_config)
|
||||
|
||||
# Verify the client was created and returned
|
||||
AnthropicClient.assert_called_once()
|
||||
assert result == mock_llm_client
|
||||
|
||||
def test_create_anthropic_llm_client_missing_api_key_fast(self, mock_config):
|
||||
"""Fast test for API key validation (line 41)."""
|
||||
# Mock the graphiti_core imports first to avoid ImportError
|
||||
mock_config_module = MagicMock()
|
||||
mock_config_module.LLMConfig = MagicMock
|
||||
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.llm_client": MagicMock(),
|
||||
"graphiti_core.llm_client.anthropic_client": MagicMock(),
|
||||
"graphiti_core.llm_client.config": mock_config_module,
|
||||
},
|
||||
):
|
||||
from graphiti_core.llm_client.anthropic_client import AnthropicClient
|
||||
|
||||
AnthropicClient.return_value = MagicMock()
|
||||
|
||||
# Now set API key to None to test validation
|
||||
mock_config.anthropic_api_key = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_anthropic_llm_client(mock_config)
|
||||
|
||||
assert "ANTHROPIC_API_KEY" in str(exc_info.value)
|
||||
|
||||
def test_create_anthropic_llm_client_import_error(self, mock_config):
|
||||
"""Test create_anthropic_llm_client raises ProviderNotInstalled on ImportError."""
|
||||
from types import ModuleType
|
||||
|
||||
# Create a broken module that raises ImportError on attribute access
|
||||
def broken_getattr(name):
|
||||
if name in ("llm_client", "anthropic_client", "config"):
|
||||
raise ImportError("graphiti-core[anthropic] not installed")
|
||||
raise AttributeError(f"module has no attribute '{name}'")
|
||||
|
||||
broken_module = ModuleType("graphiti_core")
|
||||
broken_module.__getattr__ = broken_getattr
|
||||
|
||||
# Patch both modules that are imported
|
||||
with patch.dict(sys.modules, {"graphiti_core": broken_module}):
|
||||
with pytest.raises(ProviderNotInstalled) as exc_info:
|
||||
create_anthropic_llm_client(mock_config)
|
||||
|
||||
assert "graphiti-core[anthropic]" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_anthropic_llm_client_passes_config_correctly(self, mock_config):
|
||||
"""Test create_anthropic_llm_client passes config values correctly."""
|
||||
mock_config.anthropic_api_key = "sk-ant-test-key-123"
|
||||
mock_config.anthropic_model = "claude-opus-4-20250514"
|
||||
mock_client = MagicMock()
|
||||
|
||||
# Patch at the location where the imports happen (local imports inside function)
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.anthropic_llm.LLMConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.anthropic_llm.AnthropicClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
create_anthropic_llm_client(mock_config)
|
||||
|
||||
# Verify LLMConfig was called with correct arguments
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["api_key"] == "sk-ant-test-key-123"
|
||||
assert call_kwargs["model"] == "claude-opus-4-20250514"
|
||||
@@ -0,0 +1,163 @@
|
||||
"""
|
||||
Unit tests for Azure OpenAI LLM provider.
|
||||
|
||||
Tests cover:
|
||||
- create_azure_openai_llm_client factory function
|
||||
- ProviderNotInstalled exception handling
|
||||
- ProviderError for missing configuration
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.providers_pkg.exceptions import (
|
||||
ProviderError,
|
||||
ProviderNotInstalled,
|
||||
)
|
||||
from integrations.graphiti.providers_pkg.llm_providers.azure_openai_llm import (
|
||||
create_azure_openai_llm_client,
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Test create_azure_openai_llm_client
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateAzureOpenAILLMClient:
|
||||
"""Test create_azure_openai_llm_client factory function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(self):
|
||||
"""Create a mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.azure_openai_api_key = "test-azure-key"
|
||||
config.azure_openai_base_url = "https://test.openai.azure.com"
|
||||
config.azure_openai_llm_deployment = "test-llm-deployment"
|
||||
return config
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_azure_openai_llm_client_success(self, mock_config):
|
||||
"""Test create_azure_openai_llm_client returns client with valid config."""
|
||||
mock_azure_client = MagicMock()
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.azure_openai_llm.AsyncOpenAI",
|
||||
return_value=mock_azure_client,
|
||||
):
|
||||
with patch(
|
||||
"graphiti_core.llm_client.azure_openai_client.AzureOpenAILLMClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
result = create_azure_openai_llm_client(mock_config)
|
||||
assert result == mock_client
|
||||
|
||||
def test_create_azure_openai_llm_client_success_fast(self, mock_config):
|
||||
"""Fast test for create_azure_openai_llm_client success path."""
|
||||
mock_llm_client = MagicMock()
|
||||
|
||||
# Mock the graphiti_core imports
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.llm_client": MagicMock(),
|
||||
"graphiti_core.llm_client.azure_openai_client": MagicMock(),
|
||||
"graphiti_core.llm_client.config": MagicMock(),
|
||||
},
|
||||
):
|
||||
from graphiti_core.llm_client.azure_openai_client import (
|
||||
AzureOpenAILLMClient,
|
||||
)
|
||||
|
||||
AzureOpenAILLMClient.return_value = mock_llm_client
|
||||
|
||||
result = create_azure_openai_llm_client(mock_config)
|
||||
|
||||
# Verify the client was created and returned
|
||||
AzureOpenAILLMClient.assert_called_once()
|
||||
assert result == mock_llm_client
|
||||
|
||||
def test_create_azure_openai_llm_client_missing_api_key(self, mock_config):
|
||||
"""Test create_azure_openai_llm_client raises ProviderError for missing API key."""
|
||||
mock_config.azure_openai_api_key = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_azure_openai_llm_client(mock_config)
|
||||
|
||||
assert "AZURE_OPENAI_API_KEY" in str(exc_info.value)
|
||||
|
||||
def test_create_azure_openai_llm_client_missing_base_url(self, mock_config):
|
||||
"""Test create_azure_openai_llm_client raises ProviderError for missing base URL."""
|
||||
mock_config.azure_openai_base_url = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_azure_openai_llm_client(mock_config)
|
||||
|
||||
assert "AZURE_OPENAI_BASE_URL" in str(exc_info.value)
|
||||
|
||||
def test_create_azure_openai_llm_client_missing_deployment(self, mock_config):
|
||||
"""Test create_azure_openai_llm_client raises ProviderError for missing deployment."""
|
||||
mock_config.azure_openai_llm_deployment = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_azure_openai_llm_client(mock_config)
|
||||
|
||||
assert "AZURE_OPENAI_LLM_DEPLOYMENT" in str(exc_info.value)
|
||||
|
||||
def test_create_azure_openai_llm_client_import_error(self, mock_config):
|
||||
"""Test create_azure_openai_llm_client raises ProviderNotInstalled on ImportError."""
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
if (
|
||||
name.startswith("graphiti_core.llm_client")
|
||||
or name == "openai"
|
||||
or name.startswith("openai.")
|
||||
):
|
||||
raise ImportError("Required package not installed")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
with pytest.raises(ProviderNotInstalled) as exc_info:
|
||||
create_azure_openai_llm_client(mock_config)
|
||||
|
||||
assert "graphiti-core" in str(exc_info.value)
|
||||
assert "openai" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_azure_openai_llm_client_passes_config_correctly(self, mock_config):
|
||||
"""Test create_azure_openai_llm_client passes config values correctly."""
|
||||
mock_azure_client = MagicMock()
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.azure_openai_llm.AsyncOpenAI",
|
||||
return_value=mock_azure_client,
|
||||
) as mock_openai:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.azure_openai_llm.LLMConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"graphiti_core.llm_client.azure_openai_client.AzureOpenAILLMClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
create_azure_openai_llm_client(mock_config)
|
||||
|
||||
# Verify AsyncOpenAI was called with correct arguments
|
||||
mock_openai.assert_called_once_with(
|
||||
base_url=mock_config.azure_openai_base_url,
|
||||
api_key=mock_config.azure_openai_api_key,
|
||||
)
|
||||
|
||||
# Verify LLMConfig was called with correct arguments
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert (
|
||||
call_kwargs["model"] == mock_config.azure_openai_llm_deployment
|
||||
)
|
||||
assert (
|
||||
call_kwargs["small_model"]
|
||||
== mock_config.azure_openai_llm_deployment
|
||||
)
|
||||
@@ -0,0 +1,410 @@
|
||||
"""
|
||||
Unit tests for Google LLM provider.
|
||||
|
||||
Tests cover:
|
||||
- create_google_llm_client factory function
|
||||
- GoogleLLMClient class (generate_response, generate_response_with_tools)
|
||||
- ProviderNotInstalled exception handling
|
||||
- ProviderError for missing configuration
|
||||
"""
|
||||
|
||||
import sys
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.providers_pkg.exceptions import (
|
||||
ProviderError,
|
||||
ProviderNotInstalled,
|
||||
)
|
||||
from integrations.graphiti.providers_pkg.llm_providers.google_llm import (
|
||||
DEFAULT_GOOGLE_LLM_MODEL,
|
||||
GoogleLLMClient,
|
||||
create_google_llm_client,
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Test GoogleLLMClient class
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestGoogleLLMClient:
|
||||
"""Test GoogleLLMClient class."""
|
||||
|
||||
def test_google_llm_client_init_success(self):
|
||||
"""Test GoogleLLMClient initializes with API key and model."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_model = MagicMock()
|
||||
mock_genai.GenerativeModel = MagicMock(return_value=mock_model)
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": mock_genai}):
|
||||
client = GoogleLLMClient(api_key="test-key", model="test-model")
|
||||
|
||||
assert client.api_key == "test-key"
|
||||
assert client.model == "test-model"
|
||||
mock_genai.configure.assert_called_once_with(api_key="test-key")
|
||||
mock_genai.GenerativeModel.assert_called_once_with("test-model")
|
||||
|
||||
def test_google_llm_client_init_default_model(self):
|
||||
"""Test GoogleLLMClient uses default model when not specified."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_model = MagicMock()
|
||||
mock_genai.GenerativeModel = MagicMock(return_value=mock_model)
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": mock_genai}):
|
||||
client = GoogleLLMClient(api_key="test-key")
|
||||
|
||||
assert client.model == DEFAULT_GOOGLE_LLM_MODEL
|
||||
|
||||
def test_google_llm_client_init_import_error(self):
|
||||
"""Test GoogleLLMClient raises ProviderNotInstalled on ImportError."""
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
if name == "google.generativeai" or name.startswith("google.generativeai."):
|
||||
raise ImportError("google-generativeai not installed")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
with pytest.raises(ProviderNotInstalled) as exc_info:
|
||||
GoogleLLMClient(api_key="test-key")
|
||||
|
||||
assert "google-generativeai" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_llm_client_generate_response_with_user_message(self):
|
||||
"""Test GoogleLLMClient.generate_response with user message (lines 73-133)."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_model = MagicMock()
|
||||
mock_genai.GenerativeModel = MagicMock(return_value=mock_model)
|
||||
mock_response = MagicMock()
|
||||
mock_response.text = "Test response"
|
||||
mock_model.generate_content = MagicMock(return_value=mock_response)
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": mock_genai}):
|
||||
client = GoogleLLMClient(api_key="test-key")
|
||||
result = await client.generate_response(
|
||||
[{"role": "user", "content": "Hello"}]
|
||||
)
|
||||
|
||||
assert result == "Test response"
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_llm_client_generate_response_with_user_message_slow(self):
|
||||
"""Test GoogleLLMClient.generate_response with user message (slow variant)."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_model = MagicMock()
|
||||
mock_genai.GenerativeModel = MagicMock(return_value=mock_model)
|
||||
mock_response = MagicMock()
|
||||
mock_response.text = "Test response"
|
||||
mock_model.generate_content = MagicMock(return_value=mock_response)
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": mock_genai}):
|
||||
client = GoogleLLMClient(api_key="test-key")
|
||||
result = await client.generate_response(
|
||||
[{"role": "user", "content": "Hello"}]
|
||||
)
|
||||
|
||||
assert result == "Test response"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_llm_client_generate_response_with_system_message(self):
|
||||
"""Test GoogleLLMClient.generate_response with system instruction (lines 84-98)."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_model_with_sys = MagicMock()
|
||||
mock_model_without_sys = MagicMock()
|
||||
mock_genai.GenerativeModel = MagicMock(
|
||||
side_effect=[mock_model_without_sys, mock_model_with_sys]
|
||||
)
|
||||
mock_response = MagicMock()
|
||||
mock_response.text = "Test response"
|
||||
mock_model_with_sys.generate_content = MagicMock(return_value=mock_response)
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": mock_genai}):
|
||||
client = GoogleLLMClient(api_key="test-key")
|
||||
result = await client.generate_response(
|
||||
[
|
||||
{"role": "system", "content": "You are helpful"},
|
||||
{"role": "user", "content": "Hello"},
|
||||
]
|
||||
)
|
||||
|
||||
assert result == "Test response"
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_llm_client_generate_response_with_system_message_slow(self):
|
||||
"""Test GoogleLLMClient.generate_response with system instruction (slow variant)."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_model_with_sys = MagicMock()
|
||||
mock_model_without_sys = MagicMock()
|
||||
mock_genai.GenerativeModel = MagicMock(
|
||||
side_effect=[mock_model_without_sys, mock_model_with_sys]
|
||||
)
|
||||
mock_response = MagicMock()
|
||||
mock_response.text = "Test response"
|
||||
mock_model_with_sys.generate_content = MagicMock(return_value=mock_response)
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": mock_genai}):
|
||||
client = GoogleLLMClient(api_key="test-key")
|
||||
result = await client.generate_response(
|
||||
[
|
||||
{"role": "system", "content": "You are helpful"},
|
||||
{"role": "user", "content": "Hello"},
|
||||
]
|
||||
)
|
||||
|
||||
assert result == "Test response"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_llm_client_generate_response_with_assistant_message(self):
|
||||
"""Test GoogleLLMClient.generate_response with assistant role (lines 87-88)."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_model = MagicMock()
|
||||
mock_genai.GenerativeModel = MagicMock(return_value=mock_model)
|
||||
mock_response = MagicMock()
|
||||
mock_response.text = "Test response"
|
||||
mock_model.generate_content = MagicMock(return_value=mock_response)
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": mock_genai}):
|
||||
client = GoogleLLMClient(api_key="test-key")
|
||||
result = await client.generate_response(
|
||||
[
|
||||
{"role": "user", "content": "Hello"},
|
||||
{"role": "assistant", "content": "Hi there"},
|
||||
{"role": "user", "content": "How are you?"},
|
||||
]
|
||||
)
|
||||
|
||||
assert result == "Test response"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_llm_client_generate_response_with_response_model(self):
|
||||
"""Test GoogleLLMClient.generate_response with structured output (lines 103-127)."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_model = MagicMock()
|
||||
mock_genai.GenerativeModel = MagicMock(return_value=mock_model)
|
||||
mock_response = MagicMock()
|
||||
mock_response.text = '{"key": "value"}'
|
||||
mock_model.generate_content = MagicMock(return_value=mock_response)
|
||||
mock_genai.GenerationConfig = MagicMock()
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": mock_genai}):
|
||||
from pydantic import BaseModel
|
||||
|
||||
class TestModel(BaseModel):
|
||||
key: str
|
||||
|
||||
client = GoogleLLMClient(api_key="test-key")
|
||||
result = await client.generate_response(
|
||||
[{"role": "user", "content": "Hello"}],
|
||||
response_model=TestModel,
|
||||
)
|
||||
|
||||
assert isinstance(result, TestModel)
|
||||
assert result.key == "value"
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_llm_client_generate_response_with_response_model_slow(self):
|
||||
"""Test GoogleLLMClient.generate_response with structured output (slow variant)."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_model = MagicMock()
|
||||
mock_genai.GenerativeModel = MagicMock(return_value=mock_model)
|
||||
mock_response = MagicMock()
|
||||
mock_response.text = '{"key": "value"}'
|
||||
mock_model.generate_content = MagicMock(return_value=mock_response)
|
||||
mock_genai.GenerationConfig = MagicMock()
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": mock_genai}):
|
||||
from pydantic import BaseModel
|
||||
|
||||
class TestModel(BaseModel):
|
||||
key: str
|
||||
|
||||
client = GoogleLLMClient(api_key="test-key")
|
||||
result = await client.generate_response(
|
||||
[{"role": "user", "content": "Hello"}],
|
||||
response_model=TestModel,
|
||||
)
|
||||
|
||||
assert isinstance(result, TestModel)
|
||||
assert result.key == "value"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_llm_client_generate_response_json_decode_error(self):
|
||||
"""Test GoogleLLMClient.generate_response with JSON decode error (lines 122-127)."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_model = MagicMock()
|
||||
mock_genai.GenerativeModel = MagicMock(return_value=mock_model)
|
||||
mock_response = MagicMock()
|
||||
mock_response.text = "Not valid JSON"
|
||||
mock_model.generate_content = MagicMock(return_value=mock_response)
|
||||
mock_genai.GenerationConfig = MagicMock()
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": mock_genai}):
|
||||
from pydantic import BaseModel
|
||||
|
||||
class TestModel(BaseModel):
|
||||
key: str
|
||||
|
||||
client = GoogleLLMClient(api_key="test-key")
|
||||
result = await client.generate_response(
|
||||
[{"role": "user", "content": "Hello"}],
|
||||
response_model=TestModel,
|
||||
)
|
||||
|
||||
# Should return raw text when JSON parsing fails
|
||||
assert result == "Not valid JSON"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_llm_client_generate_response_with_tools(self):
|
||||
"""Test GoogleLLMClient.generate_response_with_tools (lines 155-160)."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_model = MagicMock()
|
||||
mock_genai.GenerativeModel = MagicMock(return_value=mock_model)
|
||||
mock_response = MagicMock()
|
||||
mock_response.text = "Test response"
|
||||
mock_model.generate_content = MagicMock(return_value=mock_response)
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": mock_genai}):
|
||||
client = GoogleLLMClient(api_key="test-key")
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.google_llm.logger"
|
||||
) as mock_logger:
|
||||
result = await client.generate_response_with_tools(
|
||||
[{"role": "user", "content": "Hello"}],
|
||||
tools=[{"name": "test_tool"}],
|
||||
)
|
||||
|
||||
# Should log warning about tools not being supported
|
||||
mock_logger.warning.assert_called_once()
|
||||
assert "does not yet support tool calling" in str(
|
||||
mock_logger.warning.call_args
|
||||
)
|
||||
assert result == "Test response"
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.asyncio
|
||||
async def test_google_llm_client_generate_response_with_tools_slow(self):
|
||||
"""Test GoogleLLMClient.generate_response_with_tools (slow variant)."""
|
||||
mock_genai = MagicMock()
|
||||
mock_genai.configure = MagicMock()
|
||||
mock_model = MagicMock()
|
||||
mock_genai.GenerativeModel = MagicMock(return_value=mock_model)
|
||||
mock_response = MagicMock()
|
||||
mock_response.text = "Test response"
|
||||
mock_model.generate_content = MagicMock(return_value=mock_response)
|
||||
|
||||
with patch.dict(sys.modules, {"google.generativeai": mock_genai}):
|
||||
client = GoogleLLMClient(api_key="test-key")
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.google_llm.logger"
|
||||
) as mock_logger:
|
||||
result = await client.generate_response_with_tools(
|
||||
[{"role": "user", "content": "Hello"}],
|
||||
tools=[{"name": "test_tool"}],
|
||||
)
|
||||
|
||||
mock_logger.warning.assert_called_once()
|
||||
assert "does not yet support tool calling" in str(
|
||||
mock_logger.warning.call_args
|
||||
)
|
||||
assert result == "Test response"
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test create_google_llm_client
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateGoogleLLMClient:
|
||||
"""Test create_google_llm_client factory function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(self):
|
||||
"""Create a mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.google_api_key = "test-google-key"
|
||||
config.google_llm_model = None
|
||||
return config
|
||||
|
||||
def test_create_google_llm_client_success(self, mock_config):
|
||||
"""Test create_google_llm_client returns client with valid config."""
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.google_llm.GoogleLLMClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
result = create_google_llm_client(mock_config)
|
||||
assert result == mock_client
|
||||
|
||||
def test_create_google_llm_client_missing_api_key(self, mock_config):
|
||||
"""Test create_google_llm_client raises ProviderError for missing API key."""
|
||||
mock_config.google_api_key = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_google_llm_client(mock_config)
|
||||
|
||||
assert "GOOGLE_API_KEY" in str(exc_info.value)
|
||||
|
||||
def test_create_google_llm_client_with_custom_model(self, mock_config):
|
||||
"""Test create_google_llm_client uses custom model when specified."""
|
||||
mock_config.google_llm_model = "custom-model"
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.google_llm.GoogleLLMClient",
|
||||
return_value=mock_client,
|
||||
) as mock_google_client:
|
||||
create_google_llm_client(mock_config)
|
||||
|
||||
mock_google_client.assert_called_once_with(
|
||||
api_key=mock_config.google_api_key,
|
||||
model="custom-model",
|
||||
)
|
||||
|
||||
def test_create_google_llm_client_with_default_model(self, mock_config):
|
||||
"""Test create_google_llm_client uses default model when not specified."""
|
||||
mock_config.google_llm_model = None
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.google_llm.GoogleLLMClient",
|
||||
return_value=mock_client,
|
||||
) as mock_google_client:
|
||||
create_google_llm_client(mock_config)
|
||||
|
||||
mock_google_client.assert_called_once_with(
|
||||
api_key=mock_config.google_api_key,
|
||||
model=DEFAULT_GOOGLE_LLM_MODEL,
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test Constants
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestGoogleLLMConstants:
|
||||
"""Test Google LLM constants."""
|
||||
|
||||
def test_default_google_llm_model(self):
|
||||
"""Test DEFAULT_GOOGLE_LLM_MODEL is set correctly."""
|
||||
assert DEFAULT_GOOGLE_LLM_MODEL == "gemini-2.0-flash"
|
||||
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
Unit tests for Ollama LLM provider.
|
||||
|
||||
Tests cover:
|
||||
- create_ollama_llm_client factory function
|
||||
- ProviderNotInstalled exception handling
|
||||
- ProviderError for missing configuration
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.providers_pkg.exceptions import (
|
||||
ProviderError,
|
||||
ProviderNotInstalled,
|
||||
)
|
||||
from integrations.graphiti.providers_pkg.llm_providers.ollama_llm import (
|
||||
create_ollama_llm_client,
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Test create_ollama_llm_client
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateOllamaLLMClient:
|
||||
"""Test create_ollama_llm_client factory function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(self):
|
||||
"""Create a mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.ollama_llm_model = "llama3.2"
|
||||
config.ollama_base_url = "http://localhost:11434"
|
||||
return config
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_ollama_llm_client_success(self, mock_config):
|
||||
"""Test create_ollama_llm_client returns client with valid config."""
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.ollama_llm.OpenAIGenericClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
result = create_ollama_llm_client(mock_config)
|
||||
assert result == mock_client
|
||||
|
||||
def test_create_ollama_llm_client_success_fast(self, mock_config):
|
||||
"""Fast test for create_ollama_llm_client success path."""
|
||||
mock_llm_client = MagicMock()
|
||||
|
||||
# Create the config mock
|
||||
mock_config_module = MagicMock()
|
||||
mock_config_module.LLMConfig = MagicMock
|
||||
|
||||
# Mock the graphiti_core imports
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.llm_client": MagicMock(),
|
||||
"graphiti_core.llm_client.config": mock_config_module,
|
||||
"graphiti_core.llm_client.openai_generic_client": MagicMock(),
|
||||
},
|
||||
):
|
||||
from graphiti_core.llm_client.openai_generic_client import (
|
||||
OpenAIGenericClient,
|
||||
)
|
||||
|
||||
OpenAIGenericClient.return_value = mock_llm_client
|
||||
|
||||
result = create_ollama_llm_client(mock_config)
|
||||
|
||||
# Verify the client was created and returned
|
||||
OpenAIGenericClient.assert_called_once()
|
||||
assert result == mock_llm_client
|
||||
|
||||
def test_create_ollama_llm_client_missing_model(self, mock_config):
|
||||
"""Test create_ollama_llm_client raises ProviderError for missing model."""
|
||||
mock_config.ollama_llm_model = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_ollama_llm_client(mock_config)
|
||||
|
||||
assert "OLLAMA_LLM_MODEL" in str(exc_info.value)
|
||||
|
||||
def test_create_ollama_llm_client_import_error(self, mock_config):
|
||||
"""Test create_ollama_llm_client raises ProviderNotInstalled on ImportError."""
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
if name.startswith("graphiti_core.llm_client"):
|
||||
raise ImportError("graphiti-core not installed")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
with pytest.raises(ProviderNotInstalled) as exc_info:
|
||||
create_ollama_llm_client(mock_config)
|
||||
|
||||
assert "graphiti-core" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_ollama_llm_client_base_url_without_v1(self, mock_config):
|
||||
"""Test create_ollama_llm_client appends /v1 to base URL if missing."""
|
||||
mock_config.ollama_base_url = "http://localhost:11434"
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.ollama_llm.LLMConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.ollama_llm.OpenAIGenericClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
create_ollama_llm_client(mock_config)
|
||||
|
||||
# Verify base_url has /v1 appended
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["base_url"] == "http://localhost:11434/v1"
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_ollama_llm_client_base_url_with_v1(self, mock_config):
|
||||
"""Test create_ollama_llm_client doesn't duplicate /v1 in base URL."""
|
||||
mock_config.ollama_base_url = "http://localhost:11434/v1"
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.ollama_llm.LLMConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.ollama_llm.OpenAIGenericClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
create_ollama_llm_client(mock_config)
|
||||
|
||||
# Verify base_url is not duplicated
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["base_url"] == "http://localhost:11434/v1"
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_ollama_llm_client_base_url_with_trailing_slash(self, mock_config):
|
||||
"""Test create_ollama_llm_client handles trailing slash correctly."""
|
||||
mock_config.ollama_base_url = "http://localhost:11434/"
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.ollama_llm.LLMConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.ollama_llm.OpenAIGenericClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
create_ollama_llm_client(mock_config)
|
||||
|
||||
# Verify trailing slash is handled
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["base_url"] == "http://localhost:11434/v1"
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_ollama_llm_client_passes_config_correctly(self, mock_config):
|
||||
"""Test create_ollama_llm_client passes config values correctly."""
|
||||
mock_config.ollama_llm_model = "qwen2.5"
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.ollama_llm.LLMConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.ollama_llm.OpenAIGenericClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
create_ollama_llm_client(mock_config)
|
||||
|
||||
# Verify LLMConfig was called with correct arguments
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["api_key"] == "ollama"
|
||||
assert call_kwargs["model"] == "qwen2.5"
|
||||
assert call_kwargs["small_model"] == "qwen2.5"
|
||||
@@ -0,0 +1,207 @@
|
||||
"""
|
||||
Unit tests for OpenAI LLM provider.
|
||||
|
||||
Tests cover:
|
||||
- create_openai_llm_client factory function
|
||||
- ProviderNotInstalled exception handling
|
||||
- ProviderError for missing configuration
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.providers_pkg.exceptions import (
|
||||
ProviderError,
|
||||
ProviderNotInstalled,
|
||||
)
|
||||
from integrations.graphiti.providers_pkg.llm_providers.openai_llm import (
|
||||
create_openai_llm_client,
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Test create_openai_llm_client
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateOpenAILLMClient:
|
||||
"""Test create_openai_llm_client factory function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(self):
|
||||
"""Create a mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.openai_api_key = "sk-test-key"
|
||||
config.openai_model = "gpt-4o"
|
||||
return config
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_openai_llm_client_success(self, mock_config):
|
||||
"""Test create_openai_llm_client returns client with valid config."""
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.openai_llm.OpenAIClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
result = create_openai_llm_client(mock_config)
|
||||
assert result == mock_client
|
||||
|
||||
def test_create_openai_llm_client_success_fast(self, mock_config):
|
||||
"""Fast test for create_openai_llm_client success path."""
|
||||
mock_llm_client = MagicMock()
|
||||
|
||||
# Create the config mock
|
||||
mock_config_module = MagicMock()
|
||||
mock_config_module.LLMConfig = MagicMock
|
||||
|
||||
# Mock the graphiti_core imports
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.llm_client": MagicMock(),
|
||||
"graphiti_core.llm_client.config": mock_config_module,
|
||||
"graphiti_core.llm_client.openai_client": MagicMock(),
|
||||
},
|
||||
):
|
||||
from graphiti_core.llm_client.openai_client import OpenAIClient
|
||||
|
||||
OpenAIClient.return_value = mock_llm_client
|
||||
|
||||
result = create_openai_llm_client(mock_config)
|
||||
|
||||
# Verify the client was created and returned
|
||||
OpenAIClient.assert_called_once()
|
||||
assert result == mock_llm_client
|
||||
|
||||
def test_create_openai_llm_client_missing_api_key(self, mock_config):
|
||||
"""Test create_openai_llm_client raises ProviderError for missing API key."""
|
||||
mock_config.openai_api_key = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_openai_llm_client(mock_config)
|
||||
|
||||
assert "OPENAI_API_KEY" in str(exc_info.value)
|
||||
|
||||
def test_create_openai_llm_client_import_error(self, mock_config):
|
||||
"""Test create_openai_llm_client raises ProviderNotInstalled on ImportError."""
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
if name.startswith("graphiti_core.llm_client"):
|
||||
raise ImportError("graphiti-core not installed")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
with pytest.raises(ProviderNotInstalled) as exc_info:
|
||||
create_openai_llm_client(mock_config)
|
||||
|
||||
assert "graphiti-core" in str(exc_info.value)
|
||||
|
||||
def test_create_openai_llm_client_gpt5_model_with_reasoning_fast(self, mock_config):
|
||||
"""Fast test for GPT-5 model with reasoning (line 58)."""
|
||||
mock_config.openai_model = "gpt-5-turbo"
|
||||
mock_client = MagicMock()
|
||||
|
||||
# Create the config mock
|
||||
mock_config_module = MagicMock()
|
||||
mock_config_module.LLMConfig = MagicMock
|
||||
|
||||
# Mock the graphiti_core imports
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.llm_client": MagicMock(),
|
||||
"graphiti_core.llm_client.config": mock_config_module,
|
||||
"graphiti_core.llm_client.openai_client": MagicMock(),
|
||||
},
|
||||
):
|
||||
from graphiti_core.llm_client.openai_client import OpenAIClient
|
||||
|
||||
OpenAIClient.return_value = mock_client
|
||||
|
||||
result = create_openai_llm_client(mock_config)
|
||||
|
||||
# Verify the client was created with default config (no extra params)
|
||||
OpenAIClient.assert_called_once()
|
||||
call_kwargs = OpenAIClient.call_args.kwargs
|
||||
# Should not have reasoning/verbosity params set to None for GPT-5
|
||||
assert (
|
||||
"reasoning" not in call_kwargs
|
||||
or call_kwargs.get("reasoning") is not False
|
||||
)
|
||||
assert (
|
||||
"verbosity" not in call_kwargs
|
||||
or call_kwargs.get("verbosity") is not False
|
||||
)
|
||||
assert result == mock_client
|
||||
|
||||
@pytest.mark.slow
|
||||
@pytest.mark.parametrize(
|
||||
"model,expected_reasoning,expected_verbosity",
|
||||
[
|
||||
pytest.param("gpt-5-turbo", True, None, id="gpt5"),
|
||||
pytest.param("o1-preview", True, None, id="o1"),
|
||||
pytest.param("o3-mini", True, None, id="o3"),
|
||||
],
|
||||
)
|
||||
def test_create_openai_llm_client_reasoning_models(
|
||||
self, mock_config, model, expected_reasoning, expected_verbosity
|
||||
):
|
||||
"""Test create_openai_llm_client with reasoning-capable models."""
|
||||
mock_config.openai_model = model
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.openai_llm.OpenAIClient",
|
||||
return_value=mock_client,
|
||||
) as mock_openai_client:
|
||||
create_openai_llm_client(mock_config)
|
||||
|
||||
mock_openai_client.assert_called_once()
|
||||
call_kwargs = mock_openai_client.call_args.kwargs
|
||||
# Verify reasoning is set to True for reasoning models
|
||||
assert call_kwargs.get("reasoning") is expected_reasoning
|
||||
# Verify verbosity matches expected value (None for these models)
|
||||
assert call_kwargs.get("verbosity") == expected_verbosity
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_openai_llm_client_gpt4_model_without_reasoning(self, mock_config):
|
||||
"""Test create_openai_llm_client with GPT-4 model disables reasoning."""
|
||||
mock_config.openai_model = "gpt-4o"
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.openai_llm.OpenAIClient",
|
||||
return_value=mock_client,
|
||||
) as mock_openai_client:
|
||||
create_openai_llm_client(mock_config)
|
||||
|
||||
# GPT-4 models should be created with reasoning=None, verbosity=None
|
||||
call_kwargs = mock_openai_client.call_args.kwargs
|
||||
assert call_kwargs.get("reasoning") is None
|
||||
assert call_kwargs.get("verbosity") is None
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_openai_llm_client_passes_config_correctly(self, mock_config):
|
||||
"""Test create_openai_llm_client passes config values correctly."""
|
||||
mock_config.openai_api_key = "sk-test-key-123"
|
||||
mock_config.openai_model = "gpt-4o-mini"
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.openai_llm.LLMConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.openai_llm.OpenAIClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
create_openai_llm_client(mock_config)
|
||||
|
||||
# Verify LLMConfig was called with correct arguments
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["api_key"] == "sk-test-key-123"
|
||||
assert call_kwargs["model"] == "gpt-4o-mini"
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
Unit tests for OpenRouter LLM provider.
|
||||
|
||||
Tests cover:
|
||||
- create_openrouter_llm_client factory function
|
||||
- ProviderNotInstalled exception handling
|
||||
- ProviderError for missing configuration
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.providers_pkg.exceptions import (
|
||||
ProviderError,
|
||||
ProviderNotInstalled,
|
||||
)
|
||||
from integrations.graphiti.providers_pkg.llm_providers.openrouter_llm import (
|
||||
create_openrouter_llm_client,
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Test create_openrouter_llm_client
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateOpenRouterLLMClient:
|
||||
"""Test create_openrouter_llm_client factory function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(self):
|
||||
"""Create a mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.openrouter_api_key = "sk-or-test-key"
|
||||
config.openrouter_llm_model = "anthropic/claude-sonnet-4"
|
||||
config.openrouter_base_url = "https://openrouter.ai/api/v1"
|
||||
return config
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_openrouter_llm_client_success(self, mock_config):
|
||||
"""Test create_openrouter_llm_client returns client with valid config."""
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"graphiti_core.llm_client.openai_client.OpenAIClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
result = create_openrouter_llm_client(mock_config)
|
||||
assert result == mock_client
|
||||
|
||||
def test_create_openrouter_llm_client_missing_api_key(self, mock_config):
|
||||
"""Test create_openrouter_llm_client raises ProviderError for missing API key."""
|
||||
mock_config.openrouter_api_key = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_openrouter_llm_client(mock_config)
|
||||
|
||||
assert "OPENROUTER_API_KEY" in str(exc_info.value)
|
||||
|
||||
def test_create_openrouter_llm_client_import_error(self, mock_config):
|
||||
"""Test create_openrouter_llm_client raises ProviderNotInstalled on ImportError."""
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
if name.startswith("graphiti_core.llm_client"):
|
||||
raise ImportError("graphiti-core not installed")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
with pytest.raises(ProviderNotInstalled) as exc_info:
|
||||
create_openrouter_llm_client(mock_config)
|
||||
|
||||
assert "graphiti-core" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_openrouter_llm_client_passes_config_correctly(self, mock_config):
|
||||
"""Test create_openrouter_llm_client passes config values correctly."""
|
||||
mock_config.openrouter_api_key = "sk-or-test-key-123"
|
||||
mock_config.openrouter_llm_model = "openai/gpt-4o"
|
||||
mock_config.openrouter_base_url = "https://custom.openrouter.ai/api/v1"
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.openrouter_llm.LLMConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.openrouter_llm.OpenAIClient",
|
||||
return_value=mock_client,
|
||||
):
|
||||
create_openrouter_llm_client(mock_config)
|
||||
|
||||
# Verify LLMConfig was called with correct arguments
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["api_key"] == "sk-or-test-key-123"
|
||||
assert call_kwargs["model"] == "openai/gpt-4o"
|
||||
assert call_kwargs["base_url"] == "https://custom.openrouter.ai/api/v1"
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_openrouter_llm_client_disables_reasoning(self, mock_config):
|
||||
"""Test create_openrouter_llm_client disables reasoning/verbosity for compatibility."""
|
||||
mock_client = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.llm_providers.openrouter_llm.OpenAIClient",
|
||||
return_value=mock_client,
|
||||
) as mock_openai_client:
|
||||
create_openrouter_llm_client(mock_config)
|
||||
|
||||
# OpenRouter should have reasoning=None, verbosity=None for compatibility
|
||||
call_kwargs = mock_openai_client.call_args.kwargs
|
||||
assert call_kwargs.get("reasoning") is None
|
||||
assert call_kwargs.get("verbosity") is None
|
||||
@@ -0,0 +1,246 @@
|
||||
"""
|
||||
Tests for integrations.graphiti.providers module.
|
||||
|
||||
Tests cover:
|
||||
- All re-exported items are accessible
|
||||
- __all__ exports match documentation
|
||||
- Module has proper docstring
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class TestProvidersModuleReExports:
|
||||
"""Test that all items are properly re-exported from graphiti_providers."""
|
||||
|
||||
def test_import_provider_error(self):
|
||||
"""Test ProviderError is re-exported."""
|
||||
from integrations.graphiti.providers import ProviderError
|
||||
|
||||
assert ProviderError is not None
|
||||
assert Exception in ProviderError.__mro__
|
||||
|
||||
def test_import_provider_not_installed(self):
|
||||
"""Test ProviderNotInstalled is re-exported."""
|
||||
from integrations.graphiti.providers import ProviderNotInstalled
|
||||
|
||||
assert ProviderNotInstalled is not None
|
||||
assert Exception in ProviderNotInstalled.__mro__
|
||||
|
||||
def test_import_create_llm_client(self):
|
||||
"""Test create_llm_client is re-exported."""
|
||||
from integrations.graphiti.providers import create_llm_client
|
||||
|
||||
assert create_llm_client is not None
|
||||
assert callable(create_llm_client)
|
||||
|
||||
def test_import_create_embedder(self):
|
||||
"""Test create_embedder is re-exported."""
|
||||
from integrations.graphiti.providers import create_embedder
|
||||
|
||||
assert create_embedder is not None
|
||||
assert callable(create_embedder)
|
||||
|
||||
def test_import_create_cross_encoder(self):
|
||||
"""Test create_cross_encoder is re-exported."""
|
||||
from integrations.graphiti.providers import create_cross_encoder
|
||||
|
||||
assert create_cross_encoder is not None
|
||||
assert callable(create_cross_encoder)
|
||||
|
||||
def test_import_embedding_dimensions(self):
|
||||
"""Test EMBEDDING_DIMENSIONS is re-exported."""
|
||||
from integrations.graphiti.providers import EMBEDDING_DIMENSIONS
|
||||
|
||||
assert EMBEDDING_DIMENSIONS is not None
|
||||
assert isinstance(EMBEDDING_DIMENSIONS, dict)
|
||||
|
||||
def test_import_get_expected_embedding_dim(self):
|
||||
"""Test get_expected_embedding_dim is re-exported."""
|
||||
from integrations.graphiti.providers import get_expected_embedding_dim
|
||||
|
||||
assert get_expected_embedding_dim is not None
|
||||
assert callable(get_expected_embedding_dim)
|
||||
|
||||
def test_import_validate_embedding_config(self):
|
||||
"""Test validate_embedding_config is re-exported."""
|
||||
from integrations.graphiti.providers import validate_embedding_config
|
||||
|
||||
assert validate_embedding_config is not None
|
||||
assert callable(validate_embedding_config)
|
||||
|
||||
def test_import_test_llm_connection(self):
|
||||
"""Test test_llm_connection is re-exported."""
|
||||
from integrations.graphiti.providers import test_llm_connection
|
||||
|
||||
assert test_llm_connection is not None
|
||||
assert callable(test_llm_connection)
|
||||
|
||||
def test_import_test_embedder_connection(self):
|
||||
"""Test test_embedder_connection is re-exported."""
|
||||
from integrations.graphiti.providers import test_embedder_connection
|
||||
|
||||
assert test_embedder_connection is not None
|
||||
assert callable(test_embedder_connection)
|
||||
|
||||
def test_import_test_ollama_connection(self):
|
||||
"""Test test_ollama_connection is re-exported."""
|
||||
from integrations.graphiti.providers import test_ollama_connection
|
||||
|
||||
assert test_ollama_connection is not None
|
||||
assert callable(test_ollama_connection)
|
||||
|
||||
def test_import_is_graphiti_enabled(self):
|
||||
"""Test is_graphiti_enabled is re-exported."""
|
||||
from integrations.graphiti.providers import is_graphiti_enabled
|
||||
|
||||
assert is_graphiti_enabled is not None
|
||||
assert callable(is_graphiti_enabled)
|
||||
|
||||
def test_import_get_graph_hints(self):
|
||||
"""Test get_graph_hints is re-exported."""
|
||||
from integrations.graphiti.providers import get_graph_hints
|
||||
|
||||
assert get_graph_hints is not None
|
||||
assert callable(get_graph_hints)
|
||||
|
||||
|
||||
class TestProvidersModuleAll:
|
||||
"""Test __all__ exports match documented exports."""
|
||||
|
||||
def test___all___contains_all_exports(self):
|
||||
"""Test __all__ contains all expected exports."""
|
||||
import integrations.graphiti.providers as providers_module
|
||||
|
||||
expected_all = [
|
||||
# Exceptions
|
||||
"ProviderError",
|
||||
"ProviderNotInstalled",
|
||||
# Factory functions
|
||||
"create_llm_client",
|
||||
"create_embedder",
|
||||
"create_cross_encoder",
|
||||
# Models
|
||||
"EMBEDDING_DIMENSIONS",
|
||||
"get_expected_embedding_dim",
|
||||
# Validators
|
||||
"validate_embedding_config",
|
||||
"test_llm_connection",
|
||||
"test_embedder_connection",
|
||||
"test_ollama_connection",
|
||||
# Utilities
|
||||
"is_graphiti_enabled",
|
||||
"get_graph_hints",
|
||||
]
|
||||
|
||||
assert providers_module.__all__ == expected_all
|
||||
|
||||
def test_import_star_includes_all_exports(self):
|
||||
"""Test 'from integrations.graphiti.providers import *' works."""
|
||||
namespace = {}
|
||||
exec("from integrations.graphiti.providers import *", namespace)
|
||||
|
||||
# Verify all __all__ items are in the namespace
|
||||
import integrations.graphiti.providers as providers_module
|
||||
|
||||
for item in providers_module.__all__:
|
||||
assert item in namespace, f"{item} not found in namespace"
|
||||
|
||||
def test_all_exports_are_accessible(self):
|
||||
"""Test all items in __all__ are accessible."""
|
||||
import integrations.graphiti.providers as providers_module
|
||||
|
||||
for item in providers_module.__all__:
|
||||
assert hasattr(providers_module, item), f"{item} not accessible"
|
||||
|
||||
|
||||
class TestProvidersModuleDocumentation:
|
||||
"""Test module documentation."""
|
||||
|
||||
def test_module_has_docstring(self):
|
||||
"""Test the module has a docstring."""
|
||||
import integrations.graphiti.providers as providers_module
|
||||
|
||||
assert providers_module.__doc__ is not None
|
||||
assert len(providers_module.__doc__) > 0
|
||||
|
||||
def test_docstring_contains_key_terms(self):
|
||||
"""Test the docstring contains key terms."""
|
||||
import integrations.graphiti.providers as providers_module
|
||||
|
||||
docstring = providers_module.__doc__.lower()
|
||||
assert "provider" in docstring
|
||||
assert "graphiti" in docstring
|
||||
|
||||
|
||||
class TestProvidersModuleReExportBehavior:
|
||||
"""Test re-export behavior matches the source module."""
|
||||
|
||||
def test_create_llm_client_matches_source(self):
|
||||
"""Test create_llm_client is the same as the source."""
|
||||
from graphiti_providers import create_llm_client as source
|
||||
from integrations.graphiti.providers import create_llm_client as re_export
|
||||
|
||||
assert re_export is source
|
||||
|
||||
def test_create_embedder_matches_source(self):
|
||||
"""Test create_embedder is the same as the source."""
|
||||
from graphiti_providers import create_embedder as source
|
||||
from integrations.graphiti.providers import create_embedder as re_export
|
||||
|
||||
assert re_export is source
|
||||
|
||||
def test_exceptions_match_source(self):
|
||||
"""Test exceptions are the same as the source."""
|
||||
from graphiti_providers import ProviderError as source_error
|
||||
from graphiti_providers import ProviderNotInstalled as source_not_installed
|
||||
from integrations.graphiti.providers import (
|
||||
ProviderError as re_export_error,
|
||||
)
|
||||
from integrations.graphiti.providers import (
|
||||
ProviderNotInstalled as re_export_not_installed,
|
||||
)
|
||||
|
||||
assert re_export_error is source_error
|
||||
assert re_export_not_installed is source_not_installed
|
||||
|
||||
def test_embedding_dimensions_matches_source(self):
|
||||
"""Test EMBEDDING_DIMENSIONS is the same as the source."""
|
||||
from graphiti_providers import EMBEDDING_DIMENSIONS as source
|
||||
from integrations.graphiti.providers import EMBEDDING_DIMENSIONS as re_export
|
||||
|
||||
assert re_export is source
|
||||
|
||||
|
||||
class TestProvidersModuleIntegration:
|
||||
"""Integration tests for the providers module."""
|
||||
|
||||
def test_module_can_be_imported_multiple_times(self):
|
||||
"""Test the module can be imported multiple times without issues."""
|
||||
import importlib
|
||||
|
||||
import integrations.graphiti.providers
|
||||
|
||||
importlib.reload(integrations.graphiti.providers)
|
||||
|
||||
# Should still work
|
||||
from integrations.graphiti.providers import create_llm_client
|
||||
|
||||
assert create_llm_client is not None
|
||||
|
||||
def test_concurrent_imports(self):
|
||||
"""Test concurrent imports don't cause issues."""
|
||||
import concurrent.futures
|
||||
|
||||
def import_module():
|
||||
from integrations.graphiti.providers import create_llm_client
|
||||
|
||||
return create_llm_client
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
||||
futures = [executor.submit(import_module) for _ in range(5)]
|
||||
results = [f.result() for f in concurrent.futures.as_completed(futures)]
|
||||
|
||||
# All should succeed
|
||||
assert len(results) == 5
|
||||
assert all(r is not None for r in results)
|
||||
@@ -0,0 +1,285 @@
|
||||
"""
|
||||
Unit tests for Ollama embedder provider.
|
||||
|
||||
Tests cover:
|
||||
- get_embedding_dim_for_model helper function
|
||||
- create_ollama_embedder factory function
|
||||
- ProviderNotInstalled exception handling
|
||||
- ProviderError for missing configuration
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.providers_pkg.embedder_providers.ollama_embedder import (
|
||||
KNOWN_OLLAMA_EMBEDDING_MODELS,
|
||||
create_ollama_embedder,
|
||||
get_embedding_dim_for_model,
|
||||
)
|
||||
from integrations.graphiti.providers_pkg.exceptions import (
|
||||
ProviderError,
|
||||
ProviderNotInstalled,
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Test get_embedding_dim_for_model
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestGetEmbeddingDimForModel:
|
||||
"""Test get_embedding_dim_for_model helper function."""
|
||||
|
||||
def test_get_embedding_dim_for_model_exact_match(self):
|
||||
"""Test get_embedding_dim_for_model with exact model match."""
|
||||
result = get_embedding_dim_for_model("nomic-embed-text")
|
||||
assert result == 768
|
||||
|
||||
def test_get_embedding_dim_for_model_with_tag(self):
|
||||
"""Test get_embedding_dim_for_model with tagged model."""
|
||||
result = get_embedding_dim_for_model("qwen3-embedding:8b")
|
||||
assert result == 4096
|
||||
|
||||
def test_get_embedding_dim_for_model_base_name_fallback(self):
|
||||
"""Test get_embedding_dim_for_model falls back to base name."""
|
||||
result = get_embedding_dim_for_model("nomic-embed-text:custom-tag")
|
||||
assert result == 768 # Should use base model dimension
|
||||
|
||||
def test_get_embedding_dim_for_model_configured_dim_override(self):
|
||||
"""Test get_embedding_dim_for_model with configured dimension override."""
|
||||
result = get_embedding_dim_for_model("unknown-model", configured_dim=512)
|
||||
assert result == 512
|
||||
|
||||
def test_get_embedding_dim_for_model_unknown_model(self):
|
||||
"""Test get_embedding_dim_for_model raises ProviderError for unknown model."""
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
get_embedding_dim_for_model("totally-unknown-model")
|
||||
|
||||
assert "Unknown Ollama embedding model" in str(exc_info.value)
|
||||
assert "totally-unknown-model" in str(exc_info.value)
|
||||
assert "OLLAMA_EMBEDDING_DIM" in str(exc_info.value)
|
||||
|
||||
def test_get_embedding_dim_for_model_configured_dim_zero(self):
|
||||
"""Test get_embedding_dim_for_model ignores zero configured dimension."""
|
||||
# When configured_dim is 0, should use known model dimension
|
||||
result = get_embedding_dim_for_model("nomic-embed-text", configured_dim=0)
|
||||
assert result == 768
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test KNOWN_OLLAMA_EMBEDDING_MODELS constant
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestKnownOllamaEmbeddingModels:
|
||||
"""Test KNOWN_OLLAMA_EMBEDDING_MODELS constant."""
|
||||
|
||||
def test_known_models_contains_expected_entries(self):
|
||||
"""Test KNOWN_OLLAMA_EMBEDDING_MODELS has expected models."""
|
||||
expected_models = [
|
||||
"embeddinggemma",
|
||||
"qwen3-embedding",
|
||||
"nomic-embed-text",
|
||||
"mxbai-embed-large",
|
||||
"bge-large",
|
||||
"all-minilm",
|
||||
]
|
||||
|
||||
for model in expected_models:
|
||||
# Check if base model exists (without tag)
|
||||
base_found = any(
|
||||
key.startswith(model) for key in KNOWN_OLLAMA_EMBEDDING_MODELS.keys()
|
||||
)
|
||||
assert base_found, (
|
||||
f"Model {model} not found in KNOWN_OLLAMA_EMBEDDING_MODELS"
|
||||
)
|
||||
|
||||
def test_known_models_dimensions_are_positive(self):
|
||||
"""Test all dimensions in KNOWN_OLLAMA_EMBEDDING_MODELS are positive integers."""
|
||||
for model, dimension in KNOWN_OLLAMA_EMBEDDING_MODELS.items():
|
||||
assert isinstance(dimension, int), f"Dimension for {model} is not int"
|
||||
assert dimension > 0, f"Dimension for {model} is not positive: {dimension}"
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test create_ollama_embedder
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateOllamaEmbedder:
|
||||
"""Test create_ollama_embedder factory function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(self):
|
||||
"""Create a mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.ollama_embedding_model = "nomic-embed-text"
|
||||
config.ollama_embedding_dim = None
|
||||
config.ollama_base_url = "http://localhost:11434"
|
||||
return config
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_ollama_embedder_success(self, mock_config):
|
||||
"""Test create_ollama_embedder returns embedder with valid config."""
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.ollama_embedder.OpenAIEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
result = create_ollama_embedder(mock_config)
|
||||
assert result == mock_embedder
|
||||
|
||||
def test_create_ollama_embedder_success_fast(self, mock_config):
|
||||
"""Fast test for create_ollama_embedder success path."""
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
# Set embedding_dim to 0 to allow auto-detection
|
||||
mock_config.ollama_embedding_dim = 0
|
||||
|
||||
# Mock the graphiti_core imports
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.embedder": MagicMock(),
|
||||
"graphiti_core.embedder.openai": MagicMock(),
|
||||
},
|
||||
):
|
||||
from graphiti_core.embedder.openai import OpenAIEmbedder
|
||||
|
||||
OpenAIEmbedder.return_value = mock_embedder
|
||||
|
||||
result = create_ollama_embedder(mock_config)
|
||||
|
||||
# Verify the embedder was created and returned
|
||||
OpenAIEmbedder.assert_called_once()
|
||||
assert result == mock_embedder
|
||||
|
||||
def test_create_ollama_embedder_missing_model(self, mock_config):
|
||||
"""Test create_ollama_embedder raises ProviderError for missing model."""
|
||||
mock_config.ollama_embedding_model = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_ollama_embedder(mock_config)
|
||||
|
||||
assert "OLLAMA_EMBEDDING_MODEL" in str(exc_info.value)
|
||||
|
||||
def test_create_ollama_embedder_import_error(self, mock_config):
|
||||
"""Test create_ollama_embedder raises ProviderNotInstalled on ImportError."""
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
# Only block the specific import that create_ollama_embedder uses
|
||||
if name == "graphiti_core.embedder.openai" or name.startswith(
|
||||
"graphiti_core.embedder.openai."
|
||||
):
|
||||
raise ImportError("graphiti-core not installed")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
with pytest.raises(ProviderNotInstalled) as exc_info:
|
||||
create_ollama_embedder(mock_config)
|
||||
|
||||
assert "graphiti-core" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_ollama_embedder_base_url_without_v1(self, mock_config):
|
||||
"""Test create_ollama_embedder appends /v1 to base URL if missing."""
|
||||
mock_config.ollama_base_url = "http://localhost:11434"
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.ollama_embedder.OpenAIEmbedderConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.ollama_embedder.OpenAIEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
create_ollama_embedder(mock_config)
|
||||
|
||||
# Verify base_url has /v1 appended
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["base_url"] == "http://localhost:11434/v1"
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_ollama_embedder_base_url_with_v1(self, mock_config):
|
||||
"""Test create_ollama_embedder doesn't duplicate /v1 in base URL."""
|
||||
mock_config.ollama_base_url = "http://localhost:11434/v1"
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.ollama_embedder.OpenAIEmbedderConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.ollama_embedder.OpenAIEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
create_ollama_embedder(mock_config)
|
||||
|
||||
# Verify base_url is not duplicated
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["base_url"] == "http://localhost:11434/v1"
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_ollama_embedder_base_url_with_trailing_slash(self, mock_config):
|
||||
"""Test create_ollama_embedder handles trailing slash correctly."""
|
||||
mock_config.ollama_base_url = "http://localhost:11434/"
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.ollama_embedder.OpenAIEmbedderConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.ollama_embedder.OpenAIEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
create_ollama_embedder(mock_config)
|
||||
|
||||
# Verify trailing slash is handled
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["base_url"] == "http://localhost:11434/v1"
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_ollama_embedder_passes_config_correctly(self, mock_config):
|
||||
"""Test create_ollama_embedder passes config values correctly."""
|
||||
mock_config.ollama_embedding_model = "mxbai-embed-large"
|
||||
mock_config.ollama_embedding_dim = None
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.ollama_embedder.OpenAIEmbedderConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.ollama_embedder.OpenAIEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
create_ollama_embedder(mock_config)
|
||||
|
||||
# Verify OpenAIEmbedderConfig was called with correct arguments
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["api_key"] == "ollama"
|
||||
assert call_kwargs["embedding_model"] == "mxbai-embed-large"
|
||||
assert (
|
||||
call_kwargs["embedding_dim"] == 1024
|
||||
) # Known dimension for mxbai-embed-large
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_ollama_embedder_with_configured_dimension(self, mock_config):
|
||||
"""Test create_ollama_embedder uses configured dimension when set."""
|
||||
mock_config.ollama_embedding_dim = 512
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.ollama_embedder.OpenAIEmbedderConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.ollama_embedder.OpenAIEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
create_ollama_embedder(mock_config)
|
||||
|
||||
# Verify configured dimension is used
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["embedding_dim"] == 512
|
||||
@@ -0,0 +1,117 @@
|
||||
"""
|
||||
Unit tests for OpenAI embedder provider.
|
||||
|
||||
Tests cover:
|
||||
- create_openai_embedder factory function
|
||||
- ProviderNotInstalled exception handling
|
||||
- ProviderError for missing configuration
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.providers_pkg.embedder_providers.openai_embedder import (
|
||||
create_openai_embedder,
|
||||
)
|
||||
from integrations.graphiti.providers_pkg.exceptions import (
|
||||
ProviderError,
|
||||
ProviderNotInstalled,
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Test create_openai_embedder
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateOpenAIEmbedder:
|
||||
"""Test create_openai_embedder factory function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(self):
|
||||
"""Create a mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.openai_api_key = "sk-test-key"
|
||||
config.openai_embedding_model = "text-embedding-3-small"
|
||||
return config
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_openai_embedder_success(self, mock_config):
|
||||
"""Test create_openai_embedder returns embedder with valid config."""
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.openai_embedder.OpenAIEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
result = create_openai_embedder(mock_config)
|
||||
assert result == mock_embedder
|
||||
|
||||
def test_create_openai_embedder_success_fast(self, mock_config):
|
||||
"""Fast test for create_openai_embedder success path."""
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
# Mock the graphiti_core imports
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.embedder": MagicMock(),
|
||||
"graphiti_core.embedder.openai": MagicMock(),
|
||||
},
|
||||
):
|
||||
from graphiti_core.embedder.openai import OpenAIEmbedder
|
||||
|
||||
OpenAIEmbedder.return_value = mock_embedder
|
||||
|
||||
result = create_openai_embedder(mock_config)
|
||||
|
||||
# Verify the embedder was created and returned
|
||||
OpenAIEmbedder.assert_called_once()
|
||||
assert result == mock_embedder
|
||||
|
||||
def test_create_openai_embedder_missing_api_key(self, mock_config):
|
||||
"""Test create_openai_embedder raises ProviderError for missing API key."""
|
||||
mock_config.openai_api_key = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_openai_embedder(mock_config)
|
||||
|
||||
assert "OPENAI_API_KEY" in str(exc_info.value)
|
||||
|
||||
def test_create_openai_embedder_import_error(self, mock_config):
|
||||
"""Test create_openai_embedder raises ProviderNotInstalled on ImportError."""
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
if name.startswith("graphiti_core.embedder"):
|
||||
raise ImportError("graphiti-core not installed")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
with pytest.raises(ProviderNotInstalled) as exc_info:
|
||||
create_openai_embedder(mock_config)
|
||||
|
||||
assert "graphiti-core" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_openai_embedder_passes_config_correctly(self, mock_config):
|
||||
"""Test create_openai_embedder passes config values correctly."""
|
||||
mock_config.openai_api_key = "sk-test-key-123"
|
||||
mock_config.openai_embedding_model = "text-embedding-3-large"
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.openai_embedder.OpenAIEmbedderConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.openai_embedder.OpenAIEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
create_openai_embedder(mock_config)
|
||||
|
||||
# Verify OpenAIEmbedderConfig was called with correct arguments
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["api_key"] == "sk-test-key-123"
|
||||
assert call_kwargs["embedding_model"] == "text-embedding-3-large"
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
Unit tests for OpenRouter embedder provider.
|
||||
|
||||
Tests cover:
|
||||
- create_openrouter_embedder factory function
|
||||
- ProviderNotInstalled exception handling
|
||||
- ProviderError for missing configuration
|
||||
"""
|
||||
|
||||
import sys
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.providers_pkg.embedder_providers.openrouter_embedder import (
|
||||
create_openrouter_embedder,
|
||||
)
|
||||
from integrations.graphiti.providers_pkg.exceptions import (
|
||||
ProviderError,
|
||||
ProviderNotInstalled,
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Test create_openrouter_embedder
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateOpenRouterEmbedder:
|
||||
"""Test create_openrouter_embedder factory function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(self):
|
||||
"""Create a mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.openrouter_api_key = "sk-or-test-key"
|
||||
config.openrouter_embedding_model = "openai/text-embedding-3-small"
|
||||
config.openrouter_base_url = "https://openrouter.ai/api/v1"
|
||||
return config
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_openrouter_embedder_success(self, mock_config):
|
||||
"""Test create_openrouter_embedder returns embedder with valid config."""
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.openrouter_embedder.OpenAIEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
result = create_openrouter_embedder(mock_config)
|
||||
assert result == mock_embedder
|
||||
|
||||
def test_create_openrouter_embedder_success_fast(self, mock_config):
|
||||
"""Fast test for create_openrouter_embedder success path."""
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
# Mock the graphiti_core imports
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.embedder": MagicMock(),
|
||||
},
|
||||
):
|
||||
from graphiti_core.embedder import OpenAIEmbedder
|
||||
|
||||
OpenAIEmbedder.return_value = mock_embedder
|
||||
|
||||
result = create_openrouter_embedder(mock_config)
|
||||
|
||||
# Verify the embedder was created and returned
|
||||
OpenAIEmbedder.assert_called_once()
|
||||
assert result == mock_embedder
|
||||
|
||||
def test_create_openrouter_embedder_missing_api_key(self, mock_config):
|
||||
"""Test create_openrouter_embedder raises ProviderError for missing API key."""
|
||||
|
||||
mock_graphiti_core_embedder = MagicMock()
|
||||
mock_graphiti_core_embedder.EmbedderConfig = MagicMock
|
||||
mock_graphiti_core_embedder.OpenAIEmbedder = MagicMock
|
||||
|
||||
# Mock the graphiti_core.embedder module to allow import to succeed
|
||||
with patch.dict(
|
||||
sys.modules, {"graphiti_core.embedder": mock_graphiti_core_embedder}
|
||||
):
|
||||
mock_config.openrouter_api_key = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_openrouter_embedder(mock_config)
|
||||
|
||||
assert "OPENROUTER_API_KEY" in str(exc_info.value)
|
||||
|
||||
def test_create_openrouter_embedder_import_error(self, mock_config):
|
||||
"""Test create_openrouter_embedder raises ProviderNotInstalled on ImportError."""
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
if name.startswith("graphiti_core.embedder"):
|
||||
raise ImportError("graphiti-core not installed")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
with pytest.raises(ProviderNotInstalled) as exc_info:
|
||||
create_openrouter_embedder(mock_config)
|
||||
|
||||
assert "graphiti-core" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_openrouter_embedder_passes_config_correctly(self, mock_config):
|
||||
"""Test create_openrouter_embedder passes config values correctly."""
|
||||
mock_config.openrouter_api_key = "sk-or-test-key-123"
|
||||
mock_config.openrouter_embedding_model = "voyage/voyage-3"
|
||||
mock_config.openrouter_base_url = "https://custom.openrouter.ai/api/v1"
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.openrouter_embedder.EmbedderConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"integrations.graphiti.providers_pkg.embedder_providers.openrouter_embedder.OpenAIEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
create_openrouter_embedder(mock_config)
|
||||
|
||||
# Verify EmbedderConfig was called with correct arguments
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["api_key"] == "sk-or-test-key-123"
|
||||
assert call_kwargs["model"] == "voyage/voyage-3"
|
||||
assert call_kwargs["base_url"] == "https://custom.openrouter.ai/api/v1"
|
||||
@@ -0,0 +1,128 @@
|
||||
"""
|
||||
Unit tests for Voyage AI embedder provider.
|
||||
|
||||
Tests cover:
|
||||
- create_voyage_embedder factory function
|
||||
- ProviderNotInstalled exception handling
|
||||
- ProviderError for missing configuration
|
||||
"""
|
||||
|
||||
import sys
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.providers_pkg.embedder_providers.voyage_embedder import (
|
||||
create_voyage_embedder,
|
||||
)
|
||||
from integrations.graphiti.providers_pkg.exceptions import (
|
||||
ProviderError,
|
||||
ProviderNotInstalled,
|
||||
)
|
||||
|
||||
# =============================================================================
|
||||
# Test create_voyage_embedder
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestCreateVoyageEmbedder:
|
||||
"""Test create_voyage_embedder factory function."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(self):
|
||||
"""Create a mock GraphitiConfig."""
|
||||
config = MagicMock()
|
||||
config.voyage_api_key = "test-voyage-key"
|
||||
config.voyage_embedding_model = "voyage-3"
|
||||
return config
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_voyage_embedder_success(self, mock_config):
|
||||
"""Test create_voyage_embedder returns embedder with valid config."""
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"graphiti_core.embedder.voyage.VoyageEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
result = create_voyage_embedder(mock_config)
|
||||
assert result == mock_embedder
|
||||
|
||||
def test_create_voyage_embedder_success_fast(self, mock_config):
|
||||
"""Fast test for create_voyage_embedder success path."""
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
# Mock the graphiti_core imports
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"graphiti_core": MagicMock(),
|
||||
"graphiti_core.embedder": MagicMock(),
|
||||
"graphiti_core.embedder.voyage": MagicMock(),
|
||||
},
|
||||
):
|
||||
from graphiti_core.embedder.voyage import VoyageEmbedder
|
||||
|
||||
VoyageEmbedder.return_value = mock_embedder
|
||||
|
||||
result = create_voyage_embedder(mock_config)
|
||||
|
||||
# Verify the embedder was created and returned
|
||||
VoyageEmbedder.assert_called_once()
|
||||
assert result == mock_embedder
|
||||
|
||||
def test_create_voyage_embedder_missing_api_key(self, mock_config):
|
||||
"""Test create_voyage_embedder raises ProviderError for missing API key."""
|
||||
|
||||
mock_voyage = MagicMock()
|
||||
mock_voyage.VoyageAIConfig = MagicMock()
|
||||
mock_voyage.VoyageEmbedder = MagicMock()
|
||||
|
||||
# Clear sys.modules cache to ensure fresh import
|
||||
sys.modules.pop("graphiti_core.embedder.voyage", None)
|
||||
|
||||
# Mock the voyage module to allow import to succeed
|
||||
with patch.dict(sys.modules, {"graphiti_core.embedder.voyage": mock_voyage}):
|
||||
mock_config.voyage_api_key = None
|
||||
|
||||
with pytest.raises(ProviderError) as exc_info:
|
||||
create_voyage_embedder(mock_config)
|
||||
|
||||
assert "VOYAGE_API_KEY" in str(exc_info.value)
|
||||
|
||||
def test_create_voyage_embedder_import_error(self, mock_config):
|
||||
"""Test create_voyage_embedder raises ProviderNotInstalled on ImportError."""
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
if name.startswith("graphiti_core.embedder.voyage"):
|
||||
raise ImportError("graphiti-core[voyage] not installed")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
with pytest.raises(ProviderNotInstalled) as exc_info:
|
||||
create_voyage_embedder(mock_config)
|
||||
|
||||
assert "graphiti-core[voyage]" in str(exc_info.value)
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_create_voyage_embedder_passes_config_correctly(self, mock_config):
|
||||
"""Test create_voyage_embedder passes config values correctly."""
|
||||
mock_config.voyage_api_key = "test-voyage-key-123"
|
||||
mock_config.voyage_embedding_model = "voyage-3-lite"
|
||||
mock_embedder = MagicMock()
|
||||
|
||||
with patch(
|
||||
"graphiti_core.embedder.voyage.VoyageAIConfig",
|
||||
) as mock_config_class:
|
||||
with patch(
|
||||
"graphiti_core.embedder.voyage.VoyageEmbedder",
|
||||
return_value=mock_embedder,
|
||||
):
|
||||
create_voyage_embedder(mock_config)
|
||||
|
||||
# Verify VoyageAIConfig was called with correct arguments
|
||||
call_kwargs = mock_config_class.call_args.kwargs
|
||||
assert call_kwargs["api_key"] == "test-voyage-key-123"
|
||||
assert call_kwargs["embedding_model"] == "voyage-3-lite"
|
||||
@@ -0,0 +1,783 @@
|
||||
"""
|
||||
Tests for GraphitiQueries class.
|
||||
|
||||
Tests cover:
|
||||
- GraphitiQueries initialization
|
||||
- add_session_insight()
|
||||
- add_codebase_discoveries()
|
||||
- add_pattern()
|
||||
- add_gotcha()
|
||||
- add_task_outcome()
|
||||
- add_structured_insights()
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
# =============================================================================
|
||||
# Mock External Dependencies
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_graphiti_core_nodes():
|
||||
"""Auto-mock graphiti_core for all tests."""
|
||||
import sys
|
||||
|
||||
# Patch graphiti_core at module level before import
|
||||
mock_graphiti_core = MagicMock()
|
||||
mock_nodes = MagicMock()
|
||||
mock_episode_type = MagicMock()
|
||||
mock_episode_type.text = "text"
|
||||
mock_nodes.EpisodeType = mock_episode_type
|
||||
mock_graphiti_core.nodes = mock_nodes
|
||||
|
||||
sys.modules["graphiti_core"] = mock_graphiti_core
|
||||
sys.modules["graphiti_core.nodes"] = mock_nodes
|
||||
|
||||
try:
|
||||
yield mock_episode_type
|
||||
finally:
|
||||
# Clean up - always run even if test fails
|
||||
sys.modules.pop("graphiti_core", None)
|
||||
sys.modules.pop("graphiti_core.nodes", None)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Client and Queries Fixtures
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_client():
|
||||
"""Create a mock GraphitiClient."""
|
||||
client = MagicMock()
|
||||
client.graphiti = MagicMock()
|
||||
client.graphiti.add_episode = AsyncMock()
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def queries(mock_client):
|
||||
"""Create a GraphitiQueries instance."""
|
||||
from integrations.graphiti.queries_pkg.queries import GraphitiQueries
|
||||
|
||||
return GraphitiQueries(
|
||||
client=mock_client,
|
||||
group_id="test_group",
|
||||
spec_context_id="test_spec",
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Test Classes
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class TestGraphitiQueriesInit:
|
||||
"""Test GraphitiQueries initialization."""
|
||||
|
||||
def test_init_sets_attributes(self, mock_client):
|
||||
"""Test constructor sets all attributes correctly."""
|
||||
from integrations.graphiti.queries_pkg.queries import GraphitiQueries
|
||||
|
||||
queries = GraphitiQueries(
|
||||
client=mock_client,
|
||||
group_id="my_group",
|
||||
spec_context_id="my_spec",
|
||||
)
|
||||
|
||||
assert queries.client == mock_client
|
||||
assert queries.group_id == "my_group"
|
||||
assert queries.spec_context_id == "my_spec"
|
||||
|
||||
|
||||
class TestAddSessionInsight:
|
||||
"""Test add_session_insight method."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_session_insight_success(self, queries):
|
||||
"""Test successful session insight save."""
|
||||
insights = {
|
||||
"subtasks_completed": ["task-1", "task-2"],
|
||||
"discoveries": {"files_understood": {}},
|
||||
"what_worked": ["Using pytest"],
|
||||
"what_failed": [],
|
||||
}
|
||||
|
||||
result = await queries.add_session_insight(session_num=1, insights=insights)
|
||||
|
||||
assert result is True
|
||||
queries.client.graphiti.add_episode.assert_called_once()
|
||||
|
||||
# Verify episode format
|
||||
call_args = queries.client.graphiti.add_episode.call_args
|
||||
assert "session_001_test_spec" in call_args[1]["name"]
|
||||
|
||||
episode_body = json.loads(call_args[1]["episode_body"])
|
||||
assert episode_body["type"] == "session_insight"
|
||||
assert episode_body["session_number"] == 1
|
||||
assert episode_body["spec_id"] == "test_spec"
|
||||
assert "subtasks_completed" in episode_body
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_session_insight_exception(self, queries):
|
||||
"""Test exception handling in add_session_insight."""
|
||||
queries.client.graphiti.add_episode.side_effect = Exception("Database error")
|
||||
|
||||
result = await queries.add_session_insight(session_num=1, insights={})
|
||||
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestAddCodebaseDiscoveries:
|
||||
"""Test add_codebase_discoveries method."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_codebase_discoveries_empty_dict(self, queries):
|
||||
"""Test empty discoveries returns True without calling add_episode."""
|
||||
result = await queries.add_codebase_discoveries({})
|
||||
|
||||
assert result is True
|
||||
queries.client.graphiti.add_episode.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_codebase_discoveries_success(self, queries):
|
||||
"""Test successful codebase discoveries save."""
|
||||
discoveries = {
|
||||
"src/main.py": "Entry point for the application",
|
||||
"src/config.py": "Configuration module",
|
||||
}
|
||||
|
||||
result = await queries.add_codebase_discoveries(discoveries)
|
||||
|
||||
assert result is True
|
||||
queries.client.graphiti.add_episode.assert_called_once()
|
||||
|
||||
call_args = queries.client.graphiti.add_episode.call_args
|
||||
episode_body = json.loads(call_args[1]["episode_body"])
|
||||
assert episode_body["type"] == "codebase_discovery"
|
||||
assert episode_body["files"] == discoveries
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_codebase_discoveries_exception(self, queries):
|
||||
"""Test exception handling in add_codebase_discoveries."""
|
||||
queries.client.graphiti.add_episode.side_effect = Exception("Database error")
|
||||
|
||||
result = await queries.add_codebase_discoveries({"file.py": "desc"})
|
||||
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestAddPattern:
|
||||
"""Test add_pattern method."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_pattern_success(self, queries):
|
||||
"""Test successful pattern save."""
|
||||
pattern = "Use dependency injection for database connections"
|
||||
|
||||
result = await queries.add_pattern(pattern)
|
||||
|
||||
assert result is True
|
||||
queries.client.graphiti.add_episode.assert_called_once()
|
||||
|
||||
call_args = queries.client.graphiti.add_episode.call_args
|
||||
episode_body = json.loads(call_args[1]["episode_body"])
|
||||
assert episode_body["type"] == "pattern"
|
||||
assert episode_body["pattern"] == pattern
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_pattern_exception(self, queries):
|
||||
"""Test exception handling in add_pattern."""
|
||||
queries.client.graphiti.add_episode.side_effect = Exception("Database error")
|
||||
|
||||
result = await queries.add_pattern("test pattern")
|
||||
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestAddGotcha:
|
||||
"""Test add_gotcha method."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_gotcha_success(self, queries):
|
||||
"""Test successful gotcha save."""
|
||||
gotcha = "Always close database connections in finally blocks"
|
||||
|
||||
result = await queries.add_gotcha(gotcha)
|
||||
|
||||
assert result is True
|
||||
queries.client.graphiti.add_episode.assert_called_once()
|
||||
|
||||
call_args = queries.client.graphiti.add_episode.call_args
|
||||
episode_body = json.loads(call_args[1]["episode_body"])
|
||||
assert episode_body["type"] == "gotcha"
|
||||
assert episode_body["gotcha"] == gotcha
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_gotcha_exception(self, queries):
|
||||
"""Test exception handling in add_gotcha."""
|
||||
queries.client.graphiti.add_episode.side_effect = Exception("Database error")
|
||||
|
||||
result = await queries.add_gotcha("test gotcha")
|
||||
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestAddTaskOutcome:
|
||||
"""Test add_task_outcome method."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_task_outcome_success(self, queries):
|
||||
"""Test successful task outcome save."""
|
||||
result = await queries.add_task_outcome(
|
||||
task_id="task-123",
|
||||
success=True,
|
||||
outcome="Implementation completed successfully",
|
||||
metadata={"duration": 120},
|
||||
)
|
||||
|
||||
assert result is True
|
||||
queries.client.graphiti.add_episode.assert_called_once()
|
||||
|
||||
call_args = queries.client.graphiti.add_episode.call_args
|
||||
episode_body = json.loads(call_args[1]["episode_body"])
|
||||
assert episode_body["type"] == "task_outcome"
|
||||
assert episode_body["task_id"] == "task-123"
|
||||
assert episode_body["success"] is True
|
||||
assert episode_body["outcome"] == "Implementation completed successfully"
|
||||
assert episode_body["duration"] == 120
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_task_outcome_without_metadata(self, queries):
|
||||
"""Test task outcome save without metadata."""
|
||||
result = await queries.add_task_outcome(
|
||||
task_id="task-456",
|
||||
success=False,
|
||||
outcome="Failed due to timeout",
|
||||
)
|
||||
|
||||
assert result is True
|
||||
|
||||
call_args = queries.client.graphiti.add_episode.call_args
|
||||
episode_body = json.loads(call_args[1]["episode_body"])
|
||||
assert episode_body["task_id"] == "task-456"
|
||||
assert episode_body["success"] is False
|
||||
assert episode_body["outcome"] == "Failed due to timeout"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_task_outcome_exception(self, queries):
|
||||
"""Test exception handling in add_task_outcome."""
|
||||
queries.client.graphiti.add_episode.side_effect = Exception("Database error")
|
||||
|
||||
result = await queries.add_task_outcome("task-1", True, "success")
|
||||
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestAddStructuredInsights:
|
||||
"""Test add_structured_insights method."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_empty_dict(self, queries):
|
||||
"""Test empty insights returns True."""
|
||||
result = await queries.add_structured_insights({})
|
||||
|
||||
assert result is True
|
||||
queries.client.graphiti.add_episode.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_with_file_insights(self, queries):
|
||||
"""Test structured insights with file insights."""
|
||||
insights = {
|
||||
"file_insights": [
|
||||
{
|
||||
"path": "src/main.py",
|
||||
"purpose": "Entry point",
|
||||
"changes_made": "Added error handling",
|
||||
"patterns_used": ["error boundaries"],
|
||||
"gotchas": ["needs timeout"],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is True
|
||||
assert queries.client.graphiti.add_episode.call_count == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_with_patterns(self, queries):
|
||||
"""Test structured insights with discovered patterns."""
|
||||
insights = {
|
||||
"patterns_discovered": [
|
||||
{
|
||||
"pattern": "Use factory pattern for object creation",
|
||||
"applies_to": "Complex object initialization",
|
||||
"example": "src/factory.py",
|
||||
},
|
||||
"Simple pattern string", # Test non-dict pattern
|
||||
]
|
||||
}
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is True
|
||||
assert queries.client.graphiti.add_episode.call_count == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_with_gotchas(self, queries):
|
||||
"""Test structured insights with discovered gotchas."""
|
||||
insights = {
|
||||
"gotchas_discovered": [
|
||||
{
|
||||
"gotcha": "Don't use mutable default arguments",
|
||||
"trigger": "Function definition with [] as default",
|
||||
"solution": "Use None and check in function body",
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_with_outcome(self, queries):
|
||||
"""Test structured insights with approach outcome."""
|
||||
insights = {
|
||||
"subtask_id": "task-1",
|
||||
"approach_outcome": {
|
||||
"success": True,
|
||||
"approach_used": "Used Graphiti for memory",
|
||||
"why_it_worked": "Efficient semantic search",
|
||||
"alternatives_tried": ["PostgreSQL"],
|
||||
},
|
||||
"changed_files": ["src/memory.py"],
|
||||
}
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_with_recommendations(self, queries):
|
||||
"""Test structured insights with recommendations."""
|
||||
insights = {
|
||||
"subtask_id": "task-2",
|
||||
"recommendations": [
|
||||
"Add error handling",
|
||||
"Improve test coverage",
|
||||
],
|
||||
}
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_handles_duplicate_facts_error(self, queries):
|
||||
"""Test that duplicate_facts error is handled as non-fatal."""
|
||||
insights = {"file_insights": [{"path": "src/test.py", "purpose": "Test file"}]}
|
||||
|
||||
# First call fails with duplicate_facts, second succeeds
|
||||
queries.client.graphiti.add_episode.side_effect = [
|
||||
Exception("invalid duplicate_facts idx"),
|
||||
None, # Second call succeeds
|
||||
]
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_string_pattern(self, queries):
|
||||
"""Test string pattern (non-dict) handling."""
|
||||
insights = {"patterns_discovered": ["Simple string pattern"]}
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is True
|
||||
|
||||
call_args = queries.client.graphiti.add_episode.call_args
|
||||
episode_body = json.loads(call_args[1]["episode_body"])
|
||||
assert episode_body["pattern"] == "Simple string pattern"
|
||||
assert episode_body["applies_to"] == ""
|
||||
assert episode_body["example"] == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_string_gotcha(self, queries):
|
||||
"""Test string gotcha (non-dict) handling."""
|
||||
insights = {"gotchas_discovered": ["Simple string gotcha"]}
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is True
|
||||
|
||||
call_args = queries.client.graphiti.add_episode.call_args
|
||||
episode_body = json.loads(call_args[1]["episode_body"])
|
||||
assert episode_body["gotcha"] == "Simple string gotcha"
|
||||
assert episode_body["trigger"] == ""
|
||||
assert episode_body["solution"] == ""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_file_insight_with_all_fields(self, queries):
|
||||
"""Test file insight with all optional fields."""
|
||||
insights = {
|
||||
"file_insights": [
|
||||
{
|
||||
"path": "src/test.py",
|
||||
"purpose": "Test module",
|
||||
"changes_made": "Added new tests",
|
||||
"patterns_used": ["pattern1", "pattern2"],
|
||||
"gotchas": ["gotcha1", "gotcha2"],
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is True
|
||||
|
||||
call_args = queries.client.graphiti.add_episode.call_args
|
||||
episode_body = json.loads(call_args[1]["episode_body"])
|
||||
assert episode_body["file_path"] == "src/test.py"
|
||||
assert episode_body["purpose"] == "Test module"
|
||||
assert episode_body["changes_made"] == "Added new tests"
|
||||
assert episode_body["patterns_used"] == ["pattern1", "pattern2"]
|
||||
assert episode_body["gotchas"] == ["gotcha1", "gotcha2"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_gotcha_non_duplicate_exception(
|
||||
self, queries
|
||||
):
|
||||
"""Test gotcha save with non-duplicate_facts exception."""
|
||||
insights = {"gotchas_discovered": [{"gotcha": "Test gotcha"}]}
|
||||
|
||||
# Raise non-duplicate error
|
||||
queries.client.graphiti.add_episode.side_effect = Exception("Other error")
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
# Should return False since all saves failed
|
||||
assert result is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_gotcha_duplicate_facts_exception(
|
||||
self, queries
|
||||
):
|
||||
"""Test gotcha save with duplicate_facts exception (lines 418-419)."""
|
||||
insights = {"gotchas_discovered": [{"gotcha": "Test gotcha"}]}
|
||||
|
||||
# Raise duplicate_facts error (should be counted as success)
|
||||
queries.client.graphiti.add_episode.side_effect = Exception(
|
||||
"invalid duplicate_facts idx"
|
||||
)
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
# Should return True because duplicate_facts is non-fatal
|
||||
assert result is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_outcome_non_duplicate_exception(
|
||||
self, queries
|
||||
):
|
||||
"""Test outcome save with non-duplicate_facts exception."""
|
||||
insights = {
|
||||
"subtask_id": "task-1",
|
||||
"approach_outcome": {"success": True, "approach_used": "Test approach"},
|
||||
}
|
||||
|
||||
# Raise non-duplicate error
|
||||
queries.client.graphiti.add_episode.side_effect = Exception("Other error")
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
# Should return False since all saves failed
|
||||
assert result is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_outcome_duplicate_facts_exception(
|
||||
self, queries
|
||||
):
|
||||
"""Test outcome save with duplicate_facts exception (lines 457-458)."""
|
||||
insights = {
|
||||
"subtask_id": "task-1",
|
||||
"approach_outcome": {"success": True, "approach_used": "Test approach"},
|
||||
}
|
||||
|
||||
# Raise duplicate_facts error (should be counted as success)
|
||||
queries.client.graphiti.add_episode.side_effect = Exception(
|
||||
"invalid duplicate_facts idx"
|
||||
)
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
# Should return True because duplicate_facts is non-fatal
|
||||
assert result is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_recommendations_non_duplicate_exception(
|
||||
self, queries
|
||||
):
|
||||
"""Test recommendations save with non-duplicate_facts exception."""
|
||||
insights = {"subtask_id": "task-1", "recommendations": ["Test recommendation"]}
|
||||
|
||||
# Raise non-duplicate error
|
||||
queries.client.graphiti.add_episode.side_effect = Exception("Other error")
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
# Should return False since all saves failed
|
||||
assert result is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_recommendations_duplicate_facts_exception(
|
||||
self, queries
|
||||
):
|
||||
"""Test recommendations save with duplicate_facts exception (lines 488-489)."""
|
||||
insights = {"subtask_id": "task-1", "recommendations": ["Test recommendation"]}
|
||||
|
||||
# Raise duplicate_facts error (should be counted as success)
|
||||
queries.client.graphiti.add_episode.side_effect = Exception(
|
||||
"invalid duplicate_facts idx"
|
||||
)
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
# Should return True because duplicate_facts is non-fatal
|
||||
assert result is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_top_level_exception_with_content(
|
||||
self, queries
|
||||
):
|
||||
"""Test top-level exception with insights content."""
|
||||
insights = {
|
||||
"file_insights": [{"path": "test.py", "purpose": "test"}],
|
||||
"patterns_discovered": [{"pattern": "test pattern"}],
|
||||
"gotchas_discovered": [{"gotcha": "test gotcha"}],
|
||||
"approach_outcome": {"success": True},
|
||||
"recommendations": ["test recommendation"],
|
||||
}
|
||||
|
||||
# Mock exception during processing
|
||||
with patch(
|
||||
"integrations.graphiti.queries_pkg.queries.json.dumps",
|
||||
side_effect=Exception("JSON error"),
|
||||
):
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_outer_exception_handler(self, queries):
|
||||
"""Test outer exception handler for add_structured_insights (lines 499-523)."""
|
||||
insights = {
|
||||
"file_insights": [{"path": "test.py", "purpose": "test"}],
|
||||
"patterns_discovered": [{"pattern": "Test pattern"}],
|
||||
"gotchas_discovered": [{"gotcha": "Test gotcha"}],
|
||||
"approach_outcome": {"success": True, "approach_used": "Test approach"},
|
||||
"recommendations": ["Test recommendation"],
|
||||
}
|
||||
|
||||
# Mock EpisodeType import to fail, triggering outer exception handler
|
||||
import builtins
|
||||
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mock_import(name, *args, **kwargs):
|
||||
if name == "graphiti_core.nodes":
|
||||
raise ImportError("EpisodeType not available")
|
||||
return original_import(name, *args, **kwargs)
|
||||
|
||||
with patch("builtins.__import__", side_effect=mock_import):
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
# Should return False and trigger outer exception handler
|
||||
assert result is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_all_fail(self, queries):
|
||||
"""Test when all episode saves fail."""
|
||||
insights = {"file_insights": [{"path": "test.py", "purpose": "test"}]}
|
||||
|
||||
queries.client.graphiti.add_episode.side_effect = Exception("Total failure")
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is False
|
||||
|
||||
|
||||
class TestAddStructuredInsightsExceptionHandling:
|
||||
"""Test add_structured_insights exception handling branches."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"insights_key,insights_value",
|
||||
[
|
||||
("patterns_discovered", [{"pattern": "Test pattern"}]),
|
||||
("gotchas_discovered", [{"gotcha": "Test gotcha"}]),
|
||||
(
|
||||
"approach_outcome",
|
||||
{
|
||||
"subtask_id": "task-1",
|
||||
"success": True,
|
||||
"approach_used": "Test approach",
|
||||
},
|
||||
),
|
||||
(
|
||||
"recommendations",
|
||||
{"subtask_id": "task-1", "recommendations": ["Test recommendation"]},
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_add_structured_insights_non_duplicate_exception(
|
||||
self, queries, insights_key, insights_value
|
||||
):
|
||||
"""Test exception handling for non-duplicate errors across different insight types."""
|
||||
insights = {insights_key: insights_value}
|
||||
|
||||
queries.client.graphiti.add_episode.side_effect = Exception(
|
||||
"Non-duplicate error"
|
||||
)
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_top_level_exception(self, queries):
|
||||
"""Test top-level exception handling in add_structured_insights."""
|
||||
insights = {"file_insights": [{"path": "test.py", "purpose": "test"}]}
|
||||
|
||||
# Simulate exception during JSON serialization
|
||||
with patch(
|
||||
"integrations.graphiti.queries_pkg.queries.json.dumps",
|
||||
side_effect=Exception("JSON error"),
|
||||
):
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is False
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_mixed_success_failure(self, queries):
|
||||
"""Test mixed success and failure in structured insights."""
|
||||
insights = {
|
||||
"file_insights": [
|
||||
{"path": "test1.py", "purpose": "test1"},
|
||||
{"path": "test2.py", "purpose": "test2"},
|
||||
]
|
||||
}
|
||||
|
||||
# First succeeds, second fails with non-duplicate error
|
||||
queries.client.graphiti.add_episode.side_effect = [
|
||||
None, # First succeeds
|
||||
Exception("Non-duplicate error"), # Second fails
|
||||
]
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
# Should return True because at least one succeeded
|
||||
assert result is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_all_patterns_fail_with_duplicate(
|
||||
self, queries
|
||||
):
|
||||
"""Test all pattern saves fail with duplicate_facts error."""
|
||||
insights = {
|
||||
"patterns_discovered": [{"pattern": "Pattern 1"}, {"pattern": "Pattern 2"}]
|
||||
}
|
||||
|
||||
# Both fail with duplicate_facts error (should be counted as success)
|
||||
queries.client.graphiti.add_episode.side_effect = [
|
||||
Exception("invalid duplicate_facts idx"),
|
||||
Exception("invalid duplicate_facts idx"),
|
||||
]
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
# Should return True because duplicate_facts is non-fatal
|
||||
assert result is True
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_dict_pattern_with_all_fields(self, queries):
|
||||
"""Test dict pattern with applies_to and example fields."""
|
||||
insights = {
|
||||
"patterns_discovered": [
|
||||
{
|
||||
"pattern": "Factory pattern",
|
||||
"applies_to": "Object creation",
|
||||
"example": "src/factory.py",
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is True
|
||||
assert queries.client.graphiti.add_episode.call_count == 1
|
||||
|
||||
call_args = queries.client.graphiti.add_episode.call_args
|
||||
episode_body = json.loads(call_args[1]["episode_body"])
|
||||
assert episode_body["pattern"] == "Factory pattern"
|
||||
assert episode_body["applies_to"] == "Object creation"
|
||||
assert episode_body["example"] == "src/factory.py"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_dict_gotcha_with_all_fields(self, queries):
|
||||
"""Test dict gotcha with trigger and solution fields."""
|
||||
insights = {
|
||||
"gotchas_discovered": [
|
||||
{
|
||||
"gotcha": "Mutable default args",
|
||||
"trigger": "Function with [] as default",
|
||||
"solution": "Use None and check in body",
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is True
|
||||
|
||||
call_args = queries.client.graphiti.add_episode.call_args
|
||||
episode_body = json.loads(call_args[1]["episode_body"])
|
||||
assert episode_body["gotcha"] == "Mutable default args"
|
||||
assert episode_body["trigger"] == "Function with [] as default"
|
||||
assert episode_body["solution"] == "Use None and check in body"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_add_structured_insights_outcome_with_all_fields(self, queries):
|
||||
"""Test outcome with all optional fields."""
|
||||
insights = {
|
||||
"subtask_id": "task-1",
|
||||
"approach_outcome": {
|
||||
"success": True,
|
||||
"approach_used": "Test approach",
|
||||
"why_it_worked": "Because reasons",
|
||||
"why_it_failed": None,
|
||||
"alternatives_tried": ["Alt1", "Alt2"],
|
||||
},
|
||||
"changed_files": ["file1.py", "file2.py"],
|
||||
}
|
||||
|
||||
result = await queries.add_structured_insights(insights)
|
||||
|
||||
assert result is True
|
||||
|
||||
call_args = queries.client.graphiti.add_episode.call_args
|
||||
episode_body = json.loads(call_args[1]["episode_body"])
|
||||
assert episode_body["task_id"] == "task-1"
|
||||
assert episode_body["success"] is True
|
||||
assert episode_body["outcome"] == "Test approach"
|
||||
assert episode_body["why_worked"] == "Because reasons"
|
||||
assert episode_body["why_failed"] is None
|
||||
assert episode_body["alternatives_tried"] == ["Alt1", "Alt2"]
|
||||
assert episode_body["changed_files"] == ["file1.py", "file2.py"]
|
||||
@@ -0,0 +1,123 @@
|
||||
"""
|
||||
Tests for Graphiti schema constants and types.
|
||||
|
||||
Tests cover:
|
||||
- Episode type constants
|
||||
- MAX_CONTEXT_RESULTS constant
|
||||
- GroupIdMode enum values
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from integrations.graphiti.queries_pkg.schema import (
|
||||
EPISODE_TYPE_CODEBASE_DISCOVERY,
|
||||
EPISODE_TYPE_GOTCHA,
|
||||
EPISODE_TYPE_HISTORICAL_CONTEXT,
|
||||
EPISODE_TYPE_PATTERN,
|
||||
EPISODE_TYPE_QA_RESULT,
|
||||
EPISODE_TYPE_SESSION_INSIGHT,
|
||||
EPISODE_TYPE_TASK_OUTCOME,
|
||||
MAX_CONTEXT_RESULTS,
|
||||
MAX_RETRIES,
|
||||
RETRY_DELAY_SECONDS,
|
||||
GroupIdMode,
|
||||
)
|
||||
|
||||
|
||||
class TestEpisodeTypeConstants:
|
||||
"""Test episode type constants."""
|
||||
|
||||
def test_session_insight_constant(self):
|
||||
"""Test EPISODE_TYPE_SESSION_INSIGHT constant."""
|
||||
assert EPISODE_TYPE_SESSION_INSIGHT == "session_insight"
|
||||
assert isinstance(EPISODE_TYPE_SESSION_INSIGHT, str)
|
||||
|
||||
def test_codebase_discovery_constant(self):
|
||||
"""Test EPISODE_TYPE_CODEBASE_DISCOVERY constant."""
|
||||
assert EPISODE_TYPE_CODEBASE_DISCOVERY == "codebase_discovery"
|
||||
assert isinstance(EPISODE_TYPE_CODEBASE_DISCOVERY, str)
|
||||
|
||||
def test_pattern_constant(self):
|
||||
"""Test EPISODE_TYPE_PATTERN constant."""
|
||||
assert EPISODE_TYPE_PATTERN == "pattern"
|
||||
assert isinstance(EPISODE_TYPE_PATTERN, str)
|
||||
|
||||
def test_gotcha_constant(self):
|
||||
"""Test EPISODE_TYPE_GOTCHA constant."""
|
||||
assert EPISODE_TYPE_GOTCHA == "gotcha"
|
||||
assert isinstance(EPISODE_TYPE_GOTCHA, str)
|
||||
|
||||
def test_task_outcome_constant(self):
|
||||
"""Test EPISODE_TYPE_TASK_OUTCOME constant."""
|
||||
assert EPISODE_TYPE_TASK_OUTCOME == "task_outcome"
|
||||
assert isinstance(EPISODE_TYPE_TASK_OUTCOME, str)
|
||||
|
||||
def test_qa_result_constant(self):
|
||||
"""Test EPISODE_TYPE_QA_RESULT constant."""
|
||||
assert EPISODE_TYPE_QA_RESULT == "qa_result"
|
||||
assert isinstance(EPISODE_TYPE_QA_RESULT, str)
|
||||
|
||||
def test_historical_context_constant(self):
|
||||
"""Test EPISODE_TYPE_HISTORICAL_CONTEXT constant."""
|
||||
assert EPISODE_TYPE_HISTORICAL_CONTEXT == "historical_context"
|
||||
assert isinstance(EPISODE_TYPE_HISTORICAL_CONTEXT, str)
|
||||
|
||||
def test_all_episode_types_are_unique(self):
|
||||
"""Test that all episode type constants have unique values."""
|
||||
episode_types = [
|
||||
EPISODE_TYPE_SESSION_INSIGHT,
|
||||
EPISODE_TYPE_CODEBASE_DISCOVERY,
|
||||
EPISODE_TYPE_PATTERN,
|
||||
EPISODE_TYPE_GOTCHA,
|
||||
EPISODE_TYPE_TASK_OUTCOME,
|
||||
EPISODE_TYPE_QA_RESULT,
|
||||
EPISODE_TYPE_HISTORICAL_CONTEXT,
|
||||
]
|
||||
assert len(episode_types) == len(set(episode_types)), (
|
||||
"Episode types must be unique"
|
||||
)
|
||||
|
||||
|
||||
class TestMaxContextResults:
|
||||
"""Test MAX_CONTEXT_RESULTS constant."""
|
||||
|
||||
def test_max_context_results_is_positive_integer(self):
|
||||
"""Test MAX_CONTEXT_RESULTS is a positive integer."""
|
||||
assert isinstance(MAX_CONTEXT_RESULTS, int)
|
||||
assert MAX_CONTEXT_RESULTS > 0
|
||||
|
||||
def test_max_context_results_reasonable_value(self):
|
||||
"""Test MAX_CONTEXT_RESULTS has a reasonable value."""
|
||||
# Should be between 1 and 100 for practical use
|
||||
assert 1 <= MAX_CONTEXT_RESULTS <= 100
|
||||
|
||||
|
||||
class TestRetryConfiguration:
|
||||
"""Test retry configuration constants."""
|
||||
|
||||
def test_max_retries_is_positive_integer(self):
|
||||
"""Test MAX_RETRIES is a positive integer."""
|
||||
assert isinstance(MAX_RETRIES, int)
|
||||
assert MAX_RETRIES > 0
|
||||
|
||||
def test_retry_delay_is_positive_number(self):
|
||||
"""Test RETRY_DELAY_SECONDS is a positive number."""
|
||||
assert isinstance(RETRY_DELAY_SECONDS, (int, float))
|
||||
assert RETRY_DELAY_SECONDS >= 0
|
||||
|
||||
|
||||
class TestGroupIdMode:
|
||||
"""Test GroupIdMode class."""
|
||||
|
||||
def test_spec_mode_constant(self):
|
||||
"""Test GroupIdMode.SPEC constant."""
|
||||
assert GroupIdMode.SPEC == "spec"
|
||||
assert isinstance(GroupIdMode.SPEC, str)
|
||||
|
||||
def test_project_mode_constant(self):
|
||||
"""Test GroupIdMode.PROJECT constant."""
|
||||
assert GroupIdMode.PROJECT == "project"
|
||||
assert isinstance(GroupIdMode.PROJECT, str)
|
||||
|
||||
def test_modes_are_unique(self):
|
||||
"""Test that mode values are unique."""
|
||||
assert GroupIdMode.SPEC != GroupIdMode.PROJECT
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,82 @@
|
||||
# Pyproject configuration for Auto-Claude backend
|
||||
|
||||
[project]
|
||||
name = "auto-claude-backend"
|
||||
version = "2.7.6"
|
||||
description = "Auto-Claude autonomous coding framework - Python backend"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"claude-agent-sdk>=0.1.25",
|
||||
"python-dotenv>=1.0.0",
|
||||
"graphiti-core>=0.5.0",
|
||||
"pandas>=2.2.0",
|
||||
"google-generativeai>=0.8.0",
|
||||
"pydantic>=2.0.0",
|
||||
"sentry-sdk>=2.0.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest>=7.0.0",
|
||||
"pytest-asyncio>=0.21.0",
|
||||
"pytest-cov>=4.0.0",
|
||||
"pytest-timeout>=2.0.0",
|
||||
"pytest-mock>=3.0.0",
|
||||
"coverage>=7.0.0",
|
||||
"mypy>=1.0.0",
|
||||
"types-toml>=0.10.0",
|
||||
]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["integrations/graphiti/tests", "core/workspace/tests"]
|
||||
python_files = ["test_*.py"]
|
||||
python_functions = ["test_*"]
|
||||
python_classes = ["Test*"]
|
||||
asyncio_mode = "strict"
|
||||
asyncio_default_fixture_loop_scope = "function"
|
||||
|
||||
# Markers for long-running tests
|
||||
markers = [
|
||||
"slow: marks tests as slow (skipped in CI by default) - takes >2 seconds or involves external services",
|
||||
"integration: marks tests as integration tests (external services like database, network, API calls)",
|
||||
"smoke: marks smoke tests for quick verification",
|
||||
]
|
||||
|
||||
# Optimizations
|
||||
addopts = [
|
||||
"--maxfail=5",
|
||||
"-v",
|
||||
"-m", "not slow",
|
||||
"--tb=short",
|
||||
]
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["integrations", "core", "agents", "cli", "context", "qa", "spec", "runners", "services"]
|
||||
omit = [
|
||||
"*/tests/*",
|
||||
"*/test_*.py",
|
||||
"*/__pycache__/*",
|
||||
"*/.venv/*",
|
||||
"*/site-packages/*",
|
||||
]
|
||||
|
||||
[tool.coverage.report]
|
||||
precision = 1
|
||||
show_missing = true
|
||||
skip_covered = false
|
||||
exclude_lines = [
|
||||
"pragma: no cover",
|
||||
"def __repr__",
|
||||
"raise AssertionError",
|
||||
"raise NotImplementedError",
|
||||
"if __name__ == .__main__.:",
|
||||
"if TYPE_CHECKING:",
|
||||
"class .*\\bProtocol\\):",
|
||||
"@(abc\\.)?abstractmethod",
|
||||
]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.12"
|
||||
warn_return_any = true
|
||||
warn_unused_configs = true
|
||||
disallow_untyped_defs = false
|
||||
@@ -12,7 +12,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
|
||||
@@ -22,6 +22,11 @@ except (ImportError, ValueError, SystemError):
|
||||
from file_lock import locked_json_update, locked_json_write
|
||||
|
||||
|
||||
def _utc_now_iso() -> str:
|
||||
"""Return current UTC time as ISO 8601 string with timezone info."""
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
class ReviewSeverity(str, Enum):
|
||||
"""Severity levels for PR review findings."""
|
||||
|
||||
@@ -521,7 +526,7 @@ class PRReviewResult:
|
||||
summary: str = ""
|
||||
overall_status: str = "comment" # approve, request_changes, comment
|
||||
review_id: int | None = None
|
||||
reviewed_at: str = field(default_factory=lambda: datetime.now().isoformat())
|
||||
reviewed_at: str = field(default_factory=lambda: _utc_now_iso())
|
||||
error: str | None = None
|
||||
|
||||
# NEW: Enhanced verdict system
|
||||
@@ -610,7 +615,7 @@ class PRReviewResult:
|
||||
summary=data.get("summary", ""),
|
||||
overall_status=data.get("overall_status", "comment"),
|
||||
review_id=data.get("review_id"),
|
||||
reviewed_at=data.get("reviewed_at", datetime.now().isoformat()),
|
||||
reviewed_at=data.get("reviewed_at", _utc_now_iso()),
|
||||
error=data.get("error"),
|
||||
# NEW fields
|
||||
verdict=MergeVerdict(data.get("verdict", "ready_to_merge")),
|
||||
@@ -691,7 +696,7 @@ class PRReviewResult:
|
||||
reviews.append(entry)
|
||||
|
||||
current_data["reviews"] = reviews
|
||||
current_data["last_updated"] = datetime.now().isoformat()
|
||||
current_data["last_updated"] = _utc_now_iso()
|
||||
|
||||
return current_data
|
||||
|
||||
@@ -762,7 +767,7 @@ class TriageResult:
|
||||
suggested_breakdown: list[str] = field(default_factory=list)
|
||||
priority: str = "medium" # high, medium, low
|
||||
comment: str | None = None
|
||||
triaged_at: str = field(default_factory=lambda: datetime.now().isoformat())
|
||||
triaged_at: str = field(default_factory=lambda: _utc_now_iso())
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
@@ -798,7 +803,7 @@ class TriageResult:
|
||||
suggested_breakdown=data.get("suggested_breakdown", []),
|
||||
priority=data.get("priority", "medium"),
|
||||
comment=data.get("comment"),
|
||||
triaged_at=data.get("triaged_at", datetime.now().isoformat()),
|
||||
triaged_at=data.get("triaged_at", _utc_now_iso()),
|
||||
)
|
||||
|
||||
async def save(self, github_dir: Path) -> None:
|
||||
@@ -836,8 +841,8 @@ class AutoFixState:
|
||||
pr_url: str | None = None
|
||||
bot_comments: list[str] = field(default_factory=list)
|
||||
error: str | None = None
|
||||
created_at: str = field(default_factory=lambda: datetime.now().isoformat())
|
||||
updated_at: str = field(default_factory=lambda: datetime.now().isoformat())
|
||||
created_at: str = field(default_factory=lambda: _utc_now_iso())
|
||||
updated_at: str = field(default_factory=lambda: _utc_now_iso())
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
@@ -875,8 +880,8 @@ class AutoFixState:
|
||||
pr_url=data.get("pr_url"),
|
||||
bot_comments=data.get("bot_comments", []),
|
||||
error=data.get("error"),
|
||||
created_at=data.get("created_at", datetime.now().isoformat()),
|
||||
updated_at=data.get("updated_at", datetime.now().isoformat()),
|
||||
created_at=data.get("created_at", _utc_now_iso()),
|
||||
updated_at=data.get("updated_at", _utc_now_iso()),
|
||||
)
|
||||
|
||||
def update_status(self, status: AutoFixStatus) -> None:
|
||||
@@ -886,7 +891,7 @@ class AutoFixState:
|
||||
f"Invalid state transition: {self.status.value} -> {status.value}"
|
||||
)
|
||||
self.status = status
|
||||
self.updated_at = datetime.now().isoformat()
|
||||
self.updated_at = _utc_now_iso()
|
||||
|
||||
async def save(self, github_dir: Path) -> None:
|
||||
"""Save auto-fix state to .auto-claude/github/issues/ with file locking."""
|
||||
@@ -938,7 +943,7 @@ class AutoFixState:
|
||||
queue.append(entry)
|
||||
|
||||
current_data["auto_fix_queue"] = queue
|
||||
current_data["last_updated"] = datetime.now().isoformat()
|
||||
current_data["last_updated"] = _utc_now_iso()
|
||||
|
||||
return current_data
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
@@ -33,6 +32,7 @@ try:
|
||||
PRReviewResult,
|
||||
ReviewCategory,
|
||||
ReviewSeverity,
|
||||
_utc_now_iso,
|
||||
)
|
||||
from .category_utils import map_category
|
||||
from .io_utils import safe_print
|
||||
@@ -46,6 +46,7 @@ except (ImportError, ValueError, SystemError):
|
||||
PRReviewResult,
|
||||
ReviewCategory,
|
||||
ReviewSeverity,
|
||||
_utc_now_iso,
|
||||
)
|
||||
from services.category_utils import map_category
|
||||
from services.io_utils import safe_print
|
||||
@@ -265,7 +266,7 @@ class FollowupReviewer:
|
||||
verdict=verdict,
|
||||
verdict_reasoning=verdict_reasoning,
|
||||
blockers=blockers,
|
||||
reviewed_at=datetime.now().isoformat(),
|
||||
reviewed_at=_utc_now_iso(),
|
||||
# Follow-up specific fields
|
||||
reviewed_commit_sha=context.current_commit_sha,
|
||||
reviewed_file_blobs=file_blobs,
|
||||
|
||||
@@ -51,7 +51,7 @@ try:
|
||||
from .category_utils import map_category
|
||||
from .io_utils import safe_print
|
||||
from .pr_worktree_manager import PRWorktreeManager
|
||||
from .pydantic_models import ParallelFollowupResponse
|
||||
from .pydantic_models import FollowupExtractionResponse, ParallelFollowupResponse
|
||||
from .sdk_utils import process_sdk_stream
|
||||
except (ImportError, ValueError, SystemError):
|
||||
from context_gatherer import _validate_git_ref
|
||||
@@ -75,7 +75,10 @@ except (ImportError, ValueError, SystemError):
|
||||
from services.category_utils import map_category
|
||||
from services.io_utils import safe_print
|
||||
from services.pr_worktree_manager import PRWorktreeManager
|
||||
from services.pydantic_models import ParallelFollowupResponse
|
||||
from services.pydantic_models import (
|
||||
FollowupExtractionResponse,
|
||||
ParallelFollowupResponse,
|
||||
)
|
||||
from services.sdk_utils import process_sdk_stream
|
||||
|
||||
|
||||
@@ -576,16 +579,36 @@ The SDK will run invoked agents in parallel automatically.
|
||||
)
|
||||
|
||||
# Check for stream processing errors
|
||||
if stream_result.get("error"):
|
||||
logger.error(
|
||||
f"[ParallelFollowup] SDK stream failed: {stream_result['error']}"
|
||||
)
|
||||
raise RuntimeError(
|
||||
f"SDK stream processing failed: {stream_result['error']}"
|
||||
)
|
||||
stream_error = stream_result.get("error")
|
||||
if stream_error:
|
||||
if stream_result.get("error_recoverable"):
|
||||
# Recoverable error — attempt extraction call fallback
|
||||
logger.warning(
|
||||
f"[ParallelFollowup] Recoverable error: {stream_error}. "
|
||||
f"Attempting extraction call fallback."
|
||||
)
|
||||
safe_print(
|
||||
f"[ParallelFollowup] WARNING: {stream_error} — "
|
||||
f"attempting recovery with minimal extraction...",
|
||||
flush=True,
|
||||
)
|
||||
else:
|
||||
# Fatal error — raise as before
|
||||
logger.error(
|
||||
f"[ParallelFollowup] SDK stream failed: {stream_error}"
|
||||
)
|
||||
raise RuntimeError(
|
||||
f"SDK stream processing failed: {stream_error}"
|
||||
)
|
||||
|
||||
result_text = stream_result["result_text"]
|
||||
structured_output = stream_result["structured_output"]
|
||||
last_assistant_text = stream_result.get("last_assistant_text", "")
|
||||
# Nullify structured output on recoverable errors to force Tier 2 fallback
|
||||
structured_output = (
|
||||
None
|
||||
if (stream_error and stream_result.get("error_recoverable"))
|
||||
else stream_result["structured_output"]
|
||||
)
|
||||
agents_invoked = stream_result["agents_invoked"]
|
||||
msg_count = stream_result["msg_count"]
|
||||
|
||||
@@ -596,22 +619,28 @@ The SDK will run invoked agents in parallel automatically.
|
||||
pr_number=context.pr_number,
|
||||
)
|
||||
|
||||
# Parse findings from output
|
||||
# Parse findings from output (three-tier recovery cascade)
|
||||
if structured_output:
|
||||
result_data = self._parse_structured_output(structured_output, context)
|
||||
else:
|
||||
# Log when structured output is missing - this shouldn't happen normally
|
||||
# when output_format is configured, so it indicates a problem
|
||||
# Structured output missing or validation failed.
|
||||
# Tier 2: Attempt extraction call with minimal schema
|
||||
logger.warning(
|
||||
"[ParallelFollowup] No structured output received from SDK - "
|
||||
"falling back to text parsing. Resolution data may be incomplete."
|
||||
"[ParallelFollowup] No structured output — attempting extraction call"
|
||||
)
|
||||
safe_print(
|
||||
"[ParallelFollowup] WARNING: Structured output not captured, "
|
||||
"using text fallback (resolution tracking may be incomplete)",
|
||||
flush=True,
|
||||
# Use last_assistant_text (cleaner) if available, fall back to full transcript
|
||||
fallback_text = last_assistant_text or result_text
|
||||
result_data = await self._attempt_extraction_call(
|
||||
fallback_text, context
|
||||
)
|
||||
result_data = self._parse_text_output(result_text, context)
|
||||
if result_data is None:
|
||||
# Tier 3: Fall back to basic text parsing
|
||||
safe_print(
|
||||
"[ParallelFollowup] WARNING: Extraction call failed, "
|
||||
"using text fallback (resolution tracking may be incomplete)",
|
||||
flush=True,
|
||||
)
|
||||
result_data = self._parse_text_output(result_text, context)
|
||||
|
||||
# Extract data
|
||||
findings = result_data.get("findings", [])
|
||||
@@ -730,7 +759,9 @@ The SDK will run invoked agents in parallel automatically.
|
||||
blockers.append(f"{finding.category.value}: {finding.title}")
|
||||
|
||||
# Extract validation counts
|
||||
dismissed_count = len(result_data.get("dismissed_false_positive_ids", []))
|
||||
dismissed_count = len(
|
||||
result_data.get("dismissed_false_positive_ids", [])
|
||||
) or result_data.get("dismissed_finding_count", 0)
|
||||
confirmed_count = result_data.get("confirmed_valid_count", 0)
|
||||
needs_human_count = result_data.get("needs_human_review_count", 0)
|
||||
|
||||
@@ -1074,17 +1105,129 @@ The SDK will run invoked agents in parallel automatically.
|
||||
elif "needs revision" in text_lower or "request changes" in text_lower:
|
||||
verdict = MergeVerdict.NEEDS_REVISION
|
||||
else:
|
||||
verdict = MergeVerdict.MERGE_WITH_CHANGES
|
||||
verdict = MergeVerdict.NEEDS_REVISION
|
||||
|
||||
return {
|
||||
"findings": findings,
|
||||
"resolved_ids": [],
|
||||
"unresolved_ids": [],
|
||||
"new_finding_ids": [],
|
||||
"dismissed_false_positive_ids": [],
|
||||
"confirmed_valid_count": 0,
|
||||
"dismissed_finding_count": 0,
|
||||
"needs_human_review_count": 0,
|
||||
"verdict": verdict,
|
||||
"verdict_reasoning": text[:500] if text else "Unable to parse response",
|
||||
"agents_invoked": [],
|
||||
}
|
||||
|
||||
async def _attempt_extraction_call(
|
||||
self, text: str, context: FollowupReviewContext
|
||||
) -> dict | None:
|
||||
"""Attempt a short SDK call with a minimal schema to recover review data.
|
||||
|
||||
This is the Tier 2 recovery step when full structured output validation fails.
|
||||
Uses FollowupExtractionResponse (~6 flat fields) which has near-100% success rate.
|
||||
|
||||
Returns parsed result dict on success, None on failure.
|
||||
"""
|
||||
if not text or not text.strip():
|
||||
logger.warning("[ParallelFollowup] No text available for extraction call")
|
||||
return None
|
||||
|
||||
try:
|
||||
safe_print(
|
||||
"[ParallelFollowup] Attempting recovery with minimal extraction schema...",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
extraction_prompt = (
|
||||
"Extract the key review data from the following AI analysis output. "
|
||||
"Return the verdict, reasoning, resolved finding IDs, unresolved finding IDs, "
|
||||
"one-line summaries of any new findings, and counts of confirmed/dismissed findings.\n\n"
|
||||
f"--- AI ANALYSIS OUTPUT ---\n{text[:8000]}\n--- END ---"
|
||||
)
|
||||
|
||||
model_shorthand = self.config.model or "sonnet"
|
||||
model = resolve_model_id(model_shorthand)
|
||||
|
||||
extraction_client = create_client(
|
||||
project_dir=self.project_dir,
|
||||
spec_dir=self.github_dir,
|
||||
model=model,
|
||||
agent_type="pr_followup_extraction",
|
||||
fast_mode=self.config.fast_mode,
|
||||
output_format={
|
||||
"type": "json_schema",
|
||||
"schema": FollowupExtractionResponse.model_json_schema(),
|
||||
},
|
||||
)
|
||||
|
||||
async with extraction_client:
|
||||
await extraction_client.query(extraction_prompt)
|
||||
|
||||
stream_result = await process_sdk_stream(
|
||||
client=extraction_client,
|
||||
context_name="FollowupExtraction",
|
||||
model=model,
|
||||
system_prompt=extraction_prompt,
|
||||
max_messages=20,
|
||||
)
|
||||
|
||||
if stream_result.get("error"):
|
||||
logger.warning(
|
||||
f"[ParallelFollowup] Extraction call also failed: {stream_result['error']}"
|
||||
)
|
||||
return None
|
||||
|
||||
extraction_output = stream_result.get("structured_output")
|
||||
if not extraction_output:
|
||||
logger.warning(
|
||||
"[ParallelFollowup] Extraction call returned no structured output"
|
||||
)
|
||||
return None
|
||||
|
||||
# Parse the minimal extraction response
|
||||
extracted = FollowupExtractionResponse.model_validate(extraction_output)
|
||||
|
||||
# Map verdict string to MergeVerdict enum
|
||||
verdict_map = {
|
||||
"READY_TO_MERGE": MergeVerdict.READY_TO_MERGE,
|
||||
"MERGE_WITH_CHANGES": MergeVerdict.MERGE_WITH_CHANGES,
|
||||
"NEEDS_REVISION": MergeVerdict.NEEDS_REVISION,
|
||||
"BLOCKED": MergeVerdict.BLOCKED,
|
||||
}
|
||||
verdict = verdict_map.get(extracted.verdict, MergeVerdict.NEEDS_REVISION)
|
||||
|
||||
safe_print(
|
||||
f"[ParallelFollowup] Extraction recovered: verdict={extracted.verdict}, "
|
||||
f"{len(extracted.resolved_finding_ids)} resolved, "
|
||||
f"{len(extracted.new_finding_summaries)} new findings",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
return {
|
||||
"findings": [], # Full findings not recoverable via extraction
|
||||
"resolved_ids": extracted.resolved_finding_ids,
|
||||
"unresolved_ids": extracted.unresolved_finding_ids,
|
||||
"new_finding_ids": [],
|
||||
"dismissed_false_positive_ids": [],
|
||||
"confirmed_valid_count": extracted.confirmed_finding_count,
|
||||
"dismissed_finding_count": extracted.dismissed_finding_count,
|
||||
"needs_human_review_count": 0,
|
||||
"verdict": verdict,
|
||||
"verdict_reasoning": f"[Recovered via extraction] {extracted.verdict_reasoning}",
|
||||
"agents_invoked": [],
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"[ParallelFollowup] Extraction call failed: {e}")
|
||||
safe_print(
|
||||
f"[ParallelFollowup] Extraction call failed: {e}",
|
||||
flush=True,
|
||||
)
|
||||
return None
|
||||
|
||||
def _create_empty_result(self) -> dict:
|
||||
"""Create empty result structure."""
|
||||
return {
|
||||
@@ -1092,8 +1235,13 @@ The SDK will run invoked agents in parallel automatically.
|
||||
"resolved_ids": [],
|
||||
"unresolved_ids": [],
|
||||
"new_finding_ids": [],
|
||||
"dismissed_false_positive_ids": [],
|
||||
"confirmed_valid_count": 0,
|
||||
"dismissed_finding_count": 0,
|
||||
"needs_human_review_count": 0,
|
||||
"verdict": MergeVerdict.NEEDS_REVISION,
|
||||
"verdict_reasoning": "Unable to parse review results",
|
||||
"agents_invoked": [],
|
||||
}
|
||||
|
||||
def _extract_partial_data(self, data: dict) -> dict | None:
|
||||
|
||||
@@ -1785,6 +1785,7 @@ For EACH finding above:
|
||||
or "concurrency" in error_str
|
||||
or "circuit breaker" in error_str
|
||||
or "tool_use" in error_str
|
||||
or "structured_output" in error_str
|
||||
)
|
||||
|
||||
if is_retryable and attempt < MAX_VALIDATION_RETRIES:
|
||||
|
||||
@@ -710,3 +710,39 @@ class FindingValidationResponse(BaseModel):
|
||||
"how many dismissed, how many need human review"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Minimal Extraction Schema (Fallback for structured output validation failure)
|
||||
# =============================================================================
|
||||
|
||||
|
||||
class FollowupExtractionResponse(BaseModel):
|
||||
"""Minimal extraction schema for recovering data when full structured output fails.
|
||||
|
||||
Deliberately kept small (~6 fields, no nesting) for near-100% validation success.
|
||||
Used as an intermediate recovery step before falling back to raw text parsing.
|
||||
"""
|
||||
|
||||
verdict: Literal[
|
||||
"READY_TO_MERGE", "MERGE_WITH_CHANGES", "NEEDS_REVISION", "BLOCKED"
|
||||
] = Field(description="Overall merge verdict")
|
||||
verdict_reasoning: str = Field(description="Explanation for the verdict")
|
||||
resolved_finding_ids: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="IDs of previous findings that are now resolved",
|
||||
)
|
||||
unresolved_finding_ids: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="IDs of previous findings that remain unresolved",
|
||||
)
|
||||
new_finding_summaries: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="One-line summary of each new finding (e.g. 'HIGH: cleanup deletes QA-rejected specs in batch_commands.py')",
|
||||
)
|
||||
confirmed_finding_count: int = Field(
|
||||
0, description="Number of findings confirmed as valid"
|
||||
)
|
||||
dismissed_finding_count: int = Field(
|
||||
0, description="Number of findings dismissed as false positives"
|
||||
)
|
||||
|
||||
@@ -133,6 +133,13 @@ def _get_tool_detail(tool_name: str, tool_input: dict[str, Any]) -> str:
|
||||
# Prevents runaway retry loops from consuming unbounded resources
|
||||
MAX_MESSAGE_COUNT = 500
|
||||
|
||||
# Errors that are recoverable (callers can fall back to text parsing or retry)
|
||||
# vs fatal errors (auth failures, circuit breaker) that should propagate
|
||||
RECOVERABLE_ERRORS = {
|
||||
"structured_output_validation_failed",
|
||||
"tool_use_concurrency_error",
|
||||
}
|
||||
|
||||
# Abort after 1 consecutive repeat (2 total identical responses).
|
||||
# Low threshold catches error loops quickly (e.g., auth errors returned as AI text).
|
||||
# Normal AI responses never produce the exact same text block twice in a row.
|
||||
@@ -261,8 +268,11 @@ async def process_sdk_stream(
|
||||
- msg_count: Total message count
|
||||
- subagent_tool_ids: Mapping of tool_id -> agent_name
|
||||
- error: Error message if stream processing failed (None on success)
|
||||
- error_recoverable: Boolean indicating if the error is recoverable (fallback possible) vs fatal
|
||||
- last_assistant_text: Last non-empty assistant text block (for cleaner fallback parsing)
|
||||
"""
|
||||
result_text = ""
|
||||
last_assistant_text = "" # Last assistant text block (for cleaner fallback parsing)
|
||||
structured_output = None
|
||||
agents_invoked = []
|
||||
msg_count = 0
|
||||
@@ -481,6 +491,9 @@ async def process_sdk_stream(
|
||||
block_type = type(block).__name__
|
||||
if block_type == "TextBlock" and hasattr(block, "text"):
|
||||
result_text += block.text
|
||||
# Track last non-empty text for fallback parsing
|
||||
if block.text.strip():
|
||||
last_assistant_text = block.text
|
||||
# Check for auth/access error returned as AI response text.
|
||||
# Note: break exits this inner for-loop over msg.content;
|
||||
# the outer message loop exits via `if stream_error: break`.
|
||||
@@ -647,11 +660,16 @@ async def process_sdk_stream(
|
||||
f"[{context_name}] Tool use concurrency error detected - caller should retry"
|
||||
)
|
||||
|
||||
# Categorize error as recoverable (fallback possible) vs fatal
|
||||
error_recoverable = stream_error in RECOVERABLE_ERRORS if stream_error else False
|
||||
|
||||
return {
|
||||
"result_text": result_text,
|
||||
"last_assistant_text": last_assistant_text,
|
||||
"structured_output": structured_output,
|
||||
"agents_invoked": agents_invoked,
|
||||
"msg_count": msg_count,
|
||||
"subagent_tool_ids": subagent_tool_ids,
|
||||
"error": stream_error,
|
||||
"error_recoverable": error_recoverable,
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ export default defineConfig({
|
||||
plugins: [externalizeDepsPlugin({
|
||||
// Bundle these packages into the main process (they won't be in node_modules in packaged app)
|
||||
exclude: [
|
||||
// Workspace packages — must be bundled, not externalized
|
||||
'@auto-claude/types',
|
||||
'uuid',
|
||||
'chokidar',
|
||||
'dotenv',
|
||||
@@ -90,7 +92,10 @@ export default defineConfig({
|
||||
'@features': resolve(__dirname, 'src/renderer/features'),
|
||||
'@components': resolve(__dirname, 'src/renderer/shared/components'),
|
||||
'@hooks': resolve(__dirname, 'src/renderer/shared/hooks'),
|
||||
'@lib': resolve(__dirname, 'src/renderer/shared/lib')
|
||||
'@lib': resolve(__dirname, 'src/renderer/shared/lib'),
|
||||
// Workspace packages — resolve to source for HMR support
|
||||
'@auto-claude/types': resolve(__dirname, '../../packages/types/src'),
|
||||
'@auto-claude/ui': resolve(__dirname, '../../packages/ui/src')
|
||||
}
|
||||
},
|
||||
server: {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "auto-claude-ui",
|
||||
"version": "2.7.6-beta.3",
|
||||
"version": "2.7.7",
|
||||
"type": "module",
|
||||
"description": "Desktop UI for Auto Claude autonomous coding framework",
|
||||
"homepage": "https://github.com/AndyMik90/Auto-Claude",
|
||||
@@ -51,6 +51,8 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@auto-claude/types": "*",
|
||||
"@auto-claude/ui": "*",
|
||||
"@anthropic-ai/sdk": "^0.71.2",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
|
||||
@@ -28,7 +28,7 @@ function setupTestDirs(): void {
|
||||
TEST_DIR = mkdtempSync(path.join(tmpdir(), 'project-store-test-'));
|
||||
USER_DATA_PATH = path.join(TEST_DIR, 'userData');
|
||||
TEST_PROJECT_PATH = path.join(TEST_DIR, 'test-project');
|
||||
|
||||
|
||||
mkdirSync(USER_DATA_PATH, { recursive: true });
|
||||
mkdirSync(path.join(USER_DATA_PATH, 'store'), { recursive: true });
|
||||
mkdirSync(TEST_PROJECT_PATH, { recursive: true });
|
||||
|
||||
@@ -45,6 +45,66 @@ type UpdateChannel = 'latest' | 'beta';
|
||||
// Store interval ID for cleanup during shutdown
|
||||
let periodicCheckIntervalId: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
/**
|
||||
* Convert basic HTML (from GitHub release bodies) to markdown.
|
||||
* Handles the common tags GitHub uses in release notes.
|
||||
*/
|
||||
function htmlToMarkdown(html: string): string {
|
||||
let md = html;
|
||||
|
||||
// Block-level replacements
|
||||
md = md.replace(/<h1[^>]*>(.*?)<\/h1>/gi, '# $1\n\n');
|
||||
md = md.replace(/<h2[^>]*>(.*?)<\/h2>/gi, '## $1\n\n');
|
||||
md = md.replace(/<h3[^>]*>(.*?)<\/h3>/gi, '### $1\n\n');
|
||||
md = md.replace(/<h4[^>]*>(.*?)<\/h4>/gi, '#### $1\n\n');
|
||||
|
||||
// Lists: convert <ol>/<ul> with <li> items
|
||||
// First handle <li> within <ol> (numbered)
|
||||
md = md.replace(/<ol[^>]*>([\s\S]*?)<\/ol>/gi, (_match, content: string) => {
|
||||
let i = 0;
|
||||
return content.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, (_m: string, text: string) => {
|
||||
i++;
|
||||
return `${i}. ${text.trim()}\n`;
|
||||
}) + '\n';
|
||||
});
|
||||
// Then <li> within <ul> (bulleted)
|
||||
md = md.replace(/<ul[^>]*>([\s\S]*?)<\/ul>/gi, (_match, content: string) => {
|
||||
return content.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, (_m: string, text: string) => {
|
||||
return `- ${text.trim()}\n`;
|
||||
}) + '\n';
|
||||
});
|
||||
|
||||
// Inline replacements
|
||||
md = md.replace(/<strong[^>]*>(.*?)<\/strong>/gi, '**$1**');
|
||||
md = md.replace(/<b[^>]*>(.*?)<\/b>/gi, '**$1**');
|
||||
md = md.replace(/<em[^>]*>(.*?)<\/em>/gi, '*$1*');
|
||||
md = md.replace(/<i[^>]*>(.*?)<\/i>/gi, '*$1*');
|
||||
md = md.replace(/<code[^>]*>(.*?)<\/code>/gi, '`$1`');
|
||||
md = md.replace(/<tt[^>]*>(.*?)<\/tt>/gi, '`$1`');
|
||||
md = md.replace(/<a[^>]*href="([^"]*)"[^>]*>(.*?)<\/a>/gi, '[$2]($1)');
|
||||
|
||||
// Block elements
|
||||
md = md.replace(/<p[^>]*>([\s\S]*?)<\/p>/gi, '$1\n\n');
|
||||
md = md.replace(/<br\s*\/?>/gi, '\n');
|
||||
md = md.replace(/<hr\s*\/?>/gi, '---\n\n');
|
||||
|
||||
// Remove any remaining HTML tags
|
||||
md = md.replace(/<[^>]+>/g, '');
|
||||
|
||||
// Decode common HTML entities
|
||||
md = md.replace(/&/g, '&');
|
||||
md = md.replace(/</g, '<');
|
||||
md = md.replace(/>/g, '>');
|
||||
md = md.replace(/"/g, '"');
|
||||
md = md.replace(/'/g, "'");
|
||||
md = md.replace(/ /g, ' ');
|
||||
|
||||
// Clean up excessive whitespace
|
||||
md = md.replace(/\n{3,}/g, '\n\n');
|
||||
|
||||
return md.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert releaseNotes from electron-updater to a markdown string.
|
||||
* releaseNotes can be:
|
||||
@@ -57,8 +117,12 @@ function formatReleaseNotes(releaseNotes: UpdateInfo['releaseNotes']): string |
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// If it's already a string, return as-is
|
||||
// If it's a string, convert HTML to markdown if needed
|
||||
// electron-updater returns GitHub release bodies as HTML
|
||||
if (typeof releaseNotes === 'string') {
|
||||
if (releaseNotes.trimStart().startsWith('<')) {
|
||||
return htmlToMarkdown(releaseNotes);
|
||||
}
|
||||
return releaseNotes;
|
||||
}
|
||||
|
||||
@@ -74,8 +138,12 @@ function formatReleaseNotes(releaseNotes: UpdateInfo['releaseNotes']): string |
|
||||
.filter(item => item.note) // Filter out entries with null/undefined notes
|
||||
.map(item => {
|
||||
// Each item has version and note properties
|
||||
// note can be HTML (GitHub provider) so convert if needed
|
||||
const versionHeader = item.version ? `## ${item.version}\n` : '';
|
||||
return `${versionHeader}${item.note}`;
|
||||
const note = typeof item.note === 'string' && item.note.trimStart().startsWith('<')
|
||||
? htmlToMarkdown(item.note)
|
||||
: item.note;
|
||||
return `${versionHeader}${note}`;
|
||||
})
|
||||
.join('\n\n');
|
||||
|
||||
|
||||
@@ -20,8 +20,10 @@ import type {
|
||||
ClaudeProfileSettings,
|
||||
ClaudeUsageData,
|
||||
ClaudeRateLimitEvent,
|
||||
ClaudeAutoSwitchSettings
|
||||
ClaudeAutoSwitchSettings,
|
||||
APIProfile
|
||||
} from '../shared/types';
|
||||
import type { UnifiedAccount } from '../shared/types/unified-account';
|
||||
|
||||
// Module imports
|
||||
import { encryptToken, decryptToken } from './claude-profile/token-encryption';
|
||||
@@ -40,9 +42,11 @@ import {
|
||||
import {
|
||||
getBestAvailableProfile,
|
||||
shouldProactivelySwitch as shouldProactivelySwitchImpl,
|
||||
getProfilesSortedByAvailability as getProfilesSortedByAvailabilityImpl
|
||||
getProfilesSortedByAvailability as getProfilesSortedByAvailabilityImpl,
|
||||
getBestAvailableUnifiedAccount
|
||||
} from './claude-profile/profile-scorer';
|
||||
import { getCredentialsFromKeychain, normalizeWindowsPath, updateProfileSubscriptionMetadata } from './claude-profile/credential-utils';
|
||||
import { loadProfilesFile } from './services/profile/profile-manager';
|
||||
import {
|
||||
CLAUDE_PROFILES_DIR,
|
||||
generateProfileId as generateProfileIdImpl,
|
||||
@@ -666,6 +670,57 @@ export class ClaudeProfileManager {
|
||||
return getBestAvailableProfile(this.data.profiles, settings, excludeProfileId, priorityOrder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load API profiles from profiles.json with error handling
|
||||
* Shared helper to avoid duplication across methods
|
||||
*/
|
||||
private async loadProfilesFileSafe(): Promise<{ profiles: APIProfile[]; activeProfileId?: string }> {
|
||||
try {
|
||||
const file = await loadProfilesFile();
|
||||
return { profiles: file.profiles, activeProfileId: file.activeProfileId ?? undefined };
|
||||
} catch (error) {
|
||||
console.error('[ClaudeProfileManager] Failed to load profiles file:', error);
|
||||
return { profiles: [] };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load API profiles from profiles.json
|
||||
* Used by the unified account selection to consider API profiles as fallback
|
||||
*/
|
||||
async loadAPIProfiles(): Promise<APIProfile[]> {
|
||||
const { profiles } = await this.loadProfilesFileSafe();
|
||||
return profiles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the best available unified account from both OAuth and API profiles
|
||||
* This enables cross-type account switching when OAuth profiles are exhausted
|
||||
*
|
||||
* @param excludeAccountId - Unified account ID to exclude (e.g., 'oauth-profile1')
|
||||
* @returns The best available UnifiedAccount, or null if none available
|
||||
*/
|
||||
async getBestAvailableUnifiedAccount(excludeAccountId?: string): Promise<UnifiedAccount | null> {
|
||||
const settings = this.getAutoSwitchSettings();
|
||||
const priorityOrder = this.getAccountPriorityOrder();
|
||||
const activeOAuthId = this.data.activeProfileId;
|
||||
|
||||
// Load API profiles and active API profile ID from profiles.json
|
||||
const { profiles: apiProfiles, activeProfileId: activeAPIId } = await this.loadProfilesFileSafe();
|
||||
|
||||
return getBestAvailableUnifiedAccount(
|
||||
this.data.profiles,
|
||||
apiProfiles,
|
||||
settings,
|
||||
{
|
||||
excludeAccountId,
|
||||
priorityOrder,
|
||||
activeOAuthId,
|
||||
activeAPIId
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if we should proactively switch profiles based on current usage
|
||||
*/
|
||||
|
||||
@@ -10,9 +10,20 @@
|
||||
* - Must be below user's configured thresholds (default: 95% session, 99% weekly)
|
||||
* 3. First profile in priority order that passes all filters is selected
|
||||
* 4. If no profile passes all filters, falls back to "least bad" option
|
||||
*
|
||||
* v3 Enhancement: Unified Account Support
|
||||
* - Supports both OAuth profiles (ClaudeProfile) and API profiles (APIProfile)
|
||||
* - API profiles are always considered available (hasUnlimitedUsage = true)
|
||||
* - Unified selection algorithm considers both types in priority order
|
||||
*/
|
||||
|
||||
import type { ClaudeProfile, ClaudeAutoSwitchSettings } from '../../shared/types';
|
||||
import type { ClaudeProfile, ClaudeAutoSwitchSettings, APIProfile } from '../../shared/types';
|
||||
import type { UnifiedAccount } from '../../shared/types/unified-account';
|
||||
import {
|
||||
claudeProfileToUnified,
|
||||
apiProfileToUnified,
|
||||
OAUTH_ID_PREFIX
|
||||
} from '../../shared/utils/unified-account';
|
||||
import { isProfileRateLimited } from './rate-limit-manager';
|
||||
import { isProfileAuthenticated } from './profile-utils';
|
||||
|
||||
@@ -121,6 +132,236 @@ function calculateFallbackScore(
|
||||
return score;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Unified Account Scoring (v3)
|
||||
// ============================================
|
||||
|
||||
interface ScoredUnifiedAccount {
|
||||
account: UnifiedAccount;
|
||||
score: number;
|
||||
priorityIndex: number;
|
||||
isAvailable: boolean;
|
||||
unavailableReason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for unified account selection
|
||||
*/
|
||||
export interface UnifiedAccountSelectionOptions {
|
||||
/** Unified account ID to exclude (usually the current/failing one) */
|
||||
excludeAccountId?: string;
|
||||
/** User's configured priority order (array of unified IDs) */
|
||||
priorityOrder?: string[];
|
||||
/** Currently active OAuth profile ID (if any) */
|
||||
activeOAuthId?: string;
|
||||
/** Currently active API profile ID (if any) */
|
||||
activeAPIId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Score a single unified account for availability
|
||||
*
|
||||
* @param account - The unified account to score
|
||||
* @param priorityIndex - Index in the user's priority order (lower = higher priority)
|
||||
* @param settings - Auto-switch settings containing usage thresholds
|
||||
*/
|
||||
function scoreUnifiedAccount(
|
||||
account: UnifiedAccount,
|
||||
priorityIndex: number,
|
||||
settings: ClaudeAutoSwitchSettings
|
||||
): ScoredUnifiedAccount {
|
||||
let score = 100;
|
||||
let unavailableReason: string | undefined;
|
||||
let isOverThreshold = false;
|
||||
|
||||
// For API profiles: simple availability check
|
||||
if (account.type === 'api') {
|
||||
if (!account.isAuthenticated) {
|
||||
score = -1000;
|
||||
unavailableReason = 'API key not validated';
|
||||
} else if (!account.isAvailable) {
|
||||
score = -500;
|
||||
unavailableReason = 'not available';
|
||||
}
|
||||
// API profiles with valid auth get high scores (no usage limits)
|
||||
|
||||
return {
|
||||
account,
|
||||
score,
|
||||
priorityIndex,
|
||||
isAvailable: score > 0,
|
||||
unavailableReason
|
||||
};
|
||||
}
|
||||
|
||||
// For OAuth profiles: detailed scoring with threshold enforcement
|
||||
if (!account.isAuthenticated) {
|
||||
score = -1000;
|
||||
unavailableReason = 'not authenticated';
|
||||
} else if (account.isRateLimited) {
|
||||
if (account.rateLimitType === 'weekly') {
|
||||
score = -500;
|
||||
} else {
|
||||
score = -200;
|
||||
}
|
||||
unavailableReason = `rate limited (${account.rateLimitType || 'unknown'})`;
|
||||
} else {
|
||||
// Check usage thresholds (matching checkProfileAvailability behavior)
|
||||
if (account.weeklyPercent !== undefined && account.weeklyPercent >= settings.weeklyThreshold) {
|
||||
isOverThreshold = true;
|
||||
unavailableReason = `weekly usage ${account.weeklyPercent}% >= threshold ${settings.weeklyThreshold}%`;
|
||||
} else if (account.sessionPercent !== undefined && account.sessionPercent >= settings.sessionThreshold) {
|
||||
isOverThreshold = true;
|
||||
unavailableReason = `session usage ${account.sessionPercent}% >= threshold ${settings.sessionThreshold}%`;
|
||||
}
|
||||
|
||||
// Apply proportional penalties for high usage (even if not over threshold)
|
||||
if (account.weeklyPercent !== undefined) {
|
||||
score -= account.weeklyPercent * 0.3;
|
||||
}
|
||||
if (account.sessionPercent !== undefined) {
|
||||
score -= account.sessionPercent * 0.1;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
account,
|
||||
score,
|
||||
priorityIndex,
|
||||
isAvailable: score > 0 && account.isAuthenticated === true && !account.isRateLimited && !isOverThreshold,
|
||||
unavailableReason
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the best unified account from both OAuth and API profiles
|
||||
*
|
||||
* Selection Logic:
|
||||
* 1. Convert all profiles to UnifiedAccount format
|
||||
* 2. Sort by user's priority order
|
||||
* 3. Filter by availability
|
||||
* 4. Return first available account in priority order
|
||||
* 5. If none available, return the "least bad" option
|
||||
*
|
||||
* @param oauthProfiles - All OAuth (Claude) profiles
|
||||
* @param apiProfiles - All API profiles
|
||||
* @param settings - Auto-switch settings (contains thresholds for OAuth)
|
||||
* @param options - Optional configuration for selection
|
||||
*/
|
||||
export function getBestAvailableUnifiedAccount(
|
||||
oauthProfiles: ClaudeProfile[],
|
||||
apiProfiles: APIProfile[],
|
||||
settings: ClaudeAutoSwitchSettings,
|
||||
options: UnifiedAccountSelectionOptions = {}
|
||||
): UnifiedAccount | null {
|
||||
const { excludeAccountId, priorityOrder = [], activeOAuthId, activeAPIId } = options;
|
||||
// Convert all profiles to unified format
|
||||
const unifiedAccounts: UnifiedAccount[] = [];
|
||||
|
||||
// Convert OAuth profiles
|
||||
for (const profile of oauthProfiles) {
|
||||
const isActive = profile.id === activeOAuthId;
|
||||
const rateLimitStatus = isProfileRateLimited(profile);
|
||||
// Compute authentication status - profile.isAuthenticated may not be set on raw profiles
|
||||
const isAuthenticated = isProfileAuthenticated(profile);
|
||||
|
||||
unifiedAccounts.push(claudeProfileToUnified(profile, isActive, {
|
||||
isRateLimited: rateLimitStatus.limited,
|
||||
rateLimitType: rateLimitStatus.type,
|
||||
isAuthenticated
|
||||
}));
|
||||
}
|
||||
|
||||
// Convert API profiles
|
||||
for (const profile of apiProfiles) {
|
||||
const isActive = profile.id === activeAPIId;
|
||||
// TODO: API profiles are considered authenticated if they have an API key.
|
||||
// Add validation tracking to distinguish "has key" from "key is confirmed valid".
|
||||
const isAuthenticated = !!profile.apiKey;
|
||||
unifiedAccounts.push(apiProfileToUnified(profile, isActive, isAuthenticated));
|
||||
}
|
||||
|
||||
// Filter out excluded account
|
||||
const candidates = unifiedAccounts.filter(a => a.id !== excludeAccountId);
|
||||
|
||||
if (candidates.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isDebug) {
|
||||
console.warn('[ProfileScorer] Evaluating', candidates.length, 'candidate accounts (excluding:', excludeAccountId, ')');
|
||||
console.warn('[ProfileScorer] Priority order:', priorityOrder);
|
||||
console.warn('[ProfileScorer] OAuth thresholds: session =', settings.sessionThreshold, '%, weekly =', settings.weeklyThreshold, '%');
|
||||
}
|
||||
|
||||
// Score and check availability for each account
|
||||
const scoredAccounts: ScoredUnifiedAccount[] = candidates.map(account => {
|
||||
const priorityIndex = priorityOrder.indexOf(account.id);
|
||||
const scored = scoreUnifiedAccount(account, priorityIndex === -1 ? Infinity : priorityIndex, settings);
|
||||
|
||||
if (isDebug) {
|
||||
console.warn('[ProfileScorer] Scoring account:', account.displayName, '(', account.id, ')');
|
||||
console.warn('[ProfileScorer] Type:', account.type);
|
||||
console.warn('[ProfileScorer] Priority index:', priorityIndex === -1 ? 'not in list (Infinity)' : priorityIndex);
|
||||
console.warn('[ProfileScorer] Available:', scored.isAvailable, scored.unavailableReason ? `(${scored.unavailableReason})` : '');
|
||||
if (account.type === 'oauth') {
|
||||
console.warn('[ProfileScorer] Usage:', `session=${account.sessionPercent}%, weekly=${account.weeklyPercent}%`);
|
||||
}
|
||||
console.warn('[ProfileScorer] Score:', scored.score);
|
||||
}
|
||||
|
||||
return scored;
|
||||
});
|
||||
|
||||
// Sort by:
|
||||
// 1. Available accounts first
|
||||
// 2. Within available: by priority index (lower = higher priority)
|
||||
// 3. Within unavailable: by score (higher = better, for "least bad" selection)
|
||||
scoredAccounts.sort((a, b) => {
|
||||
// Available accounts always come first
|
||||
if (a.isAvailable !== b.isAvailable) {
|
||||
return a.isAvailable ? -1 : 1;
|
||||
}
|
||||
|
||||
// For available accounts, sort by priority order
|
||||
if (a.isAvailable && b.isAvailable) {
|
||||
if (a.priorityIndex !== b.priorityIndex) {
|
||||
return a.priorityIndex - b.priorityIndex;
|
||||
}
|
||||
// Tiebreaker: prefer higher score
|
||||
return b.score - a.score;
|
||||
}
|
||||
|
||||
// For unavailable accounts, sort by score (for "least bad" selection)
|
||||
return b.score - a.score;
|
||||
});
|
||||
|
||||
const best = scoredAccounts[0];
|
||||
|
||||
if (best.isAvailable) {
|
||||
if (isDebug) {
|
||||
console.warn('[ProfileScorer] Best available account:', best.account.displayName,
|
||||
'(type:', best.account.type, ', priority index:', best.priorityIndex, ')');
|
||||
}
|
||||
return best.account;
|
||||
}
|
||||
|
||||
// No account meets all criteria - check if we should return the least bad option
|
||||
if (best.score > 0) {
|
||||
if (isDebug) {
|
||||
console.warn('[ProfileScorer] No ideal account available, using least-bad option:', best.account.displayName,
|
||||
'(type:', best.account.type, ', score:', best.score, ', reason:', best.unavailableReason, ')');
|
||||
}
|
||||
return best.account;
|
||||
}
|
||||
|
||||
// All accounts are truly unusable
|
||||
if (isDebug) {
|
||||
console.warn('[ProfileScorer] No usable account available, all have issues');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the best profile to switch to based on priority order and availability
|
||||
*
|
||||
@@ -157,7 +398,7 @@ export function getBestAvailableProfile(
|
||||
|
||||
// Score and check availability for each profile
|
||||
const scoredProfiles: ScoredProfile[] = candidates.map(profile => {
|
||||
const unifiedId = `oauth-${profile.id}`;
|
||||
const unifiedId = `${OAUTH_ID_PREFIX}${profile.id}`;
|
||||
const priorityIndex = priorityOrder.indexOf(unifiedId);
|
||||
const availability = checkProfileAvailability(profile, settings);
|
||||
const fallbackScore = calculateFallbackScore(profile, settings);
|
||||
|
||||
@@ -1961,14 +1961,17 @@ export class UsageMonitor extends EventEmitter {
|
||||
this.clearProfileUsageCache(currentProfileId);
|
||||
|
||||
// Switch to the new profile
|
||||
// Note: bestAccount.id is already the raw profile ID (not unified format)
|
||||
const rawProfileId = bestAccount.id;
|
||||
|
||||
if (bestAccount.type === 'oauth') {
|
||||
// Switch OAuth profile via profile manager
|
||||
profileManager.setActiveProfile(bestAccount.id);
|
||||
profileManager.setActiveProfile(rawProfileId);
|
||||
} else {
|
||||
// Switch API profile via profile-manager service
|
||||
try {
|
||||
const { setActiveAPIProfile } = await import('../services/profile/profile-manager');
|
||||
await setActiveAPIProfile(bestAccount.id);
|
||||
await setActiveAPIProfile(rawProfileId);
|
||||
} catch (error) {
|
||||
console.error('[UsageMonitor] Failed to set active API profile:', error);
|
||||
return;
|
||||
|
||||
@@ -36,6 +36,8 @@ import {
|
||||
buildRunnerArgs,
|
||||
} from "./utils/subprocess-runner";
|
||||
import { getPRStatusPoller } from "../../services/pr-status-poller";
|
||||
import { safeBreadcrumb, safeCaptureException } from "../../sentry";
|
||||
import { sanitizeForSentry } from "../../../shared/utils/sentry-privacy";
|
||||
import type {
|
||||
StartPollingRequest,
|
||||
StopPollingRequest,
|
||||
@@ -1462,6 +1464,20 @@ async function runPRReview(
|
||||
|
||||
debugLog("Spawning PR review process", { args, model, thinkingLevel });
|
||||
|
||||
safeBreadcrumb({
|
||||
category: 'pr-review',
|
||||
message: 'Spawning PR review subprocess',
|
||||
level: 'info',
|
||||
data: {
|
||||
pythonPath: getPythonPath(backendPath),
|
||||
runnerPath: getRunnerPath(backendPath),
|
||||
cwd: backendPath,
|
||||
model,
|
||||
thinkingLevel,
|
||||
prNumber,
|
||||
},
|
||||
});
|
||||
|
||||
// Create log collector for this review
|
||||
const config = getGitHubConfig(project);
|
||||
const repo = config?.repo || project.name || "unknown";
|
||||
@@ -1525,9 +1541,22 @@ async function runPRReview(
|
||||
// Wait for the process to complete
|
||||
const result = await promise;
|
||||
|
||||
safeBreadcrumb({
|
||||
category: 'pr-review',
|
||||
message: `PR review subprocess exited`,
|
||||
level: result.success ? 'info' : 'error',
|
||||
data: { exitCode: result.exitCode, success: result.success, prNumber },
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
// Finalize logs with failure
|
||||
logCollector.finalize(false);
|
||||
|
||||
safeCaptureException(
|
||||
new Error(`PR review subprocess failed: ${result.error ?? 'unknown error'}`),
|
||||
{ extra: { exitCode: result.exitCode, prNumber, stderr: sanitizeForSentry(result.stderr.slice(0, 500)) } }
|
||||
);
|
||||
|
||||
throw new Error(result.error ?? "Review failed");
|
||||
}
|
||||
|
||||
@@ -2907,6 +2936,20 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
|
||||
|
||||
debugLog("Spawning follow-up review process", { args, model, thinkingLevel });
|
||||
|
||||
safeBreadcrumb({
|
||||
category: 'pr-review',
|
||||
message: 'Spawning follow-up PR review subprocess',
|
||||
level: 'info',
|
||||
data: {
|
||||
pythonPath: getPythonPath(backendPath),
|
||||
runnerPath: getRunnerPath(backendPath),
|
||||
cwd: backendPath,
|
||||
model,
|
||||
thinkingLevel,
|
||||
prNumber,
|
||||
},
|
||||
});
|
||||
|
||||
// Create log collector for this follow-up review (config already declared above)
|
||||
const repo = config?.repo || project.name || "unknown";
|
||||
const logCollector = new PRLogCollector(project, prNumber, repo, true, mainWindow);
|
||||
@@ -2964,9 +3007,22 @@ export function registerPRHandlers(getMainWindow: () => BrowserWindow | null): v
|
||||
|
||||
const result = await promise;
|
||||
|
||||
safeBreadcrumb({
|
||||
category: 'pr-review',
|
||||
message: 'Follow-up PR review subprocess exited',
|
||||
level: result.success ? 'info' : 'error',
|
||||
data: { exitCode: result.exitCode, success: result.success, prNumber },
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
// Finalize logs with failure
|
||||
logCollector.finalize(false);
|
||||
|
||||
safeCaptureException(
|
||||
new Error(`Follow-up PR review subprocess failed: ${result.error ?? 'unknown error'}`),
|
||||
{ extra: { exitCode: result.exitCode, prNumber, stderr: sanitizeForSentry(result.stderr.slice(0, 500)) } }
|
||||
);
|
||||
|
||||
throw new Error(result.error ?? "Follow-up review failed");
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { getAPIProfileEnv } from '../../../services/profile';
|
||||
import { getBestAvailableProfileEnv } from '../../../rate-limit-detector';
|
||||
import { pythonEnvManager } from '../../../python-env-manager';
|
||||
import { getGitHubTokenForSubprocess } from '../utils';
|
||||
import { getSentryEnvForSubprocess } from '../../../sentry';
|
||||
|
||||
/**
|
||||
* Get environment variables for Python runner subprocesses.
|
||||
@@ -48,6 +49,7 @@ export async function getRunnerEnv(
|
||||
...oauthModeClearVars,
|
||||
...profileEnv, // OAuth token from profile manager (fixes #563, rate-limit aware)
|
||||
...githubEnv, // Fresh GitHub token from gh CLI (fixes #151)
|
||||
...extraEnv,
|
||||
...getSentryEnvForSubprocess(), // Sentry DSN + sample rates for Python subprocess
|
||||
...extraEnv, // extraEnv last so callers can still override
|
||||
};
|
||||
}
|
||||
|
||||
@@ -9,12 +9,7 @@ import { spawn, exec, execFile } from 'child_process';
|
||||
import type { ChildProcess } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import fs from 'fs';
|
||||
|
||||
// ESM-compatible __dirname
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
import type { Project } from '../../../../shared/types';
|
||||
import type { AuthFailureInfo, BillingFailureInfo } from '../../../../shared/types/terminal';
|
||||
import { parsePythonCommand } from '../../../python-detector';
|
||||
@@ -22,7 +17,10 @@ import { detectAuthFailure, detectBillingFailure } from '../../../rate-limit-det
|
||||
import { getClaudeProfileManager } from '../../../claude-profile-manager';
|
||||
import { getOperationRegistry, type OperationType } from '../../../claude-profile/operation-registry';
|
||||
import { isWindows, isMacOS } from '../../../platform';
|
||||
import { getEffectiveSourcePath } from '../../../updater/path-resolver';
|
||||
import { pythonEnvManager, getConfiguredPythonPath } from '../../../python-env-manager';
|
||||
import { getTaskkillExePath, getWhereExePath } from '../../../utils/windows-paths';
|
||||
import { safeCaptureException } from '../../../sentry';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
const execFileAsync = promisify(execFile);
|
||||
@@ -217,6 +215,17 @@ export function runPythonSubprocess<T = unknown>(
|
||||
let killedDueToAuthFailure = false; // Track if subprocess was killed due to auth failure
|
||||
let billingFailureEmitted = false; // Track if we've already emitted a billing failure
|
||||
let killedDueToBillingFailure = false; // Track if subprocess was killed due to billing failure
|
||||
let receivedOutput = false; // Track if any stdout/stderr has been received
|
||||
|
||||
// Health-check: report to Sentry if no output received within 120 seconds
|
||||
const healthCheckTimeout = setTimeout(() => {
|
||||
if (!receivedOutput) {
|
||||
safeCaptureException(
|
||||
new Error('[SubprocessRunner] No output received from subprocess after 120s'),
|
||||
{ extra: { pythonPath: options.pythonPath, args: options.args, cwd: options.cwd, envKeys: options.env ? Object.keys(options.env) : [] } }
|
||||
);
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
// Default progress pattern: [ 30%] message OR [30%] message
|
||||
const progressPattern = options.progressPattern ?? /\[\s*(\d+)%\]\s*(.+)/;
|
||||
@@ -340,6 +349,7 @@ export function runPythonSubprocess<T = unknown>(
|
||||
};
|
||||
|
||||
child.stdout.on('data', (data: Buffer) => {
|
||||
receivedOutput = true;
|
||||
const text = data.toString('utf-8');
|
||||
stdout += text;
|
||||
|
||||
@@ -367,6 +377,7 @@ export function runPythonSubprocess<T = unknown>(
|
||||
});
|
||||
|
||||
child.stderr.on('data', (data: Buffer) => {
|
||||
receivedOutput = true;
|
||||
const text = data.toString('utf-8');
|
||||
stderr += text;
|
||||
|
||||
@@ -385,6 +396,7 @@ export function runPythonSubprocess<T = unknown>(
|
||||
});
|
||||
|
||||
child.on('close', (code: number | null) => {
|
||||
clearTimeout(healthCheckTimeout);
|
||||
// Treat null exit code (killed with SIGKILL) as failure, not success
|
||||
const exitCode = code ?? -1;
|
||||
|
||||
@@ -464,6 +476,7 @@ export function runPythonSubprocess<T = unknown>(
|
||||
});
|
||||
|
||||
child.on('error', (err: Error) => {
|
||||
clearTimeout(healthCheckTimeout);
|
||||
options.onError?.(err.message);
|
||||
resolve({
|
||||
success: false,
|
||||
@@ -479,10 +492,20 @@ export function runPythonSubprocess<T = unknown>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Python path for a project's backend
|
||||
* Cross-platform: uses Scripts/python.exe on Windows, bin/python on Unix
|
||||
* Get the Python path for running GitHub runners.
|
||||
*
|
||||
* Prefers the managed Python environment (bundled app venv) when ready,
|
||||
* falls back to project-local .venv for development repos.
|
||||
*/
|
||||
export function getPythonPath(backendPath: string): string {
|
||||
// Use managed env when it's fully set up (has dependencies installed)
|
||||
if (pythonEnvManager.isEnvReady()) {
|
||||
const managed = getConfiguredPythonPath();
|
||||
if (fs.existsSync(managed)) {
|
||||
return managed;
|
||||
}
|
||||
}
|
||||
// Fallback to venv in backend path (dev mode)
|
||||
return isWindows()
|
||||
? path.join(backendPath, '.venv', 'Scripts', 'python.exe')
|
||||
: path.join(backendPath, '.venv', 'bin', 'python');
|
||||
@@ -498,44 +521,30 @@ export function getRunnerPath(backendPath: string): string {
|
||||
/**
|
||||
* Get the auto-claude backend path for a project
|
||||
*
|
||||
* Auto-detects the backend location using multiple strategies:
|
||||
* 1. Development repo structure (apps/backend)
|
||||
* 2. Electron app bundle location
|
||||
* 3. Current working directory
|
||||
* Uses getEffectiveSourcePath() which handles:
|
||||
* 1. User settings (autoBuildPath)
|
||||
* 2. userData override (backend-source) for user-updated backend
|
||||
* 3. Bundled backend (process.resourcesPath/backend)
|
||||
* 4. Development paths
|
||||
* Falls back to project.path/apps/backend for development repos.
|
||||
*/
|
||||
export function getBackendPath(project: Project): string | null {
|
||||
// Import app module for production path detection
|
||||
let app: any;
|
||||
try {
|
||||
app = require('electron').app;
|
||||
} catch {
|
||||
// Electron not available in tests
|
||||
// Use shared path resolver which handles:
|
||||
// 1. User settings (autoBuildPath)
|
||||
// 2. userData override (backend-source) for user-updated backend
|
||||
// 3. Bundled backend (process.resourcesPath/backend)
|
||||
// 4. Development paths
|
||||
const effectivePath = getEffectiveSourcePath();
|
||||
if (fs.existsSync(effectivePath) && fs.existsSync(path.join(effectivePath, 'runners', 'github', 'runner.py'))) {
|
||||
return effectivePath;
|
||||
}
|
||||
|
||||
// Check if this is a development repo (has apps/backend structure)
|
||||
// Fallback: check project path for development repo structure
|
||||
const appsBackendPath = path.join(project.path, 'apps', 'backend');
|
||||
if (fs.existsSync(path.join(appsBackendPath, 'runners', 'github', 'runner.py'))) {
|
||||
return appsBackendPath;
|
||||
}
|
||||
|
||||
// Auto-detect from app location (same logic as agent-process.ts)
|
||||
const possiblePaths = [
|
||||
// Dev mode: from dist/main -> ../../backend (apps/frontend/out/main -> apps/backend)
|
||||
path.resolve(__dirname, '..', '..', '..', '..', '..', 'backend'),
|
||||
// Alternative: from app root -> apps/backend
|
||||
app ? path.resolve(app.getAppPath(), '..', 'backend') : null,
|
||||
// If running from repo root with apps structure
|
||||
path.resolve(process.cwd(), 'apps', 'backend'),
|
||||
].filter((p): p is string => p !== null);
|
||||
|
||||
for (const backendPath of possiblePaths) {
|
||||
// Check for runner.py as marker
|
||||
const runnerPath = path.join(backendPath, 'runners', 'github', 'runner.py');
|
||||
if (fs.existsSync(runnerPath)) {
|
||||
return backendPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,12 +3,17 @@
|
||||
*
|
||||
* Handles IPC communication for the rate limit recovery queue routing system.
|
||||
* Provides profile-aware task distribution to enable overnight autonomous operation.
|
||||
*
|
||||
* v3 Enhancement: Unified Account Support
|
||||
* - Supports both OAuth profiles and API profiles in unified selection
|
||||
* - New QUEUE_GET_BEST_UNIFIED_ACCOUNT handler for cross-type account switching
|
||||
*/
|
||||
|
||||
import { ipcMain, BrowserWindow } from 'electron';
|
||||
import { IPC_CHANNELS } from '../../shared/constants';
|
||||
import type { AgentManager } from '../agent/agent-manager';
|
||||
import type { ProfileAssignmentReason, RunningTasksByProfile, ClaudeProfile } from '../../shared/types';
|
||||
import type { UnifiedAccount } from '../../shared/types/unified-account';
|
||||
import type { ClaudeProfileManager } from '../claude-profile-manager';
|
||||
|
||||
/**
|
||||
@@ -93,6 +98,61 @@ export function registerQueueRoutingHandlers(
|
||||
}
|
||||
);
|
||||
|
||||
// Get best unified account for a task (OAuth + API profiles)
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.QUEUE_GET_BEST_UNIFIED_ACCOUNT,
|
||||
async (
|
||||
_event,
|
||||
options?: {
|
||||
excludeAccountId?: string;
|
||||
}
|
||||
): Promise<{ success: boolean; data?: UnifiedAccount | null; error?: string }> => {
|
||||
try {
|
||||
// If no profile manager is available, return null (no preference)
|
||||
if (!profileManager) {
|
||||
console.log('[QueueRouting] Profile manager not available, returning null');
|
||||
return { success: true, data: null };
|
||||
}
|
||||
|
||||
// Get auto-switch settings to check if enabled
|
||||
const settings = profileManager.getAutoSwitchSettings();
|
||||
|
||||
// If auto-switching is disabled, return null (no preference)
|
||||
if (!settings.enabled) {
|
||||
console.log('[QueueRouting] Auto-switching disabled, returning null');
|
||||
return { success: true, data: null };
|
||||
}
|
||||
|
||||
// Use getBestAvailableUnifiedAccount which handles:
|
||||
// - User's configured priority order
|
||||
// - OAuth profiles (with usage thresholds)
|
||||
// - API profiles (always available if authenticated)
|
||||
const bestAccount = await profileManager.getBestAvailableUnifiedAccount(
|
||||
options?.excludeAccountId
|
||||
);
|
||||
|
||||
if (bestAccount) {
|
||||
console.log('[QueueRouting] Best unified account selected:', {
|
||||
accountId: bestAccount.id,
|
||||
accountName: bestAccount.displayName,
|
||||
accountType: bestAccount.type,
|
||||
excludedId: options?.excludeAccountId
|
||||
});
|
||||
} else {
|
||||
console.log('[QueueRouting] No suitable unified account found for task routing');
|
||||
}
|
||||
|
||||
return { success: true, data: bestAccount };
|
||||
} catch (error) {
|
||||
console.error('[QueueRouting] Failed to get best unified account for task:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Assign a profile to a task
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.QUEUE_ASSIGN_PROFILE_TO_TASK,
|
||||
|
||||
@@ -27,32 +27,7 @@ import { AgentManager } from "../agent";
|
||||
import { debugLog, debugError } from "../../shared/utils/debug-logger";
|
||||
import { safeSendToRenderer } from "./utils";
|
||||
import { writeFileWithRetry, readFileWithRetry } from "../utils/atomic-file";
|
||||
|
||||
/**
|
||||
* Simple in-process file lock to serialize read-modify-write operations.
|
||||
* Prevents concurrent IPC calls from causing lost updates on the same file.
|
||||
*/
|
||||
const fileLocks = new Map<string, Promise<void>>();
|
||||
|
||||
async function withFileLock<T>(filepath: string, fn: () => Promise<T>): Promise<T> {
|
||||
// Wait for any existing lock on this file
|
||||
while (fileLocks.has(filepath)) {
|
||||
await fileLocks.get(filepath);
|
||||
}
|
||||
|
||||
let resolve: (() => void) | undefined;
|
||||
const lockPromise = new Promise<void>((r) => {
|
||||
resolve = r;
|
||||
});
|
||||
fileLocks.set(filepath, lockPromise);
|
||||
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
fileLocks.delete(filepath);
|
||||
resolve?.();
|
||||
}
|
||||
}
|
||||
import { withFileLock } from "../utils/file-lock";
|
||||
|
||||
/**
|
||||
* Read feature settings from the settings file
|
||||
@@ -221,6 +196,8 @@ export function registerRoadmapHandlers(
|
||||
acceptanceCriteria: feature.acceptance_criteria || [],
|
||||
userStories: feature.user_stories || [],
|
||||
linkedSpecId: feature.linked_spec_id,
|
||||
taskOutcome: feature.task_outcome,
|
||||
previousStatus: feature.previous_status,
|
||||
competitorInsightIds: (feature.competitor_insight_ids as string[]) || undefined,
|
||||
})),
|
||||
status: rawRoadmap.status || "draft",
|
||||
@@ -432,6 +409,8 @@ export function registerRoadmapHandlers(
|
||||
acceptance_criteria: feature.acceptanceCriteria || [],
|
||||
user_stories: feature.userStories || [],
|
||||
linked_spec_id: feature.linkedSpecId,
|
||||
task_outcome: feature.taskOutcome,
|
||||
previous_status: feature.previousStatus,
|
||||
competitor_insight_ids: feature.competitorInsightIds,
|
||||
}));
|
||||
|
||||
@@ -491,6 +470,10 @@ export function registerRoadmapHandlers(
|
||||
}
|
||||
|
||||
feature.status = status;
|
||||
if (status !== 'done') {
|
||||
delete feature.task_outcome;
|
||||
delete feature.previous_status;
|
||||
}
|
||||
roadmap.metadata = roadmap.metadata || {};
|
||||
roadmap.metadata.updated_at = new Date().toISOString();
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { ipcMain, nativeImage } from 'electron';
|
||||
import { IPC_CHANNELS, AUTO_BUILD_PATHS, getSpecsDir, VALID_THINKING_LEVELS, sanitizeThinkingLevel } from '../../../shared/constants';
|
||||
import type { IPCResult, Task, TaskMetadata } from '../../../shared/types';
|
||||
import type { IPCResult, Task, TaskMetadata, TaskOutcome } from '../../../shared/types';
|
||||
import path from 'path';
|
||||
import { execFileSync } from 'child_process';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, Dirent } from 'fs';
|
||||
import { updateRoadmapFeatureOutcome } from '../../utils/roadmap-utils';
|
||||
import { projectStore } from '../../project-store';
|
||||
import { titleGenerator } from '../../title-generator';
|
||||
import { AgentManager } from '../../agent';
|
||||
@@ -103,6 +104,19 @@ function truncateToTitle(description: string): string {
|
||||
return title;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a linked roadmap feature when a task is deleted.
|
||||
* Delegates to shared utility with file locking and retry.
|
||||
*/
|
||||
async function updateLinkedRoadmapFeature(
|
||||
projectPath: string,
|
||||
specId: string,
|
||||
taskOutcome: TaskOutcome
|
||||
): Promise<void> {
|
||||
const roadmapFile = path.join(projectPath, AUTO_BUILD_PATHS.ROADMAP_DIR, AUTO_BUILD_PATHS.ROADMAP_FILE);
|
||||
await updateRoadmapFeatureOutcome(roadmapFile, [specId], taskOutcome, '[TASK_CRUD]');
|
||||
}
|
||||
|
||||
/**
|
||||
* Register task CRUD (Create, Read, Update, Delete) handlers
|
||||
*/
|
||||
@@ -411,6 +425,13 @@ export function registerTaskCRUDHandlers(agentManager: AgentManager): void {
|
||||
};
|
||||
}
|
||||
|
||||
// Update any linked roadmap feature (only after successful deletion)
|
||||
try {
|
||||
await updateLinkedRoadmapFeature(project.path, task.specId, 'deleted');
|
||||
} catch (err) {
|
||||
console.warn('[TASK_DELETE] Failed to update linked roadmap feature:', err);
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { getConfiguredPythonPath, PythonEnvManager, pythonEnvManager as pythonEn
|
||||
import { getEffectiveSourcePath } from '../../updater/path-resolver';
|
||||
import { getBestAvailableProfileEnv } from '../../rate-limit-detector';
|
||||
import { findTaskAndProject } from './shared';
|
||||
import { updateRoadmapFeatureOutcome } from '../../utils/roadmap-utils';
|
||||
import { parsePythonCommand } from '../../python-detector';
|
||||
import { getToolPath } from '../../cli-tool-manager';
|
||||
import { promisify } from 'util';
|
||||
@@ -3351,6 +3352,14 @@ export function registerWorktreeHandlers(
|
||||
task.specId,
|
||||
debug
|
||||
);
|
||||
|
||||
// Update linked roadmap feature on backend (complements renderer-side handling)
|
||||
if (project.path && task.specId) {
|
||||
const roadmapFile = path.join(project.path, AUTO_BUILD_PATHS.ROADMAP_DIR, AUTO_BUILD_PATHS.ROADMAP_FILE);
|
||||
updateRoadmapFeatureOutcome(roadmapFile, [task.specId], 'completed', '[PR_CREATE]').catch((err) => {
|
||||
debug('Failed to update roadmap feature after PR creation:', err);
|
||||
});
|
||||
}
|
||||
} else if (result.alreadyExists) {
|
||||
debug('PR already exists, not updating task status');
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { getTaskWorktreeDir } from './worktree-paths';
|
||||
import { findAllSpecPaths } from './utils/spec-path-helpers';
|
||||
import { ensureAbsolutePath } from './utils/path-helpers';
|
||||
import { writeFileAtomicSync } from './utils/atomic-file';
|
||||
import { updateRoadmapFeatureOutcome, revertRoadmapFeatureOutcome } from './utils/roadmap-utils';
|
||||
|
||||
interface TabState {
|
||||
openProjectIds: string[];
|
||||
@@ -809,12 +810,25 @@ export class ProjectStore {
|
||||
}
|
||||
}
|
||||
|
||||
// Update linked roadmap features for archived tasks
|
||||
this.updateRoadmapForArchivedTasks(project, taskIds);
|
||||
|
||||
// Invalidate cache since task metadata changed
|
||||
this.invalidateTasksCache(projectId);
|
||||
|
||||
return !hasErrors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update roadmap features linked to archived tasks
|
||||
*/
|
||||
private updateRoadmapForArchivedTasks(project: Project, taskIds: string[]): void {
|
||||
const roadmapFile = path.join(project.path, AUTO_BUILD_PATHS.ROADMAP_DIR, AUTO_BUILD_PATHS.ROADMAP_FILE);
|
||||
updateRoadmapFeatureOutcome(roadmapFile, taskIds, 'archived', '[ProjectStore]').catch((err) => {
|
||||
console.warn('[ProjectStore] Failed to update roadmap for archived tasks:', err);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Unarchive tasks by removing archivedAt from their metadata
|
||||
* @param projectId - Project ID
|
||||
@@ -867,6 +881,12 @@ export class ProjectStore {
|
||||
}
|
||||
}
|
||||
|
||||
// Revert linked roadmap features from 'archived' back to 'in_progress'
|
||||
const roadmapFile = path.join(project.path, AUTO_BUILD_PATHS.ROADMAP_DIR, AUTO_BUILD_PATHS.ROADMAP_FILE);
|
||||
revertRoadmapFeatureOutcome(roadmapFile, taskIds, '[ProjectStore]').catch((err) => {
|
||||
console.warn('[ProjectStore] Failed to revert roadmap for unarchived tasks:', err);
|
||||
});
|
||||
|
||||
// Invalidate cache since task metadata changed
|
||||
this.invalidateTasksCache(projectId);
|
||||
|
||||
|
||||
@@ -753,6 +753,8 @@ if sys.version_info >= (3, 12):
|
||||
...windowsEnv,
|
||||
// Don't write bytecode - not needed and avoids permission issues
|
||||
PYTHONDONTWRITEBYTECODE: '1',
|
||||
// Force unbuffered stdout/stderr so progress updates reach Electron immediately
|
||||
PYTHONUNBUFFERED: '1',
|
||||
// Use UTF-8 encoding
|
||||
PYTHONIOENCODING: 'utf-8',
|
||||
PYTHONUTF8: '1',
|
||||
|
||||
@@ -222,7 +222,5 @@ export function getSentryEnvForSubprocess(): Record<string, string> {
|
||||
SENTRY_DSN: dsn,
|
||||
SENTRY_TRACES_SAMPLE_RATE: String(getTracesSampleRate()),
|
||||
SENTRY_PROFILES_SAMPLE_RATE: String(getProfilesSampleRate()),
|
||||
// Pass SENTRY_DEV so Python backend also enables Sentry in dev mode
|
||||
...(process.env.SENTRY_DEV ? { SENTRY_DEV: process.env.SENTRY_DEV } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* In-process file lock for serializing read-modify-write operations.
|
||||
* Prevents concurrent IPC calls from causing lost updates on the same file.
|
||||
*
|
||||
* Shared across all modules to ensure a single lock map coordinates access.
|
||||
*/
|
||||
|
||||
const fileLocks = new Map<string, Promise<void>>();
|
||||
|
||||
export async function withFileLock<T>(filepath: string, fn: () => Promise<T>): Promise<T> {
|
||||
while (fileLocks.has(filepath)) {
|
||||
await fileLocks.get(filepath);
|
||||
}
|
||||
|
||||
let resolve: (() => void) | undefined;
|
||||
const lockPromise = new Promise<void>((r) => {
|
||||
resolve = r;
|
||||
});
|
||||
fileLocks.set(filepath, lockPromise);
|
||||
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
fileLocks.delete(filepath);
|
||||
resolve?.();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* Shared roadmap file utilities for updating feature outcomes.
|
||||
*
|
||||
* Used by task deletion (crud-handlers.ts) and archival (project-store.ts)
|
||||
* to update linked roadmap features when tasks change state.
|
||||
*/
|
||||
|
||||
import { existsSync } from 'fs';
|
||||
import { readFileWithRetry, writeFileWithRetry } from './atomic-file';
|
||||
import { withFileLock } from './file-lock';
|
||||
import type { TaskOutcome } from '../../shared/types/roadmap';
|
||||
|
||||
/**
|
||||
* Update roadmap features on disk when linked tasks change state.
|
||||
*
|
||||
* Finds features matching the given specIds and sets their status to 'done'
|
||||
* with the specified taskOutcome. Uses file locking and retry logic to
|
||||
* prevent concurrent write races.
|
||||
*
|
||||
* @param roadmapFile - Absolute path to roadmap.json
|
||||
* @param specIds - Spec IDs to match against feature.linked_spec_id / linkedSpecId
|
||||
* @param taskOutcome - The outcome to set on matched features
|
||||
* @param logPrefix - Prefix for log messages (e.g., '[TASK_CRUD]')
|
||||
*/
|
||||
export async function updateRoadmapFeatureOutcome(
|
||||
roadmapFile: string,
|
||||
specIds: string[],
|
||||
taskOutcome: TaskOutcome,
|
||||
logPrefix = '[Roadmap]'
|
||||
): Promise<void> {
|
||||
if (!existsSync(roadmapFile)) return;
|
||||
|
||||
const specIdSet = new Set(specIds);
|
||||
|
||||
await withFileLock(roadmapFile, async () => {
|
||||
try {
|
||||
const content = await readFileWithRetry(roadmapFile, { encoding: 'utf-8' });
|
||||
const roadmap = JSON.parse(content as string);
|
||||
|
||||
if (!roadmap.features || !Array.isArray(roadmap.features)) return;
|
||||
|
||||
let changed = false;
|
||||
for (const feature of roadmap.features) {
|
||||
const linkedId = feature.linked_spec_id || feature.linkedSpecId;
|
||||
if (linkedId && specIdSet.has(linkedId) && (feature.status !== 'done' || feature.task_outcome !== taskOutcome)) {
|
||||
if (feature.status !== 'done') {
|
||||
feature.previous_status = feature.status;
|
||||
}
|
||||
feature.status = 'done';
|
||||
feature.task_outcome = taskOutcome;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
roadmap.metadata = roadmap.metadata || {};
|
||||
roadmap.metadata.updated_at = new Date().toISOString();
|
||||
await writeFileWithRetry(roadmapFile, JSON.stringify(roadmap, null, 2));
|
||||
console.log(`${logPrefix} Updated roadmap features for ${specIds.length} task(s) with outcome: ${taskOutcome}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(`${logPrefix} Failed to update roadmap for tasks [${specIds.join(', ')}]:`, err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Revert roadmap features when a task is unarchived.
|
||||
*
|
||||
* Finds features matching the given specIds that have taskOutcome='archived',
|
||||
* resets their status to 'in_progress' and removes taskOutcome.
|
||||
*/
|
||||
export async function revertRoadmapFeatureOutcome(
|
||||
roadmapFile: string,
|
||||
specIds: string[],
|
||||
logPrefix = '[Roadmap]'
|
||||
): Promise<void> {
|
||||
if (!existsSync(roadmapFile)) return;
|
||||
|
||||
const specIdSet = new Set(specIds);
|
||||
|
||||
await withFileLock(roadmapFile, async () => {
|
||||
try {
|
||||
const content = await readFileWithRetry(roadmapFile, { encoding: 'utf-8' });
|
||||
const roadmap = JSON.parse(content as string);
|
||||
|
||||
if (!roadmap.features || !Array.isArray(roadmap.features)) return;
|
||||
|
||||
let changed = false;
|
||||
for (const feature of roadmap.features) {
|
||||
const linkedId = feature.linked_spec_id || feature.linkedSpecId;
|
||||
if (linkedId && specIdSet.has(linkedId) && feature.task_outcome === 'archived') {
|
||||
feature.status = feature.previous_status || 'in_progress';
|
||||
delete feature.task_outcome;
|
||||
delete feature.previous_status;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
roadmap.metadata = roadmap.metadata || {};
|
||||
roadmap.metadata.updated_at = new Date().toISOString();
|
||||
await writeFileWithRetry(roadmapFile, JSON.stringify(roadmap, null, 2));
|
||||
console.log(`${logPrefix} Reverted roadmap features for ${specIds.length} unarchived task(s)`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(`${logPrefix} Failed to revert roadmap for tasks [${specIds.join(', ')}]:`, err);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
import { ipcRenderer } from 'electron';
|
||||
import { IPC_CHANNELS } from '../../../shared/constants/ipc';
|
||||
import type { IPCResult } from '../../../shared/types/common';
|
||||
import type { IPCResult } from '@auto-claude/types';
|
||||
import type { CustomMcpServer, McpHealthCheckResult, McpTestConnectionResult } from '../../../shared/types/project';
|
||||
|
||||
export interface McpAPI {
|
||||
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
ProfileAssignmentReason,
|
||||
ProfileSwapRecord,
|
||||
} from '../../shared/types';
|
||||
import type { UnifiedAccount } from '../../shared/types/unified-account';
|
||||
|
||||
/**
|
||||
* Result of best profile selection for a task
|
||||
@@ -37,6 +38,14 @@ export interface GetBestProfileOptions {
|
||||
profileThreshold?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for getting the best unified account for a task
|
||||
*/
|
||||
export interface GetBestUnifiedAccountOptions {
|
||||
/** Unified account ID to exclude (e.g., 'oauth-profile1' or 'api-profile2') */
|
||||
excludeAccountId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Profile swap notification event payload
|
||||
*/
|
||||
@@ -68,6 +77,13 @@ export interface QueueAPI {
|
||||
*/
|
||||
getBestProfileForTask: (options?: GetBestProfileOptions) => Promise<IPCResult<BestProfileResult | null>>;
|
||||
|
||||
/**
|
||||
* Get the best available unified account for a new task
|
||||
* Considers both OAuth profiles and API profiles in unified selection
|
||||
* Used for cross-type account switching when OAuth profiles are exhausted
|
||||
*/
|
||||
getBestUnifiedAccount: (options?: GetBestUnifiedAccountOptions) => Promise<IPCResult<UnifiedAccount | null>>;
|
||||
|
||||
/**
|
||||
* Assign a profile to a task
|
||||
* Called when a task is started or when profile is swapped
|
||||
@@ -118,6 +134,9 @@ export const createQueueAPI = (): QueueAPI => ({
|
||||
getBestProfileForTask: (options?: GetBestProfileOptions): Promise<IPCResult<BestProfileResult | null>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.QUEUE_GET_BEST_PROFILE_FOR_TASK, options),
|
||||
|
||||
getBestUnifiedAccount: (options?: GetBestUnifiedAccountOptions): Promise<IPCResult<UnifiedAccount | null>> =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.QUEUE_GET_BEST_UNIFIED_ACCOUNT, options),
|
||||
|
||||
assignProfileToTask: (
|
||||
taskId: string,
|
||||
profileId: string,
|
||||
|
||||
@@ -499,6 +499,113 @@ describe('Roadmap Store', () => {
|
||||
const state = useRoadmapStore.getState();
|
||||
expect(state.roadmap?.features[0].status).toBe('in_progress');
|
||||
});
|
||||
|
||||
it('should clear taskOutcome and previousStatus when moving away from done', () => {
|
||||
const features = [createTestFeature({
|
||||
id: 'feature-1',
|
||||
status: 'done' as RoadmapFeatureStatus,
|
||||
taskOutcome: 'completed',
|
||||
previousStatus: 'in_progress' as RoadmapFeatureStatus
|
||||
})];
|
||||
const roadmap = createTestRoadmap({ features });
|
||||
|
||||
useRoadmapStore.setState({ roadmap });
|
||||
|
||||
useRoadmapStore.getState().updateFeatureStatus('feature-1', 'in_progress');
|
||||
|
||||
const state = useRoadmapStore.getState();
|
||||
expect(state.roadmap?.features[0].status).toBe('in_progress');
|
||||
expect(state.roadmap?.features[0].taskOutcome).toBeUndefined();
|
||||
expect(state.roadmap?.features[0].previousStatus).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should preserve taskOutcome when status remains done', () => {
|
||||
const features = [createTestFeature({
|
||||
id: 'feature-1',
|
||||
status: 'done' as RoadmapFeatureStatus,
|
||||
taskOutcome: 'completed'
|
||||
})];
|
||||
const roadmap = createTestRoadmap({ features });
|
||||
|
||||
useRoadmapStore.setState({ roadmap });
|
||||
|
||||
useRoadmapStore.getState().updateFeatureStatus('feature-1', 'done');
|
||||
|
||||
const state = useRoadmapStore.getState();
|
||||
expect(state.roadmap?.features[0].taskOutcome).toBe('completed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('markFeatureDoneBySpecId', () => {
|
||||
it('should mark feature as done with taskOutcome', () => {
|
||||
const features = [createTestFeature({
|
||||
id: 'feature-1',
|
||||
linkedSpecId: 'spec-001',
|
||||
status: 'in_progress' as RoadmapFeatureStatus
|
||||
})];
|
||||
const roadmap = createTestRoadmap({ features });
|
||||
|
||||
useRoadmapStore.setState({ roadmap });
|
||||
|
||||
useRoadmapStore.getState().markFeatureDoneBySpecId('spec-001', 'completed');
|
||||
|
||||
const state = useRoadmapStore.getState();
|
||||
expect(state.roadmap?.features[0].status).toBe('done');
|
||||
expect(state.roadmap?.features[0].taskOutcome).toBe('completed');
|
||||
});
|
||||
|
||||
it('should preserve previousStatus before overwriting to done', () => {
|
||||
const features = [createTestFeature({
|
||||
id: 'feature-1',
|
||||
linkedSpecId: 'spec-001',
|
||||
status: 'planned' as RoadmapFeatureStatus
|
||||
})];
|
||||
const roadmap = createTestRoadmap({ features });
|
||||
|
||||
useRoadmapStore.setState({ roadmap });
|
||||
|
||||
useRoadmapStore.getState().markFeatureDoneBySpecId('spec-001', 'archived');
|
||||
|
||||
const state = useRoadmapStore.getState();
|
||||
expect(state.roadmap?.features[0].status).toBe('done');
|
||||
expect(state.roadmap?.features[0].taskOutcome).toBe('archived');
|
||||
expect(state.roadmap?.features[0].previousStatus).toBe('planned');
|
||||
});
|
||||
|
||||
it('should not overwrite previousStatus if already done', () => {
|
||||
const features = [createTestFeature({
|
||||
id: 'feature-1',
|
||||
linkedSpecId: 'spec-001',
|
||||
status: 'done' as RoadmapFeatureStatus,
|
||||
taskOutcome: 'completed',
|
||||
previousStatus: 'in_progress' as RoadmapFeatureStatus
|
||||
})];
|
||||
const roadmap = createTestRoadmap({ features });
|
||||
|
||||
useRoadmapStore.setState({ roadmap });
|
||||
|
||||
useRoadmapStore.getState().markFeatureDoneBySpecId('spec-001', 'archived');
|
||||
|
||||
const state = useRoadmapStore.getState();
|
||||
expect(state.roadmap?.features[0].taskOutcome).toBe('archived');
|
||||
expect(state.roadmap?.features[0].previousStatus).toBe('in_progress');
|
||||
});
|
||||
|
||||
it('should not affect features with different linkedSpecId', () => {
|
||||
const features = [
|
||||
createTestFeature({ id: 'feature-1', linkedSpecId: 'spec-001', status: 'in_progress' as RoadmapFeatureStatus }),
|
||||
createTestFeature({ id: 'feature-2', linkedSpecId: 'spec-002', status: 'planned' as RoadmapFeatureStatus })
|
||||
];
|
||||
const roadmap = createTestRoadmap({ features });
|
||||
|
||||
useRoadmapStore.setState({ roadmap });
|
||||
|
||||
useRoadmapStore.getState().markFeatureDoneBySpecId('spec-001', 'completed');
|
||||
|
||||
const state = useRoadmapStore.getState();
|
||||
expect(state.roadmap?.features[1].status).toBe('planned');
|
||||
expect(state.roadmap?.features[1].taskOutcome).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateFeatureLinkedSpec', () => {
|
||||
|
||||
@@ -174,6 +174,8 @@ export function GitHubIssues({ onOpenSettings, onNavigateToTask }: GitHubIssuesP
|
||||
onSelectIssue={selectIssue}
|
||||
onInvestigate={handleInvestigate}
|
||||
onLoadMore={!isSearchActive ? handleLoadMore : undefined}
|
||||
onRetry={handleRefresh}
|
||||
onOpenSettings={onOpenSettings}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
TooltipTrigger
|
||||
} from './ui/tooltip';
|
||||
import { Play, ExternalLink, TrendingUp, Layers, ThumbsUp } from 'lucide-react';
|
||||
import { TaskOutcomeBadge, getTaskOutcomeColorClass } from './roadmap/TaskOutcomeBadge';
|
||||
import {
|
||||
ROADMAP_PRIORITY_COLORS,
|
||||
ROADMAP_PRIORITY_LABELS,
|
||||
@@ -120,7 +121,14 @@ export function SortableFeatureCard({
|
||||
<h3 className="font-medium text-sm leading-snug line-clamp-2">{feature.title}</h3>
|
||||
</div>
|
||||
<div className="shrink-0">
|
||||
{feature.linkedSpecId ? (
|
||||
{feature.taskOutcome ? (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={`text-[10px] px-1.5 py-0 ${getTaskOutcomeColorClass(feature.taskOutcome)}`}
|
||||
>
|
||||
<TaskOutcomeBadge outcome={feature.taskOutcome} size="sm" />
|
||||
</Badge>
|
||||
) : feature.linkedSpecId ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
|
||||
+371
@@ -0,0 +1,371 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
AlertTriangle,
|
||||
Clock,
|
||||
Key,
|
||||
Shield,
|
||||
WifiOff,
|
||||
SearchX,
|
||||
RefreshCw,
|
||||
Settings2,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '../../ui/button';
|
||||
import { Card, CardContent } from '../../ui/card';
|
||||
import { cn } from '../../../lib/utils';
|
||||
import { parseGitHubError } from '../utils/github-error-parser';
|
||||
import type { GitHubErrorInfo, GitHubErrorType } from '../types';
|
||||
|
||||
/**
|
||||
* Props for the GitHubErrorDisplay component.
|
||||
*/
|
||||
export interface GitHubErrorDisplayProps {
|
||||
/** Raw error string or pre-parsed GitHubErrorInfo */
|
||||
error: string | GitHubErrorInfo | null;
|
||||
/** Callback when user clicks retry button */
|
||||
onRetry?: () => void;
|
||||
/** Callback when user clicks settings button */
|
||||
onOpenSettings?: () => void;
|
||||
/** Additional CSS classes */
|
||||
className?: string;
|
||||
/** Whether to show as compact inline error (vs full-width card) */
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for each error type: icon, color, title key.
|
||||
*/
|
||||
const ERROR_CONFIG: Record<
|
||||
GitHubErrorType,
|
||||
{
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
titleKey: string;
|
||||
iconColorClass: string;
|
||||
}
|
||||
> = {
|
||||
rate_limit: {
|
||||
icon: Clock,
|
||||
titleKey: 'githubErrors.rateLimitTitle',
|
||||
iconColorClass: 'text-warning',
|
||||
},
|
||||
auth: {
|
||||
icon: Key,
|
||||
titleKey: 'githubErrors.authTitle',
|
||||
iconColorClass: 'text-destructive',
|
||||
},
|
||||
permission: {
|
||||
icon: Shield,
|
||||
titleKey: 'githubErrors.permissionTitle',
|
||||
iconColorClass: 'text-destructive',
|
||||
},
|
||||
not_found: {
|
||||
icon: SearchX,
|
||||
titleKey: 'githubErrors.notFoundTitle',
|
||||
iconColorClass: 'text-muted-foreground',
|
||||
},
|
||||
network: {
|
||||
icon: WifiOff,
|
||||
titleKey: 'githubErrors.networkTitle',
|
||||
iconColorClass: 'text-warning',
|
||||
},
|
||||
unknown: {
|
||||
icon: AlertTriangle,
|
||||
titleKey: 'githubErrors.unknownTitle',
|
||||
iconColorClass: 'text-destructive',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Base message keys for each error type.
|
||||
* Hoisted to module scope to avoid recreation on every function call.
|
||||
*/
|
||||
const BASE_MESSAGE_KEYS: Record<GitHubErrorType, string> = {
|
||||
rate_limit: 'githubErrors.rateLimitMessage',
|
||||
auth: 'githubErrors.authMessage',
|
||||
permission: 'githubErrors.permissionMessage',
|
||||
not_found: 'githubErrors.notFoundMessage',
|
||||
network: 'githubErrors.networkMessage',
|
||||
unknown: 'githubErrors.unknownMessage',
|
||||
};
|
||||
|
||||
/**
|
||||
* Countdown time components for i18n-friendly formatting.
|
||||
*/
|
||||
interface CountdownComponents {
|
||||
hours: number;
|
||||
minutes: number;
|
||||
seconds: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate countdown time components from reset time.
|
||||
* Returns numeric values for i18n-friendly formatting in the component.
|
||||
*/
|
||||
function getCountdownComponents(resetTime: Date): CountdownComponents | null {
|
||||
const now = new Date();
|
||||
const diffMs = resetTime.getTime() - now.getTime();
|
||||
|
||||
if (diffMs <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const diffSecs = Math.floor(diffMs / 1000);
|
||||
const diffMins = Math.floor(diffSecs / 60);
|
||||
const diffHours = Math.floor(diffMins / 60);
|
||||
|
||||
return {
|
||||
hours: diffHours,
|
||||
minutes: diffHours > 0 ? diffMins % 60 : diffMins,
|
||||
seconds: diffSecs % 60,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the most specific message key based on available metadata.
|
||||
* Pure function extracted to module scope to avoid recreation on each render.
|
||||
* @param info - The error info object
|
||||
* @param rateLimitDiffMs - Pre-computed time difference in milliseconds (avoids dual calculation)
|
||||
*/
|
||||
function getMessageKey(info: GitHubErrorInfo, rateLimitDiffMs?: number): string {
|
||||
if (info.type === 'rate_limit' && rateLimitDiffMs !== undefined && rateLimitDiffMs > 0) {
|
||||
const diffMins = Math.ceil(rateLimitDiffMs / 60000);
|
||||
return diffMins >= 60
|
||||
? 'githubErrors.rateLimitMessageHours'
|
||||
: 'githubErrors.rateLimitMessageMinutes';
|
||||
}
|
||||
if (info.type === 'permission' && info.requiredScopes && info.requiredScopes.length > 0) {
|
||||
return 'githubErrors.permissionMessageScopes';
|
||||
}
|
||||
return BASE_MESSAGE_KEYS[info.type];
|
||||
}
|
||||
|
||||
/**
|
||||
* Component that displays GitHub API errors with appropriate icons,
|
||||
* messages, and action buttons based on error type.
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* // With raw error string
|
||||
* <GitHubErrorDisplay
|
||||
* error="GitHub API error: 403 - Rate limit exceeded"
|
||||
* onRetry={handleRetry}
|
||||
* />
|
||||
*
|
||||
* // With pre-parsed error info
|
||||
* <GitHubErrorDisplay
|
||||
* error={errorInfo}
|
||||
* onOpenSettings={handleOpenSettings}
|
||||
* compact
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export function GitHubErrorDisplay({
|
||||
error,
|
||||
onRetry,
|
||||
onOpenSettings,
|
||||
className,
|
||||
compact = false,
|
||||
}: GitHubErrorDisplayProps) {
|
||||
const { t } = useTranslation('common');
|
||||
|
||||
// Parse error if it's a string, otherwise use the provided GitHubErrorInfo
|
||||
// Memoize to prevent useEffect churn from new Date references on each render
|
||||
const errorInfo: GitHubErrorInfo = useMemo(
|
||||
() =>
|
||||
typeof error === 'string' || error === null
|
||||
? parseGitHubError(error)
|
||||
: error,
|
||||
[error]
|
||||
);
|
||||
|
||||
// State for rate limit countdown components
|
||||
const [countdownComponents, setCountdownComponents] = useState<CountdownComponents | null>(() =>
|
||||
errorInfo.rateLimitResetTime
|
||||
? getCountdownComponents(errorInfo.rateLimitResetTime)
|
||||
: null
|
||||
);
|
||||
|
||||
// Update countdown every second for rate limit errors
|
||||
// Extract timestamp for stable useEffect dependency (avoids optional chaining in deps)
|
||||
const resetTimeMs = errorInfo.rateLimitResetTime?.getTime();
|
||||
|
||||
useEffect(() => {
|
||||
if (errorInfo.type !== 'rate_limit' || !errorInfo.rateLimitResetTime) {
|
||||
// Clear stale countdown state when error type changes away from rate_limit
|
||||
setCountdownComponents(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const resetTime = errorInfo.rateLimitResetTime;
|
||||
let intervalId: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
const updateCountdown = () => {
|
||||
const components = getCountdownComponents(resetTime);
|
||||
setCountdownComponents(components);
|
||||
// Stop the interval when countdown expires
|
||||
if (!components && intervalId) {
|
||||
clearInterval(intervalId);
|
||||
intervalId = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
// Update immediately
|
||||
updateCountdown();
|
||||
|
||||
// Only set interval if countdown is still active
|
||||
if (getCountdownComponents(resetTime)) {
|
||||
intervalId = setInterval(updateCountdown, 1000);
|
||||
}
|
||||
|
||||
// Cleanup on unmount or when error changes
|
||||
return () => {
|
||||
if (intervalId) clearInterval(intervalId);
|
||||
};
|
||||
}, [errorInfo.type, resetTimeMs]);
|
||||
|
||||
// Format countdown using i18n
|
||||
const formatCountdownDisplay = (components: CountdownComponents | null): string => {
|
||||
if (!components) return '';
|
||||
if (components.hours > 0) {
|
||||
return t('githubErrors.countdownHoursMinutes', {
|
||||
hours: components.hours,
|
||||
minutes: components.minutes,
|
||||
});
|
||||
}
|
||||
return t('githubErrors.countdownMinutesSeconds', {
|
||||
minutes: components.minutes,
|
||||
seconds: components.seconds,
|
||||
});
|
||||
};
|
||||
|
||||
// Get configuration for this error type
|
||||
const config = ERROR_CONFIG[errorInfo.type];
|
||||
const Icon = config.icon;
|
||||
|
||||
// Determine which actions to show
|
||||
const showRetry = ['rate_limit', 'network', 'unknown'].includes(errorInfo.type);
|
||||
const showSettings = ['auth', 'permission'].includes(errorInfo.type);
|
||||
const isRateLimitExpired =
|
||||
errorInfo.type === 'rate_limit' &&
|
||||
errorInfo.rateLimitResetTime &&
|
||||
new Date() >= errorInfo.rateLimitResetTime;
|
||||
|
||||
// Don't render if no error
|
||||
if (!error) return null;
|
||||
|
||||
// Compute time remaining once for both message key selection and translation
|
||||
const rateLimitDiffMs = errorInfo.rateLimitResetTime
|
||||
? errorInfo.rateLimitResetTime.getTime() - Date.now()
|
||||
: undefined;
|
||||
|
||||
// Get the translated message with appropriate interpolation values
|
||||
const messageKey = getMessageKey(errorInfo, rateLimitDiffMs);
|
||||
// Only pass positive minutes/hours values to avoid stale negative/zero values
|
||||
const rawMinutes = rateLimitDiffMs ? Math.ceil(rateLimitDiffMs / 60000) : undefined;
|
||||
const minutes = rawMinutes && rawMinutes > 0 ? rawMinutes : undefined;
|
||||
const hours = minutes ? Math.ceil(minutes / 60) : undefined;
|
||||
|
||||
const errorMessage = t(messageKey, {
|
||||
defaultValue: errorInfo.message,
|
||||
minutes,
|
||||
hours,
|
||||
scopes: errorInfo.requiredScopes?.join(', '),
|
||||
});
|
||||
|
||||
// Compact variant for inline display
|
||||
if (compact) {
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
aria-label={errorMessage}
|
||||
className={cn(
|
||||
'flex items-center gap-2 p-3 rounded-lg bg-muted/50 border border-border',
|
||||
className
|
||||
)}
|
||||
title={errorMessage}
|
||||
>
|
||||
<Icon className={cn('h-4 w-4 shrink-0', config.iconColorClass)} />
|
||||
<span className="text-sm text-muted-foreground flex-1 truncate">
|
||||
{t(config.titleKey)}
|
||||
</span>
|
||||
{showRetry && onRetry && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onRetry}
|
||||
className="h-7 px-2"
|
||||
>
|
||||
<RefreshCw className="h-3 w-3 mr-1" />
|
||||
{t('buttons.retry')}
|
||||
</Button>
|
||||
)}
|
||||
{showSettings && onOpenSettings && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onOpenSettings}
|
||||
className="h-7 px-2"
|
||||
>
|
||||
<Settings2 className="h-3 w-3 mr-1" />
|
||||
{t('actions.settings')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Full card variant for blocking errors
|
||||
return (
|
||||
<Card role="alert" className={cn('border-destructive/50 m-4', className)}>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex flex-col items-center gap-4 text-center">
|
||||
<div className="w-12 h-12 rounded-full bg-muted/50 flex items-center justify-center">
|
||||
<Icon className={cn('h-6 w-6', config.iconColorClass)} />
|
||||
</div>
|
||||
<div className="space-y-2 max-w-md">
|
||||
<h3 className="font-semibold text-lg text-foreground">
|
||||
{t(config.titleKey)}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">{errorMessage}</p>
|
||||
{/* Rate limit countdown display */}
|
||||
{errorInfo.type === 'rate_limit' && countdownComponents && (
|
||||
<p className="text-xs text-warning font-medium">
|
||||
{t('githubErrors.resetsIn', { time: formatCountdownDisplay(countdownComponents) })}
|
||||
</p>
|
||||
)}
|
||||
{/* Rate limit expired - show retry prompt */}
|
||||
{isRateLimitExpired && (
|
||||
<p className="text-xs text-primary">
|
||||
{t('githubErrors.rateLimitExpired')}
|
||||
</p>
|
||||
)}
|
||||
{/* Required scopes for permission errors */}
|
||||
{errorInfo.requiredScopes && errorInfo.requiredScopes.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('githubErrors.requiredScopes')}:{' '}
|
||||
<code className="bg-muted px-1 rounded">
|
||||
{errorInfo.requiredScopes.join(', ')}
|
||||
</code>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{/* Action buttons */}
|
||||
<div className="flex gap-2">
|
||||
{showRetry && onRetry && (
|
||||
<Button onClick={onRetry} variant="outline" size="sm">
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
{t('buttons.retry')}
|
||||
</Button>
|
||||
)}
|
||||
{showSettings && onOpenSettings && (
|
||||
<Button onClick={onOpenSettings} variant="outline" size="sm">
|
||||
<Settings2 className="h-4 w-4 mr-2" />
|
||||
{t('actions.settings')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { useRef, useEffect, useCallback, useState } from 'react';
|
||||
import { Loader2, AlertCircle } from 'lucide-react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { ScrollArea } from '../../ui/scroll-area';
|
||||
import { IssueListItem } from './IssueListItem';
|
||||
import { EmptyState } from './EmptyStates';
|
||||
import { GitHubErrorDisplay } from './GitHubErrorDisplay';
|
||||
import type { IssueListProps } from '../types';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
@@ -15,7 +16,9 @@ export function IssueList({
|
||||
error,
|
||||
onSelectIssue,
|
||||
onInvestigate,
|
||||
onLoadMore
|
||||
onLoadMore,
|
||||
onRetry,
|
||||
onOpenSettings
|
||||
}: IssueListProps) {
|
||||
const { t } = useTranslation('common');
|
||||
const loadMoreTriggerRef = useRef<HTMLDivElement>(null);
|
||||
@@ -50,12 +53,12 @@ export function IssueList({
|
||||
// Load-more errors are shown inline near the load-more trigger
|
||||
if (error && issues.length === 0) {
|
||||
return (
|
||||
<div className="p-4 bg-destructive/10 border-b border-destructive/30">
|
||||
<div className="flex items-center gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{error}
|
||||
</div>
|
||||
</div>
|
||||
<GitHubErrorDisplay
|
||||
error={error}
|
||||
onRetry={onRetry}
|
||||
onOpenSettings={onOpenSettings}
|
||||
className="flex-1"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -85,15 +88,18 @@ export function IssueList({
|
||||
))}
|
||||
|
||||
{/* Load more trigger / Loading indicator */}
|
||||
{/* Inline error for load-more failures (visible even when onLoadMore is undefined during search) */}
|
||||
{error && issues.length > 0 && (
|
||||
<GitHubErrorDisplay
|
||||
error={error}
|
||||
onRetry={onRetry}
|
||||
onOpenSettings={onOpenSettings}
|
||||
compact
|
||||
className="w-full"
|
||||
/>
|
||||
)}
|
||||
{onLoadMore && (
|
||||
<div ref={loadMoreTriggerRef} className="py-4 flex flex-col items-center gap-2">
|
||||
{/* Inline error for load-more failures (when issues are already loaded) */}
|
||||
{error && issues.length > 0 && (
|
||||
<div className="flex items-center gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
{isLoadingMore ? (
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
|
||||
+500
@@ -0,0 +1,500 @@
|
||||
/**
|
||||
* @vitest-environment jsdom
|
||||
*/
|
||||
/**
|
||||
* Unit tests for GitHubErrorDisplay component.
|
||||
* Tests error display, icon rendering, button visibility, and countdown functionality.
|
||||
*/
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { GitHubErrorDisplay } from '../GitHubErrorDisplay';
|
||||
import type { GitHubErrorInfo } from '../../types';
|
||||
|
||||
// Mock react-i18next
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, options?: Record<string, unknown>) => {
|
||||
const translations: Record<string, string> = {
|
||||
'githubErrors.rateLimitTitle': 'GitHub Rate Limit Reached',
|
||||
'githubErrors.authTitle': 'GitHub Authentication Required',
|
||||
'githubErrors.permissionTitle': 'GitHub Permission Denied',
|
||||
'githubErrors.notFoundTitle': 'GitHub Resource Not Found',
|
||||
'githubErrors.networkTitle': 'GitHub Connection Error',
|
||||
'githubErrors.unknownTitle': 'GitHub Error',
|
||||
'githubErrors.rateLimitMessage': 'GitHub API rate limit reached. Please wait a moment before trying again.',
|
||||
'githubErrors.rateLimitMessageMinutes': `GitHub API rate limit reached. Please wait ${options?.minutes ?? 'X'} minute(s) before trying again.`,
|
||||
'githubErrors.rateLimitMessageHours': `GitHub API rate limit reached. Rate limit resets in approximately ${options?.hours ?? 'X'} hour(s).`,
|
||||
'githubErrors.authMessage': 'GitHub authentication failed. Please check your GitHub token in Settings.',
|
||||
'githubErrors.permissionMessage': 'GitHub permission denied. Your token may not have the required access.',
|
||||
'githubErrors.permissionMessageScopes': `GitHub permission denied. Your token is missing required scopes: ${options?.scopes ?? ''}. Please update your GitHub token in Settings.`,
|
||||
'githubErrors.notFoundMessage': 'The requested GitHub resource was not found.',
|
||||
'githubErrors.networkMessage': 'Unable to connect to GitHub. Please check your internet connection.',
|
||||
'githubErrors.unknownMessage': 'An unexpected error occurred while communicating with GitHub.',
|
||||
'githubErrors.resetsIn': options?.time ? `Resets in ${options.time as string}` : 'Resets in',
|
||||
'githubErrors.countdownHoursMinutes': `${options?.hours ?? 0}h ${options?.minutes ?? 0}m`,
|
||||
'githubErrors.countdownMinutesSeconds': `${options?.minutes ?? 0}m ${options?.seconds ?? 0}s`,
|
||||
'githubErrors.rateLimitExpired': 'Rate limit has reset. You can retry now.',
|
||||
'githubErrors.requiredScopes': 'Required scopes',
|
||||
'buttons.retry': 'Retry',
|
||||
'actions.settings': 'Settings',
|
||||
};
|
||||
return translations[key] || key;
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
// Helper to create mock GitHubErrorInfo
|
||||
function createMockErrorInfo(
|
||||
type: GitHubErrorInfo['type'],
|
||||
overrides: Partial<GitHubErrorInfo> = {}
|
||||
): GitHubErrorInfo {
|
||||
const defaults: Record<string, GitHubErrorInfo> = {
|
||||
rate_limit: {
|
||||
type: 'rate_limit',
|
||||
message: 'GitHub API rate limit reached. Please wait a moment before trying again.',
|
||||
statusCode: 403,
|
||||
},
|
||||
auth: {
|
||||
type: 'auth',
|
||||
message: 'GitHub authentication failed. Please check your GitHub token in Settings.',
|
||||
statusCode: 401,
|
||||
},
|
||||
permission: {
|
||||
type: 'permission',
|
||||
message: 'GitHub permission denied. Your token may not have the required access.',
|
||||
statusCode: 403,
|
||||
},
|
||||
not_found: {
|
||||
type: 'not_found',
|
||||
message: 'The requested GitHub resource was not found.',
|
||||
statusCode: 404,
|
||||
},
|
||||
network: {
|
||||
type: 'network',
|
||||
message: 'Unable to connect to GitHub. Please check your internet connection.',
|
||||
},
|
||||
unknown: {
|
||||
type: 'unknown',
|
||||
message: 'An unexpected error occurred while communicating with GitHub.',
|
||||
},
|
||||
};
|
||||
|
||||
return { ...defaults[type], ...overrides };
|
||||
}
|
||||
|
||||
describe('GitHubErrorDisplay', () => {
|
||||
describe('rendering null/empty states', () => {
|
||||
it('should render nothing when error is null', () => {
|
||||
const { container } = render(<GitHubErrorDisplay error={null} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('should render nothing when error is an empty string', () => {
|
||||
// Empty string is falsy, so component should return null
|
||||
const { container } = render(
|
||||
<GitHubErrorDisplay error={'' as string} />
|
||||
);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('rendering with string error', () => {
|
||||
it('should render error display when error is a string', () => {
|
||||
render(<GitHubErrorDisplay error="401 Unauthorized" />);
|
||||
|
||||
// Should show the auth title (parsed from the error)
|
||||
expect(screen.getByText('GitHub Authentication Required')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render error display for rate limit string error', () => {
|
||||
render(<GitHubErrorDisplay error="rate limit exceeded" />);
|
||||
|
||||
expect(screen.getByText('GitHub Rate Limit Reached')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('rendering with GitHubErrorInfo object', () => {
|
||||
it('should render rate_limit error correctly', () => {
|
||||
const errorInfo = createMockErrorInfo('rate_limit');
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
expect(screen.getByText('GitHub Rate Limit Reached')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(/GitHub API rate limit reached/)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render auth error correctly', () => {
|
||||
const errorInfo = createMockErrorInfo('auth');
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
expect(screen.getByText('GitHub Authentication Required')).toBeInTheDocument();
|
||||
expect(screen.getByText(/authentication failed/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render permission error correctly', () => {
|
||||
const errorInfo = createMockErrorInfo('permission', {
|
||||
requiredScopes: ['repo', 'workflow'],
|
||||
});
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
expect(screen.getByText('GitHub Permission Denied')).toBeInTheDocument();
|
||||
// Check that permission message is rendered
|
||||
expect(screen.getByText(/Your token is missing required scopes/)).toBeInTheDocument();
|
||||
// Should show required scopes in the code element
|
||||
expect(screen.getByText('repo, workflow')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render not_found error correctly', () => {
|
||||
const errorInfo = createMockErrorInfo('not_found');
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
expect(screen.getByText('GitHub Resource Not Found')).toBeInTheDocument();
|
||||
expect(screen.getByText(/not found/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render network error correctly', () => {
|
||||
const errorInfo = createMockErrorInfo('network');
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
expect(screen.getByText('GitHub Connection Error')).toBeInTheDocument();
|
||||
expect(screen.getByText(/Unable to connect/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should render unknown error correctly', () => {
|
||||
const errorInfo = createMockErrorInfo('unknown');
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
expect(screen.getByText('GitHub Error')).toBeInTheDocument();
|
||||
expect(screen.getByText(/unexpected error/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('compact mode', () => {
|
||||
it('should render compact variant when compact=true', () => {
|
||||
const errorInfo = createMockErrorInfo('rate_limit');
|
||||
render(<GitHubErrorDisplay error={errorInfo} compact />);
|
||||
|
||||
// In compact mode, the title is in a smaller span
|
||||
expect(screen.getByText('GitHub Rate Limit Reached')).toBeInTheDocument();
|
||||
// Should not render the card structure (no centered layout)
|
||||
expect(screen.queryByRole('heading', { level: 3 })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show retry button in compact mode for rate_limit errors', () => {
|
||||
const errorInfo = createMockErrorInfo('rate_limit');
|
||||
const onRetry = vi.fn();
|
||||
render(<GitHubErrorDisplay error={errorInfo} compact onRetry={onRetry} />);
|
||||
|
||||
const retryButton = screen.getByRole('button', { name: /retry/i });
|
||||
expect(retryButton).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(retryButton);
|
||||
expect(onRetry).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should show settings button in compact mode for auth errors', () => {
|
||||
const errorInfo = createMockErrorInfo('auth');
|
||||
const onOpenSettings = vi.fn();
|
||||
render(<GitHubErrorDisplay error={errorInfo} compact onOpenSettings={onOpenSettings} />);
|
||||
|
||||
const settingsButton = screen.getByRole('button', { name: /settings/i });
|
||||
expect(settingsButton).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(settingsButton);
|
||||
expect(onOpenSettings).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('full card mode (default)', () => {
|
||||
it('should render card structure by default', () => {
|
||||
const errorInfo = createMockErrorInfo('rate_limit');
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
// Should render heading
|
||||
expect(screen.getByRole('heading', { level: 3 })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show retry button for rate_limit errors with onRetry callback', () => {
|
||||
const errorInfo = createMockErrorInfo('rate_limit');
|
||||
const onRetry = vi.fn();
|
||||
render(<GitHubErrorDisplay error={errorInfo} onRetry={onRetry} />);
|
||||
|
||||
const retryButton = screen.getByRole('button', { name: /retry/i });
|
||||
expect(retryButton).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(retryButton);
|
||||
expect(onRetry).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should show retry button for network errors', () => {
|
||||
const errorInfo = createMockErrorInfo('network');
|
||||
const onRetry = vi.fn();
|
||||
render(<GitHubErrorDisplay error={errorInfo} onRetry={onRetry} />);
|
||||
|
||||
const retryButton = screen.getByRole('button', { name: /retry/i });
|
||||
expect(retryButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show retry button for unknown errors', () => {
|
||||
const errorInfo = createMockErrorInfo('unknown');
|
||||
const onRetry = vi.fn();
|
||||
render(<GitHubErrorDisplay error={errorInfo} onRetry={onRetry} />);
|
||||
|
||||
const retryButton = screen.getByRole('button', { name: /retry/i });
|
||||
expect(retryButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should NOT show retry button for auth errors', () => {
|
||||
const errorInfo = createMockErrorInfo('auth');
|
||||
const onRetry = vi.fn();
|
||||
render(<GitHubErrorDisplay error={errorInfo} onRetry={onRetry} />);
|
||||
|
||||
expect(screen.queryByRole('button', { name: /retry/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should NOT show retry button for permission errors', () => {
|
||||
const errorInfo = createMockErrorInfo('permission');
|
||||
const onRetry = vi.fn();
|
||||
render(<GitHubErrorDisplay error={errorInfo} onRetry={onRetry} />);
|
||||
|
||||
expect(screen.queryByRole('button', { name: /retry/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should NOT show retry button for not_found errors', () => {
|
||||
const errorInfo = createMockErrorInfo('not_found');
|
||||
const onRetry = vi.fn();
|
||||
render(<GitHubErrorDisplay error={errorInfo} onRetry={onRetry} />);
|
||||
|
||||
expect(screen.queryByRole('button', { name: /retry/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show settings button for auth errors with onOpenSettings callback', () => {
|
||||
const errorInfo = createMockErrorInfo('auth');
|
||||
const onOpenSettings = vi.fn();
|
||||
render(<GitHubErrorDisplay error={errorInfo} onOpenSettings={onOpenSettings} />);
|
||||
|
||||
const settingsButton = screen.getByRole('button', { name: /settings/i });
|
||||
expect(settingsButton).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(settingsButton);
|
||||
expect(onOpenSettings).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should show settings button for permission errors', () => {
|
||||
const errorInfo = createMockErrorInfo('permission');
|
||||
const onOpenSettings = vi.fn();
|
||||
render(<GitHubErrorDisplay error={errorInfo} onOpenSettings={onOpenSettings} />);
|
||||
|
||||
const settingsButton = screen.getByRole('button', { name: /settings/i });
|
||||
expect(settingsButton).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should NOT show settings button for rate_limit errors', () => {
|
||||
const errorInfo = createMockErrorInfo('rate_limit');
|
||||
const onOpenSettings = vi.fn();
|
||||
render(<GitHubErrorDisplay error={errorInfo} onOpenSettings={onOpenSettings} />);
|
||||
|
||||
expect(screen.queryByRole('button', { name: /settings/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should NOT show settings button for network errors', () => {
|
||||
const errorInfo = createMockErrorInfo('network');
|
||||
const onOpenSettings = vi.fn();
|
||||
render(<GitHubErrorDisplay error={errorInfo} onOpenSettings={onOpenSettings} />);
|
||||
|
||||
expect(screen.queryByRole('button', { name: /settings/i })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('rate limit countdown', () => {
|
||||
it('should display countdown for rate limit errors with reset time', () => {
|
||||
// Set reset time 5 minutes in the future
|
||||
const resetTime = new Date(Date.now() + 5 * 60 * 1000);
|
||||
const errorInfo = createMockErrorInfo('rate_limit', {
|
||||
rateLimitResetTime: resetTime,
|
||||
});
|
||||
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
// Should show countdown in "Xm Ys" format (e.g., "4m 59s" or "5m 0s")
|
||||
expect(screen.getByText(/Resets in \d+m \d+s/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should set up interval to update countdown', () => {
|
||||
vi.useFakeTimers();
|
||||
const resetTime = new Date(Date.now() + 2 * 60 * 1000);
|
||||
const errorInfo = createMockErrorInfo('rate_limit', {
|
||||
rateLimitResetTime: resetTime,
|
||||
});
|
||||
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
// Initial countdown should be displayed
|
||||
expect(screen.getByText(/Resets in/)).toBeInTheDocument();
|
||||
|
||||
// Verify interval is running by checking timers
|
||||
const timerCount = vi.getTimerCount();
|
||||
expect(timerCount).toBe(1); // One interval should be running
|
||||
|
||||
// Advance time and verify interval still fires
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(screen.getByText(/Resets in/)).toBeInTheDocument();
|
||||
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('should NOT show countdown for non-rate-limit errors', () => {
|
||||
const errorInfo = createMockErrorInfo('auth');
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
expect(screen.queryByText(/Resets in/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should show rate limit expired message when reset time has passed', () => {
|
||||
// Set reset time in the past
|
||||
const resetTime = new Date(Date.now() - 1000);
|
||||
const errorInfo = createMockErrorInfo('rate_limit', {
|
||||
rateLimitResetTime: resetTime,
|
||||
});
|
||||
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
expect(
|
||||
screen.getByText('Rate limit has reset. You can retry now.')
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should cleanup interval on unmount', () => {
|
||||
vi.useFakeTimers();
|
||||
const clearIntervalSpy = vi.spyOn(global, 'clearInterval');
|
||||
|
||||
const resetTime = new Date(Date.now() + 5 * 60 * 1000);
|
||||
const errorInfo = createMockErrorInfo('rate_limit', {
|
||||
rateLimitResetTime: resetTime,
|
||||
});
|
||||
|
||||
const { unmount } = render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
// Verify the countdown was rendered
|
||||
expect(screen.getByText(/Resets in/)).toBeInTheDocument();
|
||||
|
||||
// Unmount and verify clearInterval was called
|
||||
unmount();
|
||||
expect(clearIntervalSpy).toHaveBeenCalled();
|
||||
|
||||
clearIntervalSpy.mockRestore();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
|
||||
describe('required scopes display', () => {
|
||||
it('should display required scopes for permission errors', () => {
|
||||
const errorInfo = createMockErrorInfo('permission', {
|
||||
requiredScopes: ['repo', 'read:org', 'workflow'],
|
||||
});
|
||||
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
expect(screen.getByText('Required scopes:')).toBeInTheDocument();
|
||||
// The scopes appear in a code element
|
||||
expect(screen.getByText('repo, read:org, workflow')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should NOT display scopes section when no scopes are provided', () => {
|
||||
const errorInfo = createMockErrorInfo('permission', {
|
||||
requiredScopes: undefined,
|
||||
});
|
||||
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
expect(screen.queryByText('Required scopes:')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should NOT display scopes section when scopes array is empty', () => {
|
||||
const errorInfo = createMockErrorInfo('permission', {
|
||||
requiredScopes: [],
|
||||
});
|
||||
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
expect(screen.queryByText('Required scopes:')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('className prop', () => {
|
||||
it('should apply custom className in full card mode', () => {
|
||||
const errorInfo = createMockErrorInfo('rate_limit');
|
||||
const { container } = render(
|
||||
<GitHubErrorDisplay error={errorInfo} className="custom-class" />
|
||||
);
|
||||
|
||||
expect(container.firstChild).toHaveClass('custom-class');
|
||||
});
|
||||
|
||||
it('should apply custom className in compact mode', () => {
|
||||
const errorInfo = createMockErrorInfo('rate_limit');
|
||||
const { container } = render(
|
||||
<GitHubErrorDisplay error={errorInfo} compact className="custom-compact-class" />
|
||||
);
|
||||
|
||||
expect(container.firstChild).toHaveClass('custom-compact-class');
|
||||
});
|
||||
});
|
||||
|
||||
describe('callback stability', () => {
|
||||
it('should not call onRetry on initial render', () => {
|
||||
const errorInfo = createMockErrorInfo('rate_limit');
|
||||
const onRetry = vi.fn();
|
||||
|
||||
render(<GitHubErrorDisplay error={errorInfo} onRetry={onRetry} />);
|
||||
|
||||
expect(onRetry).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not call onOpenSettings on initial render', () => {
|
||||
const errorInfo = createMockErrorInfo('auth');
|
||||
const onOpenSettings = vi.fn();
|
||||
|
||||
render(<GitHubErrorDisplay error={errorInfo} onOpenSettings={onOpenSettings} />);
|
||||
|
||||
expect(onOpenSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('accessibility', () => {
|
||||
it('should have role="alert" for screen reader announcements', () => {
|
||||
const errorInfo = createMockErrorInfo('rate_limit');
|
||||
render(<GitHubErrorDisplay error={errorInfo} />);
|
||||
|
||||
// The error card should have role="alert" for accessibility
|
||||
expect(screen.getByRole('alert')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should have role="alert" in compact mode', () => {
|
||||
const errorInfo = createMockErrorInfo('network');
|
||||
render(<GitHubErrorDisplay error={errorInfo} compact />);
|
||||
|
||||
expect(screen.getByRole('alert')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should have accessible button labels', () => {
|
||||
const errorInfo = createMockErrorInfo('rate_limit');
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function -- callback not needed for this test
|
||||
render(<GitHubErrorDisplay error={errorInfo} onRetry={() => { /* no-op */ }} />);
|
||||
|
||||
const button = screen.getByRole('button', { name: /retry/i });
|
||||
expect(button).toHaveTextContent('Retry');
|
||||
});
|
||||
|
||||
it('should have accessible settings button label', () => {
|
||||
const errorInfo = createMockErrorInfo('auth');
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function -- callback not needed for this test
|
||||
render(<GitHubErrorDisplay error={errorInfo} onOpenSettings={() => { /* no-op */ }} />);
|
||||
|
||||
const button = screen.getByRole('button', { name: /settings/i });
|
||||
expect(button).toHaveTextContent('Settings');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -6,3 +6,4 @@ export { IssueListHeader } from './IssueListHeader';
|
||||
export { IssueList } from './IssueList';
|
||||
export { AutoFixButton } from './AutoFixButton';
|
||||
export { BatchReviewWizard } from './BatchReviewWizard';
|
||||
export { GitHubErrorDisplay } from './GitHubErrorDisplay';
|
||||
|
||||
@@ -3,6 +3,47 @@ import type { AutoFixConfig, AutoFixQueueItem } from '../../../../preload/api/mo
|
||||
|
||||
export type FilterState = 'open' | 'closed' | 'all';
|
||||
|
||||
/**
|
||||
* Classification types for GitHub API errors.
|
||||
* Used to determine appropriate icon, message, and actions for error display.
|
||||
*/
|
||||
export type GitHubErrorType =
|
||||
| 'rate_limit'
|
||||
| 'auth'
|
||||
| 'permission'
|
||||
| 'network'
|
||||
| 'not_found'
|
||||
| 'unknown';
|
||||
|
||||
/**
|
||||
* Parsed GitHub error information with metadata.
|
||||
* Returned by the github-error-parser utility.
|
||||
*
|
||||
* IMPORTANT: The `message` field contains hardcoded English strings intended
|
||||
* ONLY as a fallback defaultValue for i18n translation. Direct consumers should
|
||||
* use the `type` field to look up the appropriate translation key (e.g.,
|
||||
* 'githubErrors.rateLimitMessage') via react-i18next rather than displaying
|
||||
* `message` directly. This ensures proper localization for all users.
|
||||
*/
|
||||
export interface GitHubErrorInfo {
|
||||
/** The classified error type */
|
||||
type: GitHubErrorType;
|
||||
/**
|
||||
* User-friendly error message in English.
|
||||
* NOTE: Use only as defaultValue for i18n - do not display directly.
|
||||
* Use type field to look up translation key (e.g., 'githubErrors.rateLimitMessage').
|
||||
*/
|
||||
message: string;
|
||||
/** Original raw error string (for debugging/details) */
|
||||
rawMessage?: string;
|
||||
/** Rate limit reset time (only for rate_limit type) */
|
||||
rateLimitResetTime?: Date;
|
||||
/** Required OAuth scopes that are missing (only for permission type) */
|
||||
requiredScopes?: string[];
|
||||
/** HTTP status code if available */
|
||||
statusCode?: number;
|
||||
}
|
||||
|
||||
export interface GitHubIssuesProps {
|
||||
onOpenSettings?: () => void;
|
||||
/** Navigate to view a task in the kanban board */
|
||||
@@ -76,6 +117,10 @@ export interface IssueListProps {
|
||||
onSelectIssue: (issueNumber: number) => void;
|
||||
onInvestigate: (issue: GitHubIssue) => void;
|
||||
onLoadMore?: () => void;
|
||||
/** Callback for retry button in error display */
|
||||
onRetry?: () => void;
|
||||
/** Callback for settings button in error display */
|
||||
onOpenSettings?: () => void;
|
||||
}
|
||||
|
||||
export interface EmptyStateProps {
|
||||
|
||||
+691
@@ -0,0 +1,691 @@
|
||||
/**
|
||||
* Unit tests for GitHub API error parser utility.
|
||||
* Tests error classification, metadata extraction, and helper functions.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
parseGitHubError,
|
||||
isRateLimitError,
|
||||
isAuthError,
|
||||
isNetworkError,
|
||||
isRecoverableError,
|
||||
requiresSettingsAction,
|
||||
} from '../github-error-parser';
|
||||
import type { GitHubErrorType } from '../../types';
|
||||
|
||||
describe('parseGitHubError', () => {
|
||||
describe('null/undefined/empty handling', () => {
|
||||
it('should return unknown for null input', () => {
|
||||
const result = parseGitHubError(null);
|
||||
expect(result.type).toBe('unknown');
|
||||
expect(result.message).toBeDefined();
|
||||
});
|
||||
|
||||
it('should return unknown for undefined input', () => {
|
||||
const result = parseGitHubError(undefined);
|
||||
expect(result.type).toBe('unknown');
|
||||
expect(result.message).toBeDefined();
|
||||
});
|
||||
|
||||
it('should return unknown for empty string', () => {
|
||||
const result = parseGitHubError('');
|
||||
expect(result.type).toBe('unknown');
|
||||
expect(result.message).toBeDefined();
|
||||
});
|
||||
|
||||
it('should return unknown for whitespace-only string', () => {
|
||||
const result = parseGitHubError(' ');
|
||||
expect(result.type).toBe('unknown');
|
||||
expect(result.message).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('rate_limit errors', () => {
|
||||
it('should detect "rate limit exceeded" pattern', () => {
|
||||
const result = parseGitHubError('GitHub API error: rate limit exceeded');
|
||||
expect(result.type).toBe('rate_limit');
|
||||
expect(result.message).toContain('rate limit');
|
||||
expect(result.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('should detect "API rate limit exceeded" pattern', () => {
|
||||
const result = parseGitHubError('API rate limit exceeded for user');
|
||||
expect(result.type).toBe('rate_limit');
|
||||
});
|
||||
|
||||
it('should detect "too many requests" pattern', () => {
|
||||
const result = parseGitHubError('Error: too many requests');
|
||||
expect(result.type).toBe('rate_limit');
|
||||
});
|
||||
|
||||
it('should detect "403 rate limit" pattern', () => {
|
||||
const result = parseGitHubError('403 rate limit reached');
|
||||
expect(result.type).toBe('rate_limit');
|
||||
expect(result.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('should detect "abuse rate limit" pattern', () => {
|
||||
const result = parseGitHubError('Abuse rate limit triggered');
|
||||
expect(result.type).toBe('rate_limit');
|
||||
});
|
||||
|
||||
it('should detect "secondary rate limit" pattern', () => {
|
||||
const result = parseGitHubError('Secondary rate limit exceeded');
|
||||
expect(result.type).toBe('rate_limit');
|
||||
});
|
||||
|
||||
it('should extract rate limit reset time from ISO date format', () => {
|
||||
const result = parseGitHubError('rate limit exceeded, resets at 2024-01-15T12:00:00Z');
|
||||
expect(result.type).toBe('rate_limit');
|
||||
expect(result.rateLimitResetTime).toBeInstanceOf(Date);
|
||||
expect(result.rateLimitResetTime?.getUTCFullYear()).toBe(2024);
|
||||
});
|
||||
|
||||
it('should extract rate limit reset time from Unix timestamp', () => {
|
||||
const result = parseGitHubError('X-RateLimit-Reset: 1705312800');
|
||||
expect(result.type).toBe('rate_limit');
|
||||
expect(result.rateLimitResetTime).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('should generate user-friendly message with time remaining', () => {
|
||||
// Create a date 5 minutes in the future
|
||||
const futureDate = new Date(Date.now() + 5 * 60 * 1000);
|
||||
const isoString = futureDate.toISOString();
|
||||
const result = parseGitHubError(`rate limit exceeded, resets at ${isoString}`);
|
||||
expect(result.type).toBe('rate_limit');
|
||||
expect(result.message).toContain('rate limit');
|
||||
});
|
||||
|
||||
it('should generate fallback message when reset time has passed', () => {
|
||||
// Create a date in the past
|
||||
const pastDate = new Date(Date.now() - 5 * 60 * 1000);
|
||||
const isoString = pastDate.toISOString();
|
||||
const result = parseGitHubError(`rate limit exceeded, resets at ${isoString}`);
|
||||
expect(result.type).toBe('rate_limit');
|
||||
expect(result.message).toContain('moment');
|
||||
});
|
||||
|
||||
it('should include raw message truncated to MAX_RAW_ERROR_LENGTH', () => {
|
||||
const longError = 'rate limit exceeded ' + 'x'.repeat(600);
|
||||
const result = parseGitHubError(longError);
|
||||
expect(result.type).toBe('rate_limit');
|
||||
expect(result.rawMessage).toBeDefined();
|
||||
expect(result.rawMessage?.length).toBeLessThanOrEqual(503); // 500 + '...'
|
||||
});
|
||||
});
|
||||
|
||||
describe('auth errors', () => {
|
||||
it('should detect "401" pattern', () => {
|
||||
const result = parseGitHubError('HTTP 401 Unauthorized');
|
||||
expect(result.type).toBe('auth');
|
||||
expect(result.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('should detect "unauthorized" pattern', () => {
|
||||
const result = parseGitHubError('Error: unauthorized access');
|
||||
expect(result.type).toBe('auth');
|
||||
});
|
||||
|
||||
it('should detect "bad credentials" pattern', () => {
|
||||
const result = parseGitHubError('Bad credentials');
|
||||
expect(result.type).toBe('auth');
|
||||
});
|
||||
|
||||
it('should detect "authentication failed" pattern', () => {
|
||||
const result = parseGitHubError('Authentication failed');
|
||||
expect(result.type).toBe('auth');
|
||||
});
|
||||
|
||||
it('should detect "invalid token" pattern', () => {
|
||||
const result = parseGitHubError('Invalid token provided');
|
||||
expect(result.type).toBe('auth');
|
||||
});
|
||||
|
||||
it('should detect "token expired" pattern', () => {
|
||||
const result = parseGitHubError('Token expired');
|
||||
expect(result.type).toBe('auth');
|
||||
});
|
||||
|
||||
it('should detect "not authenticated" pattern', () => {
|
||||
const result = parseGitHubError('Not authenticated');
|
||||
expect(result.type).toBe('auth');
|
||||
});
|
||||
|
||||
it('should generate user-friendly message mentioning Settings', () => {
|
||||
const result = parseGitHubError('401 Unauthorized');
|
||||
expect(result.message).toContain('authentication');
|
||||
expect(result.message).toContain('Settings');
|
||||
});
|
||||
});
|
||||
|
||||
describe('not_found errors', () => {
|
||||
it('should detect "404" pattern', () => {
|
||||
const result = parseGitHubError('HTTP 404 Not Found');
|
||||
expect(result.type).toBe('not_found');
|
||||
expect(result.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('should detect "not found" pattern', () => {
|
||||
const result = parseGitHubError('Repository not found');
|
||||
expect(result.type).toBe('not_found');
|
||||
});
|
||||
|
||||
it('should detect "no such repository" pattern', () => {
|
||||
const result = parseGitHubError('No such repository exists');
|
||||
expect(result.type).toBe('not_found');
|
||||
});
|
||||
|
||||
it('should detect "does not exist" pattern', () => {
|
||||
const result = parseGitHubError('Resource does not exist');
|
||||
expect(result.type).toBe('not_found');
|
||||
});
|
||||
|
||||
it('should detect "user not found" pattern', () => {
|
||||
const result = parseGitHubError('User not found');
|
||||
expect(result.type).toBe('not_found');
|
||||
});
|
||||
|
||||
it('should generate user-friendly message about verifying repository', () => {
|
||||
const result = parseGitHubError('404 Not Found');
|
||||
expect(result.message).toContain('not found');
|
||||
expect(result.message).toContain('verify');
|
||||
});
|
||||
});
|
||||
|
||||
describe('network errors', () => {
|
||||
it('should detect "network error" pattern', () => {
|
||||
const result = parseGitHubError('Network error');
|
||||
expect(result.type).toBe('network');
|
||||
});
|
||||
|
||||
it('should detect "failed to fetch" pattern', () => {
|
||||
const result = parseGitHubError('Failed to fetch data');
|
||||
expect(result.type).toBe('network');
|
||||
});
|
||||
|
||||
it('should detect "ECONNREFUSED" pattern', () => {
|
||||
const result = parseGitHubError('Error: ECONNREFUSED');
|
||||
expect(result.type).toBe('network');
|
||||
});
|
||||
|
||||
it('should detect "ECONNRESET" pattern', () => {
|
||||
const result = parseGitHubError('Error: ECONNRESET');
|
||||
expect(result.type).toBe('network');
|
||||
});
|
||||
|
||||
it('should detect "ETIMEDOUT" pattern', () => {
|
||||
const result = parseGitHubError('Error: ETIMEDOUT');
|
||||
expect(result.type).toBe('network');
|
||||
});
|
||||
|
||||
it('should detect "connection refused" pattern', () => {
|
||||
const result = parseGitHubError('Connection refused');
|
||||
expect(result.type).toBe('network');
|
||||
});
|
||||
|
||||
it('should detect "connection timeout" pattern', () => {
|
||||
const result = parseGitHubError('Connection timeout');
|
||||
expect(result.type).toBe('network');
|
||||
});
|
||||
|
||||
it('should detect "DNS error" pattern', () => {
|
||||
const result = parseGitHubError('DNS error occurred');
|
||||
expect(result.type).toBe('network');
|
||||
});
|
||||
|
||||
it('should detect "offline" pattern', () => {
|
||||
const result = parseGitHubError('You are offline');
|
||||
expect(result.type).toBe('network');
|
||||
});
|
||||
|
||||
it('should detect "no internet" pattern', () => {
|
||||
const result = parseGitHubError('No internet connection');
|
||||
expect(result.type).toBe('network');
|
||||
});
|
||||
|
||||
it('should generate user-friendly message about internet connection', () => {
|
||||
const result = parseGitHubError('Network error');
|
||||
expect(result.message).toContain('internet');
|
||||
});
|
||||
});
|
||||
|
||||
describe('permission errors', () => {
|
||||
it('should detect "403" pattern (without rate limit context)', () => {
|
||||
const result = parseGitHubError('HTTP 403 Forbidden');
|
||||
expect(result.type).toBe('permission');
|
||||
expect(result.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('should detect "forbidden" pattern', () => {
|
||||
const result = parseGitHubError('Access forbidden');
|
||||
expect(result.type).toBe('permission');
|
||||
});
|
||||
|
||||
it('should detect "permission denied" pattern', () => {
|
||||
const result = parseGitHubError('Permission denied');
|
||||
expect(result.type).toBe('permission');
|
||||
});
|
||||
|
||||
it('should detect "insufficient scope" pattern', () => {
|
||||
const result = parseGitHubError('Insufficient scope');
|
||||
expect(result.type).toBe('permission');
|
||||
});
|
||||
|
||||
it('should detect "access denied" pattern', () => {
|
||||
const result = parseGitHubError('Access denied');
|
||||
expect(result.type).toBe('permission');
|
||||
});
|
||||
|
||||
it('should detect "repository access denied" pattern', () => {
|
||||
const result = parseGitHubError('Repository access denied');
|
||||
expect(result.type).toBe('permission');
|
||||
});
|
||||
|
||||
it('should detect "requires admin access" pattern', () => {
|
||||
const result = parseGitHubError('Requires admin access');
|
||||
expect(result.type).toBe('permission');
|
||||
});
|
||||
|
||||
it('should detect "missing required scope" pattern', () => {
|
||||
const result = parseGitHubError('Missing required scope');
|
||||
expect(result.type).toBe('permission');
|
||||
});
|
||||
|
||||
it('should extract required scopes from error message with 403', () => {
|
||||
const result = parseGitHubError('403 Forbidden - missing scopes: repo, read:org');
|
||||
expect(result.type).toBe('permission');
|
||||
expect(result.requiredScopes).toContain('repo');
|
||||
expect(result.requiredScopes).toContain('read:org');
|
||||
});
|
||||
|
||||
it('should extract scopes from "requires:" format with 403', () => {
|
||||
const result = parseGitHubError('403 - Requires: repo, workflow');
|
||||
expect(result.type).toBe('permission');
|
||||
expect(result.requiredScopes).toContain('repo');
|
||||
expect(result.requiredScopes).toContain('workflow');
|
||||
});
|
||||
|
||||
it('should extract scopes from X-Accepted-OAuth-Scopes header with 403', () => {
|
||||
const result = parseGitHubError('403 Forbidden X-Accepted-OAuth-Scopes: repo');
|
||||
expect(result.type).toBe('permission');
|
||||
expect(result.requiredScopes).toContain('repo');
|
||||
});
|
||||
|
||||
it('should generate user-friendly message with scopes', () => {
|
||||
const result = parseGitHubError('403 Forbidden - missing scopes: repo, workflow');
|
||||
expect(result.message).toContain('repo');
|
||||
expect(result.message).toContain('workflow');
|
||||
expect(result.message).toContain('Settings');
|
||||
});
|
||||
|
||||
it('should generate user-friendly message without scopes', () => {
|
||||
const result = parseGitHubError('403 Forbidden');
|
||||
expect(result.message).toContain('permission');
|
||||
expect(result.message).toContain('Settings');
|
||||
});
|
||||
});
|
||||
|
||||
describe('unknown errors', () => {
|
||||
it('should return unknown for unrecognized error patterns', () => {
|
||||
const result = parseGitHubError('Something unexpected happened');
|
||||
expect(result.type).toBe('unknown');
|
||||
expect(result.message).toBeDefined();
|
||||
});
|
||||
|
||||
it('should include raw message for unknown errors', () => {
|
||||
const result = parseGitHubError('Custom error message');
|
||||
expect(result.rawMessage).toBe('Custom error message');
|
||||
});
|
||||
|
||||
it('should extract status code even for unknown errors', () => {
|
||||
const result = parseGitHubError('HTTP 500 Internal Server Error');
|
||||
expect(result.type).toBe('unknown');
|
||||
expect(result.statusCode).toBe(500);
|
||||
});
|
||||
});
|
||||
|
||||
describe('error classification priority', () => {
|
||||
it('should prioritize rate_limit over permission (both 403)', () => {
|
||||
const result = parseGitHubError('403 rate limit exceeded');
|
||||
expect(result.type).toBe('rate_limit');
|
||||
});
|
||||
|
||||
it('should classify as permission when 403 without rate limit context', () => {
|
||||
const result = parseGitHubError('403 forbidden');
|
||||
expect(result.type).toBe('permission');
|
||||
});
|
||||
|
||||
it('should handle errors with multiple patterns correctly', () => {
|
||||
// Rate limit should take priority
|
||||
const result = parseGitHubError('403 API rate limit exceeded');
|
||||
expect(result.type).toBe('rate_limit');
|
||||
});
|
||||
|
||||
it('should prioritize auth over not_found when both patterns present', () => {
|
||||
// "401" should be classified as auth, not not_found
|
||||
const result = parseGitHubError('HTTP 401 Unauthorized - user not found');
|
||||
expect(result.type).toBe('auth');
|
||||
});
|
||||
|
||||
it('should prioritize auth over network when 401 appears with network context', () => {
|
||||
const result = parseGitHubError('Network error: HTTP 401');
|
||||
expect(result.type).toBe('auth');
|
||||
});
|
||||
|
||||
it('should classify as not_found when 404 without auth patterns', () => {
|
||||
const result = parseGitHubError('HTTP 404 Not Found');
|
||||
expect(result.type).toBe('not_found');
|
||||
});
|
||||
|
||||
it('should not match bare 401 in unrelated numbers', () => {
|
||||
// The word boundary should prevent matching "1401" as a 401 error
|
||||
const result = parseGitHubError('Error code 14010 occurred');
|
||||
expect(result.type).toBe('unknown');
|
||||
});
|
||||
|
||||
it('should not match bare 404 embedded in other numbers', () => {
|
||||
// The word boundary should prevent matching "404" embedded in "14040"
|
||||
const result = parseGitHubError('Error code 14040 occurred');
|
||||
expect(result.type).toBe('unknown');
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('should handle multiline error messages', () => {
|
||||
const result = parseGitHubError(`Error occurred:
|
||||
HTTP 401 Unauthorized
|
||||
Please check your credentials`);
|
||||
expect(result.type).toBe('auth');
|
||||
});
|
||||
|
||||
it('should handle case-insensitive matching', () => {
|
||||
const testCases = [
|
||||
{ input: 'RATE LIMIT EXCEEDED', expected: 'rate_limit' as GitHubErrorType },
|
||||
{ input: 'UNAUTHORIZED', expected: 'auth' as GitHubErrorType },
|
||||
{ input: 'NOT FOUND', expected: 'not_found' as GitHubErrorType },
|
||||
{ input: 'NETWORK ERROR', expected: 'network' as GitHubErrorType },
|
||||
{ input: 'FORBIDDEN', expected: 'permission' as GitHubErrorType },
|
||||
];
|
||||
|
||||
for (const { input, expected } of testCases) {
|
||||
const result = parseGitHubError(input);
|
||||
expect(result.type).toBe(expected);
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle errors with JSON content', () => {
|
||||
const result = parseGitHubError('{"message":"Bad credentials","status":401}');
|
||||
expect(result.type).toBe('auth');
|
||||
});
|
||||
|
||||
it('should handle errors with leading/trailing whitespace', () => {
|
||||
const result = parseGitHubError(' 401 Unauthorized ');
|
||||
expect(result.type).toBe('auth');
|
||||
});
|
||||
|
||||
it('should sanitize very long error messages', () => {
|
||||
const longError = 'A'.repeat(1000);
|
||||
const result = parseGitHubError(longError);
|
||||
expect(result.rawMessage?.length).toBeLessThanOrEqual(503);
|
||||
expect(result.rawMessage).toContain('...');
|
||||
});
|
||||
|
||||
it('should not include rateLimitResetTime for non-rate-limit errors', () => {
|
||||
const result = parseGitHubError('401 Unauthorized');
|
||||
expect(result.rateLimitResetTime).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should not include requiredScopes for non-permission errors', () => {
|
||||
const result = parseGitHubError('401 Unauthorized');
|
||||
expect(result.requiredScopes).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('isRateLimitError', () => {
|
||||
it('should return true for rate limit errors', () => {
|
||||
expect(isRateLimitError('rate limit exceeded')).toBe(true);
|
||||
expect(isRateLimitError('API rate limit exceeded')).toBe(true);
|
||||
expect(isRateLimitError('too many requests')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-rate-limit errors', () => {
|
||||
expect(isRateLimitError('401 Unauthorized')).toBe(false);
|
||||
expect(isRateLimitError('404 Not Found')).toBe(false);
|
||||
expect(isRateLimitError('Network error')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for null/undefined/empty', () => {
|
||||
expect(isRateLimitError(null)).toBe(false);
|
||||
expect(isRateLimitError(undefined)).toBe(false);
|
||||
expect(isRateLimitError('')).toBe(false);
|
||||
});
|
||||
|
||||
it('should use parsedInfo when provided', () => {
|
||||
const parsedInfo = { type: 'rate_limit' as const, message: 'test' };
|
||||
expect(isRateLimitError('unrelated error', parsedInfo)).toBe(true);
|
||||
expect(isRateLimitError(null, parsedInfo)).toBe(true);
|
||||
expect(isRateLimitError(undefined, parsedInfo)).toBe(true);
|
||||
});
|
||||
|
||||
it('should ignore parsedInfo when error type differs', () => {
|
||||
const authParsedInfo = { type: 'auth' as const, message: 'test' };
|
||||
expect(isRateLimitError('rate limit exceeded', authParsedInfo)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isAuthError', () => {
|
||||
it('should return true for auth errors', () => {
|
||||
expect(isAuthError('401 Unauthorized')).toBe(true);
|
||||
expect(isAuthError('Bad credentials')).toBe(true);
|
||||
expect(isAuthError('Invalid token')).toBe(true);
|
||||
expect(isAuthError('Not authenticated')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-auth errors', () => {
|
||||
expect(isAuthError('rate limit exceeded')).toBe(false);
|
||||
expect(isAuthError('404 Not Found')).toBe(false);
|
||||
expect(isAuthError('Network error')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for null/undefined/empty', () => {
|
||||
expect(isAuthError(null)).toBe(false);
|
||||
expect(isAuthError(undefined)).toBe(false);
|
||||
expect(isAuthError('')).toBe(false);
|
||||
});
|
||||
|
||||
it('should use parsedInfo when provided', () => {
|
||||
const parsedInfo = { type: 'auth' as const, message: 'test' };
|
||||
expect(isAuthError('unrelated error', parsedInfo)).toBe(true);
|
||||
expect(isAuthError(null, parsedInfo)).toBe(true);
|
||||
expect(isAuthError(undefined, parsedInfo)).toBe(true);
|
||||
});
|
||||
|
||||
it('should ignore parsedInfo when error type differs', () => {
|
||||
const rateLimitParsedInfo = { type: 'rate_limit' as const, message: 'test' };
|
||||
expect(isAuthError('401 Unauthorized', rateLimitParsedInfo)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isNetworkError', () => {
|
||||
it('should return true for network errors', () => {
|
||||
expect(isNetworkError('Network error')).toBe(true);
|
||||
expect(isNetworkError('Failed to fetch')).toBe(true);
|
||||
expect(isNetworkError('ECONNREFUSED')).toBe(true);
|
||||
expect(isNetworkError('Connection timeout')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-network errors', () => {
|
||||
expect(isNetworkError('401 Unauthorized')).toBe(false);
|
||||
expect(isNetworkError('rate limit exceeded')).toBe(false);
|
||||
expect(isNetworkError('404 Not Found')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for null/undefined/empty', () => {
|
||||
expect(isNetworkError(null)).toBe(false);
|
||||
expect(isNetworkError(undefined)).toBe(false);
|
||||
expect(isNetworkError('')).toBe(false);
|
||||
});
|
||||
|
||||
it('should use parsedInfo when provided', () => {
|
||||
const parsedInfo = { type: 'network' as const, message: 'test' };
|
||||
expect(isNetworkError('unrelated error', parsedInfo)).toBe(true);
|
||||
expect(isNetworkError(null, parsedInfo)).toBe(true);
|
||||
expect(isNetworkError(undefined, parsedInfo)).toBe(true);
|
||||
});
|
||||
|
||||
it('should ignore parsedInfo when error type differs', () => {
|
||||
const authParsedInfo = { type: 'auth' as const, message: 'test' };
|
||||
expect(isNetworkError('Network error', authParsedInfo)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isRecoverableError', () => {
|
||||
it('should return true for recoverable errors (rate_limit, network, unknown)', () => {
|
||||
expect(isRecoverableError('rate limit exceeded')).toBe(true);
|
||||
expect(isRecoverableError('Network error')).toBe(true);
|
||||
expect(isRecoverableError('Unknown error occurred')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for non-recoverable errors (auth, permission, not_found)', () => {
|
||||
expect(isRecoverableError('401 Unauthorized')).toBe(false);
|
||||
expect(isRecoverableError('403 Forbidden')).toBe(false);
|
||||
expect(isRecoverableError('404 Not Found')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for null/undefined/empty', () => {
|
||||
expect(isRecoverableError(null)).toBe(false);
|
||||
expect(isRecoverableError(undefined)).toBe(false);
|
||||
expect(isRecoverableError('')).toBe(false);
|
||||
});
|
||||
|
||||
it('should use parsedInfo when provided', () => {
|
||||
const rateLimitInfo = { type: 'rate_limit' as const, message: 'test' };
|
||||
const networkInfo = { type: 'network' as const, message: 'test' };
|
||||
const unknownInfo = { type: 'unknown' as const, message: 'test' };
|
||||
expect(isRecoverableError('unrelated error', rateLimitInfo)).toBe(true);
|
||||
expect(isRecoverableError(null, networkInfo)).toBe(true);
|
||||
expect(isRecoverableError(undefined, unknownInfo)).toBe(true);
|
||||
});
|
||||
|
||||
it('should ignore parsedInfo when error type is non-recoverable', () => {
|
||||
const authParsedInfo = { type: 'auth' as const, message: 'test' };
|
||||
const permissionParsedInfo = { type: 'permission' as const, message: 'test' };
|
||||
const notFoundParsedInfo = { type: 'not_found' as const, message: 'test' };
|
||||
expect(isRecoverableError('Network error', authParsedInfo)).toBe(false);
|
||||
expect(isRecoverableError('rate limit exceeded', permissionParsedInfo)).toBe(false);
|
||||
expect(isRecoverableError('unknown', notFoundParsedInfo)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('requiresSettingsAction', () => {
|
||||
it('should return true for errors requiring settings action (auth, permission)', () => {
|
||||
expect(requiresSettingsAction('401 Unauthorized')).toBe(true);
|
||||
expect(requiresSettingsAction('403 Forbidden')).toBe(true);
|
||||
expect(requiresSettingsAction('Invalid token')).toBe(true);
|
||||
expect(requiresSettingsAction('403 Forbidden - missing scopes: repo')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for errors not requiring settings (rate_limit, network, not_found, unknown)', () => {
|
||||
expect(requiresSettingsAction('rate limit exceeded')).toBe(false);
|
||||
expect(requiresSettingsAction('Network error')).toBe(false);
|
||||
expect(requiresSettingsAction('404 Not Found')).toBe(false);
|
||||
expect(requiresSettingsAction('Unknown error')).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for null/undefined/empty', () => {
|
||||
expect(requiresSettingsAction(null)).toBe(false);
|
||||
expect(requiresSettingsAction(undefined)).toBe(false);
|
||||
expect(requiresSettingsAction('')).toBe(false);
|
||||
});
|
||||
|
||||
it('should use parsedInfo when provided', () => {
|
||||
const authInfo = { type: 'auth' as const, message: 'test' };
|
||||
const permissionInfo = { type: 'permission' as const, message: 'test' };
|
||||
expect(requiresSettingsAction('unrelated error', authInfo)).toBe(true);
|
||||
expect(requiresSettingsAction(null, permissionInfo)).toBe(true);
|
||||
expect(requiresSettingsAction(undefined, authInfo)).toBe(true);
|
||||
});
|
||||
|
||||
it('should ignore parsedInfo when error type does not require settings', () => {
|
||||
const rateLimitInfo = { type: 'rate_limit' as const, message: 'test' };
|
||||
const networkInfo = { type: 'network' as const, message: 'test' };
|
||||
const notFoundInfo = { type: 'not_found' as const, message: 'test' };
|
||||
expect(requiresSettingsAction('401 Unauthorized', rateLimitInfo)).toBe(false);
|
||||
expect(requiresSettingsAction('403 Forbidden', networkInfo)).toBe(false);
|
||||
expect(requiresSettingsAction('invalid token', notFoundInfo)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cross-cutting concerns', () => {
|
||||
describe('consistency between parseGitHubError and helper functions', () => {
|
||||
it('should have consistent rate_limit detection', () => {
|
||||
const error = 'rate limit exceeded';
|
||||
const parsed = parseGitHubError(error);
|
||||
expect(parsed.type).toBe('rate_limit');
|
||||
expect(isRateLimitError(error)).toBe(true);
|
||||
});
|
||||
|
||||
it('should have consistent auth detection', () => {
|
||||
const error = '401 Unauthorized';
|
||||
const parsed = parseGitHubError(error);
|
||||
expect(parsed.type).toBe('auth');
|
||||
expect(isAuthError(error)).toBe(true);
|
||||
});
|
||||
|
||||
it('should have consistent network detection', () => {
|
||||
const error = 'Network error';
|
||||
const parsed = parseGitHubError(error);
|
||||
expect(parsed.type).toBe('network');
|
||||
expect(isNetworkError(error)).toBe(true);
|
||||
});
|
||||
|
||||
it('should have consistent recoverable classification', () => {
|
||||
const errors = ['rate limit exceeded', 'Network error', 'Unknown error'];
|
||||
for (const error of errors) {
|
||||
const parsed = parseGitHubError(error);
|
||||
expect(isRecoverableError(error)).toBe(['rate_limit', 'network', 'unknown'].includes(parsed.type));
|
||||
}
|
||||
});
|
||||
|
||||
it('should have consistent settings action classification', () => {
|
||||
const errors = ['401 Unauthorized', '403 Forbidden'];
|
||||
for (const error of errors) {
|
||||
const parsed = parseGitHubError(error);
|
||||
expect(requiresSettingsAction(error)).toBe(['auth', 'permission'].includes(parsed.type));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('statusCode extraction', () => {
|
||||
it('should extract 403 for rate_limit errors', () => {
|
||||
const result = parseGitHubError('rate limit exceeded');
|
||||
expect(result.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('should extract 401 for auth errors', () => {
|
||||
const result = parseGitHubError('Bad credentials');
|
||||
expect(result.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('should extract 404 for not_found errors', () => {
|
||||
const result = parseGitHubError('Not found');
|
||||
expect(result.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('should extract 403 for permission errors', () => {
|
||||
const result = parseGitHubError('Forbidden');
|
||||
expect(result.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('should extract status code from message when present', () => {
|
||||
const result = parseGitHubError('HTTP 429 Too Many Requests');
|
||||
expect(result.statusCode).toBe(429);
|
||||
});
|
||||
|
||||
it('should not extract invalid status codes', () => {
|
||||
const result = parseGitHubError('Error 999');
|
||||
expect(result.statusCode).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,497 @@
|
||||
/**
|
||||
* GitHub API error parser utility.
|
||||
* Parses raw error strings to classify GitHub API errors and extract metadata.
|
||||
*/
|
||||
|
||||
import type { GitHubErrorType, GitHubErrorInfo } from '../types';
|
||||
|
||||
/**
|
||||
* Maximum length for raw error messages stored in GitHubErrorInfo.
|
||||
* Truncates to prevent memory bloat and UI issues.
|
||||
*/
|
||||
const MAX_RAW_ERROR_LENGTH = 500;
|
||||
|
||||
/**
|
||||
* Patterns for rate limit errors (HTTP 403 with rate limit context).
|
||||
* Note: Pattern 1 covers all "rate limit" variations (api rate limit exceeded,
|
||||
* abuse rate limit, secondary rate limit, etc.) via substring matching.
|
||||
*/
|
||||
const RATE_LIMIT_PATTERNS = [
|
||||
/rate\s*limit/i, // Covers all variations containing "rate limit"
|
||||
/too\s*many\s*requests/i,
|
||||
/403.*rate/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* Patterns for authentication errors (HTTP 401)
|
||||
* Note: Bare status codes are intentionally omitted here - STATUS_CODE_PATTERN
|
||||
* handles HTTP-context-aware matching to avoid false positives.
|
||||
*/
|
||||
const AUTH_PATTERNS = [
|
||||
/unauthorized/i,
|
||||
/bad\s*credentials/i,
|
||||
/authentication\s*failed/i,
|
||||
/invalid\s*(oauth\s*)?token/i,
|
||||
/token\s*(is\s*)?(invalid|expired|required)/i,
|
||||
/not\s*authenticated/i,
|
||||
/requires\s*authentication/i, // GitHub 401 response body
|
||||
];
|
||||
|
||||
/**
|
||||
* Patterns for permission/scope errors (HTTP 403 with scope context)
|
||||
* Note: Bare status codes are intentionally omitted here - STATUS_CODE_PATTERN
|
||||
* handles HTTP-context-aware matching to avoid false positives.
|
||||
*/
|
||||
const PERMISSION_PATTERNS = [
|
||||
/forbidden/i,
|
||||
/permission\s*denied/i,
|
||||
/insufficient\s*(scope|permission)/i,
|
||||
/access\s*denied/i,
|
||||
/repository\s*access\s*denied/i,
|
||||
/not\s*authorized\s*to\s*access/i,
|
||||
/requires\s*(admin|write|read)\s*access/i,
|
||||
/missing\s*required\s*scope/i,
|
||||
// Matches "requires: repo" or "requires workflow" for OAuth scope context
|
||||
// Uses specific scope names to avoid matching "requires authentication" (auth error)
|
||||
/requires[:\s]+(?:repo|admin|write|read|workflow|org|gist|notification|user|project|package|delete|discussion)/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* Patterns for not found errors (HTTP 404)
|
||||
* Note: Bare status codes are intentionally omitted here - STATUS_CODE_PATTERN
|
||||
* handles HTTP-context-aware matching to avoid false positives (e.g., "Issue #404").
|
||||
*/
|
||||
const NOT_FOUND_PATTERNS = [
|
||||
/not\s*found/i,
|
||||
/no\s*such\s*(repository|repo|issue|resource)/i,
|
||||
/does\s*not\s*exist/i,
|
||||
/repository\s*not\s*found/i,
|
||||
/user\s*not\s*found/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* Patterns for network/connectivity errors
|
||||
*/
|
||||
const NETWORK_PATTERNS = [
|
||||
/network\s*(error|failed|unreachable)/i,
|
||||
/failed\s*to\s*fetch/i,
|
||||
/enetunreach/i,
|
||||
/econnrefused/i,
|
||||
/econnreset/i,
|
||||
/etimedout/i,
|
||||
/dns\s*(error|failed)/i,
|
||||
/offline/i,
|
||||
/no\s*internet/i,
|
||||
/unable\s*to\s*connect/i,
|
||||
/connection\s*(refused|reset|timeout|failed)/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* Pattern to extract required OAuth scopes from error messages
|
||||
* Matches formats like:
|
||||
* - "requires: repo, read:org"
|
||||
* - "missing scopes: repo, workflow"
|
||||
* - "X-Accepted-OAuth-Scopes: repo"
|
||||
* Stops at sentence boundaries or non-scope characters
|
||||
*/
|
||||
const REQUIRED_SCOPES_PATTERN = /(?:requires?[:\s]*|missing\s*scopes?[:\s]*|X-Accepted-OAuth-Scopes[:\s]*)([a-z0-9_:]+(?:[,\s]+[a-z0-9_:]+)*)/i;
|
||||
|
||||
/**
|
||||
* Pattern to extract HTTP status code from error messages.
|
||||
* Matches status codes preceded by HTTP context keywords or at string start
|
||||
* (for common error formats like "403 Forbidden").
|
||||
*/
|
||||
const STATUS_CODE_PATTERN = /(?:^|HTTP\s*|status[:\s]*|error[:\s]*|code[:\s]*)\b([1-5]\d{2})\b/i;
|
||||
|
||||
/**
|
||||
* Sanitize error output to a reasonable length.
|
||||
* Prevents memory bloat and UI issues from very long error messages.
|
||||
*/
|
||||
function sanitizeRawError(error: string): string {
|
||||
if (error.length > MAX_RAW_ERROR_LENGTH) {
|
||||
return error.substring(0, MAX_RAW_ERROR_LENGTH) + '...';
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maximum reasonable reset duration in seconds (24 hours).
|
||||
* Prevents malformed error strings from creating far-future dates.
|
||||
*/
|
||||
const MAX_RESET_SECONDS = 86400;
|
||||
|
||||
/**
|
||||
* Extract rate limit reset time from error message.
|
||||
* Parses various formats and returns a Date object if found.
|
||||
* Handles both absolute timestamps and relative durations ("in X seconds").
|
||||
*/
|
||||
function extractRateLimitResetTime(error: string): Date | undefined {
|
||||
// First, try to match relative duration pattern (e.g., "reset in 3600 seconds")
|
||||
const relativePattern = /reset[s]?\s*in[:\s]*(\d+)\s*seconds?/i;
|
||||
const relativeMatch = error.match(relativePattern);
|
||||
if (relativeMatch) {
|
||||
const seconds = parseInt(relativeMatch[1], 10);
|
||||
// Validate: positive, non-NaN, and within reasonable bounds (24 hours max)
|
||||
if (!Number.isNaN(seconds) && seconds > 0 && seconds <= MAX_RESET_SECONDS) {
|
||||
return new Date(Date.now() + seconds * 1000);
|
||||
}
|
||||
}
|
||||
|
||||
// Then try absolute timestamp pattern
|
||||
const absolutePattern = /(?:reset[s]?\s*at[:\s]*|X-RateLimit-Reset[:\s]*)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z?|\d+)/i;
|
||||
const match = error.match(absolutePattern);
|
||||
if (!match) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const resetValue = match[1].trim();
|
||||
|
||||
// Check if it's an ISO date string
|
||||
if (resetValue.includes('-') && resetValue.includes('T')) {
|
||||
const date = new Date(resetValue);
|
||||
if (Number.isNaN(date.getTime())) return undefined;
|
||||
// Validate: within reasonable bounds (24 hours max from now)
|
||||
if (date.getTime() - Date.now() > MAX_RESET_SECONDS * 1000) return undefined;
|
||||
return date;
|
||||
}
|
||||
|
||||
// Check if it's a Unix timestamp (seconds or milliseconds)
|
||||
const numericValue = parseInt(resetValue, 10);
|
||||
if (!Number.isNaN(numericValue)) {
|
||||
// GitHub API uses seconds, JavaScript uses milliseconds
|
||||
// Values > 1e12 are likely milliseconds already
|
||||
const timestamp = numericValue > 1e12 ? numericValue : numericValue * 1000;
|
||||
const date = new Date(timestamp);
|
||||
if (Number.isNaN(date.getTime())) return undefined;
|
||||
// Validate: within reasonable bounds (24 hours max from now)
|
||||
if (date.getTime() - Date.now() > MAX_RESET_SECONDS * 1000) return undefined;
|
||||
return date;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract required OAuth scopes from error message.
|
||||
* Returns an array of scope strings if found.
|
||||
*/
|
||||
function extractRequiredScopes(error: string): string[] | undefined {
|
||||
const match = error.match(REQUIRED_SCOPES_PATTERN);
|
||||
if (!match) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const scopes = match[1]
|
||||
.split(/[,\s]+/)
|
||||
.map(s => s.trim())
|
||||
.filter(s => s.length > 0);
|
||||
|
||||
return scopes.length > 0 ? scopes : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract HTTP status code from error message.
|
||||
*/
|
||||
function extractStatusCode(error: string): number | undefined {
|
||||
const match = error.match(STATUS_CODE_PATTERN);
|
||||
if (!match) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const code = parseInt(match[1], 10);
|
||||
// Only return valid HTTP status codes
|
||||
if (code >= 100 && code < 600) {
|
||||
return code;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the error matches any of the given patterns.
|
||||
*/
|
||||
function matchesPatterns(error: string, patterns: RegExp[]): boolean {
|
||||
return patterns.some(pattern => pattern.test(error));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user-friendly message for rate limit errors.
|
||||
*/
|
||||
function getRateLimitMessage(_error: string, resetTime?: Date): string {
|
||||
if (resetTime) {
|
||||
const now = new Date();
|
||||
const diffMs = resetTime.getTime() - now.getTime();
|
||||
|
||||
if (diffMs > 0) {
|
||||
const diffMins = Math.ceil(diffMs / 60000);
|
||||
if (diffMins < 60) {
|
||||
return `GitHub API rate limit reached. Please wait ${diffMins} minute${diffMins !== 1 ? 's' : ''} before trying again.`;
|
||||
}
|
||||
const diffHours = Math.ceil(diffMins / 60);
|
||||
return `GitHub API rate limit reached. Rate limit resets in approximately ${diffHours} hour${diffHours !== 1 ? 's' : ''}.`;
|
||||
}
|
||||
}
|
||||
|
||||
return 'GitHub API rate limit reached. Please wait a moment before trying again.';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user-friendly message for authentication errors.
|
||||
*/
|
||||
function getAuthMessage(): string {
|
||||
return 'GitHub authentication failed. Please check your GitHub token in Settings and try again.';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user-friendly message for permission errors.
|
||||
*/
|
||||
function getPermissionMessage(scopes?: string[]): string {
|
||||
if (scopes && scopes.length > 0) {
|
||||
return `GitHub permission denied. Your token is missing required scopes: ${scopes.join(', ')}. Please update your GitHub token in Settings.`;
|
||||
}
|
||||
return 'GitHub permission denied. Your token may not have the required access. Please check your token permissions in Settings.';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user-friendly message for not found errors.
|
||||
*/
|
||||
function getNotFoundMessage(): string {
|
||||
return 'The requested GitHub resource was not found. Please verify the repository exists and you have access to it.';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user-friendly message for network errors.
|
||||
*/
|
||||
function getNetworkMessage(): string {
|
||||
return 'Unable to connect to GitHub. Please check your internet connection and try again.';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user-friendly message for unknown errors.
|
||||
*/
|
||||
function getUnknownMessage(): string {
|
||||
return 'An unexpected error occurred while communicating with GitHub. Please try again.';
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify error type based on pattern matching and optional status code.
|
||||
* Priority: rate_limit > auth > permission > not_found > network > unknown
|
||||
* Note: Permission checks run before not_found to properly classify 403 responses.
|
||||
* Status code fallback takes priority over network patterns since HTTP status
|
||||
* codes are more specific than generic network error text.
|
||||
* @param error - The error string to classify
|
||||
* @param statusCode - Optional HTTP status code extracted with context (helps classify when text patterns don't match)
|
||||
*/
|
||||
function classifyError(error: string, statusCode?: number): GitHubErrorType {
|
||||
// Check rate limit first (403 can also be permission, but rate limit is more specific)
|
||||
if (matchesPatterns(error, RATE_LIMIT_PATTERNS)) {
|
||||
return 'rate_limit';
|
||||
}
|
||||
|
||||
// Check auth (401 is always auth)
|
||||
if (matchesPatterns(error, AUTH_PATTERNS)) {
|
||||
return 'auth';
|
||||
}
|
||||
|
||||
// Check permission (403 without rate limit context) before not_found
|
||||
// to properly classify 403 responses that might contain "not found" text
|
||||
if (matchesPatterns(error, PERMISSION_PATTERNS)) {
|
||||
return 'permission';
|
||||
}
|
||||
|
||||
// Check not found (404 is always not_found)
|
||||
if (matchesPatterns(error, NOT_FOUND_PATTERNS)) {
|
||||
return 'not_found';
|
||||
}
|
||||
|
||||
// Use status code fallback BEFORE network patterns
|
||||
// HTTP status codes are more specific than generic network error text
|
||||
if (statusCode === 401) return 'auth';
|
||||
if (statusCode === 403) return 'permission';
|
||||
if (statusCode === 404) return 'not_found';
|
||||
|
||||
// Check network errors (only if no status code fallback matched)
|
||||
if (matchesPatterns(error, NETWORK_PATTERNS)) {
|
||||
return 'network';
|
||||
}
|
||||
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a GitHub API error string and return classified error information.
|
||||
*
|
||||
* IMPORTANT: The returned `message` field contains hardcoded English strings
|
||||
* intended ONLY as a fallback defaultValue for i18n translation. Consumers
|
||||
* should use the `type` field to look up the appropriate translation key
|
||||
* (e.g., 'githubErrors.rateLimitMessage') via react-i18next rather than
|
||||
* displaying `message` directly. This ensures proper localization.
|
||||
*
|
||||
* Translation key mapping by type:
|
||||
* - rate_limit → 'githubErrors.rateLimitMessage' (or rateLimitMessageMinutes/Hours)
|
||||
* - auth → 'githubErrors.authMessage'
|
||||
* - permission → 'githubErrors.permissionMessage' (or permissionMessageScopes)
|
||||
* - not_found → 'githubErrors.notFoundMessage'
|
||||
* - network → 'githubErrors.networkMessage'
|
||||
* - unknown → 'githubErrors.unknownMessage'
|
||||
*
|
||||
* @param error - The raw error string (typically from issues-store error state)
|
||||
* @returns GitHubErrorInfo object with classified type, user-friendly message, and metadata
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const errorInfo = parseGitHubError('GitHub API error: 403 - API rate limit exceeded');
|
||||
* // Use type to get i18n key, message only as fallback:
|
||||
* // t(`githubErrors.${errorInfo.type}Message`, { defaultValue: errorInfo.message })
|
||||
* ```
|
||||
*/
|
||||
export function parseGitHubError(error: string | null | undefined): GitHubErrorInfo {
|
||||
// Handle null/undefined/empty errors
|
||||
if (!error || typeof error !== 'string' || error.trim() === '') {
|
||||
return {
|
||||
type: 'unknown',
|
||||
message: getUnknownMessage(),
|
||||
};
|
||||
}
|
||||
|
||||
const trimmedError = error.trim();
|
||||
// Extract status code first so we can use it for classification fallback
|
||||
const statusCode = extractStatusCode(trimmedError);
|
||||
const errorType = classifyError(trimmedError, statusCode);
|
||||
|
||||
switch (errorType) {
|
||||
case 'rate_limit': {
|
||||
const resetTime = extractRateLimitResetTime(trimmedError);
|
||||
return {
|
||||
type: 'rate_limit',
|
||||
message: getRateLimitMessage(trimmedError, resetTime),
|
||||
rawMessage: sanitizeRawError(trimmedError),
|
||||
rateLimitResetTime: resetTime,
|
||||
statusCode: statusCode ?? 403,
|
||||
};
|
||||
}
|
||||
|
||||
case 'auth':
|
||||
return {
|
||||
type: 'auth',
|
||||
message: getAuthMessage(),
|
||||
rawMessage: sanitizeRawError(trimmedError),
|
||||
statusCode: statusCode ?? 401,
|
||||
};
|
||||
|
||||
case 'permission': {
|
||||
const scopes = extractRequiredScopes(trimmedError);
|
||||
return {
|
||||
type: 'permission',
|
||||
message: getPermissionMessage(scopes),
|
||||
rawMessage: sanitizeRawError(trimmedError),
|
||||
requiredScopes: scopes,
|
||||
statusCode: statusCode ?? 403,
|
||||
};
|
||||
}
|
||||
|
||||
case 'not_found':
|
||||
return {
|
||||
type: 'not_found',
|
||||
message: getNotFoundMessage(),
|
||||
rawMessage: sanitizeRawError(trimmedError),
|
||||
statusCode: statusCode ?? 404,
|
||||
};
|
||||
|
||||
case 'network':
|
||||
return {
|
||||
type: 'network',
|
||||
message: getNetworkMessage(),
|
||||
rawMessage: sanitizeRawError(trimmedError),
|
||||
};
|
||||
|
||||
default:
|
||||
return {
|
||||
type: 'unknown',
|
||||
message: getUnknownMessage(),
|
||||
rawMessage: sanitizeRawError(trimmedError),
|
||||
statusCode,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an error is a rate limit error.
|
||||
* Convenience function for quick checks without full parsing.
|
||||
* @param error - Raw error string or null/undefined
|
||||
* @param parsedInfo - Optional pre-parsed GitHubErrorInfo to avoid re-classification
|
||||
*/
|
||||
export function isRateLimitError(
|
||||
error: string | null | undefined,
|
||||
parsedInfo?: GitHubErrorInfo | null
|
||||
): boolean {
|
||||
if (parsedInfo) return parsedInfo.type === 'rate_limit';
|
||||
if (!error) return false;
|
||||
const trimmed = error.trim();
|
||||
return classifyError(trimmed, extractStatusCode(trimmed)) === 'rate_limit';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an error is an authentication error.
|
||||
* Convenience function for quick checks without full parsing.
|
||||
* @param error - Raw error string or null/undefined
|
||||
* @param parsedInfo - Optional pre-parsed GitHubErrorInfo to avoid re-classification
|
||||
*/
|
||||
export function isAuthError(
|
||||
error: string | null | undefined,
|
||||
parsedInfo?: GitHubErrorInfo | null
|
||||
): boolean {
|
||||
if (parsedInfo) return parsedInfo.type === 'auth';
|
||||
if (!error) return false;
|
||||
const trimmed = error.trim();
|
||||
return classifyError(trimmed, extractStatusCode(trimmed)) === 'auth';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an error is a network error.
|
||||
* Convenience function for quick checks without full parsing.
|
||||
* @param error - Raw error string or null/undefined
|
||||
* @param parsedInfo - Optional pre-parsed GitHubErrorInfo to avoid re-classification
|
||||
*/
|
||||
export function isNetworkError(
|
||||
error: string | null | undefined,
|
||||
parsedInfo?: GitHubErrorInfo | null
|
||||
): boolean {
|
||||
if (parsedInfo) return parsedInfo.type === 'network';
|
||||
if (!error) return false;
|
||||
const trimmed = error.trim();
|
||||
return classifyError(trimmed, extractStatusCode(trimmed)) === 'network';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an error is recoverable (user can retry).
|
||||
* Rate limit, network, and unknown errors are considered recoverable.
|
||||
* @param error - Raw error string or null/undefined
|
||||
* @param parsedInfo - Optional pre-parsed GitHubErrorInfo to avoid re-classification
|
||||
*/
|
||||
export function isRecoverableError(
|
||||
error: string | null | undefined,
|
||||
parsedInfo?: GitHubErrorInfo | null
|
||||
): boolean {
|
||||
if (parsedInfo) return ['rate_limit', 'network', 'unknown'].includes(parsedInfo.type);
|
||||
if (!error) return false;
|
||||
const trimmed = error.trim();
|
||||
const errorType = classifyError(trimmed, extractStatusCode(trimmed));
|
||||
return ['rate_limit', 'network', 'unknown'].includes(errorType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if an error requires user action in settings.
|
||||
* Auth and permission errors require settings changes.
|
||||
* @param error - Raw error string or null/undefined
|
||||
* @param parsedInfo - Optional pre-parsed GitHubErrorInfo to avoid re-classification
|
||||
*/
|
||||
export function requiresSettingsAction(
|
||||
error: string | null | undefined,
|
||||
parsedInfo?: GitHubErrorInfo | null
|
||||
): boolean {
|
||||
if (parsedInfo) return ['auth', 'permission'].includes(parsedInfo.type);
|
||||
if (!error) return false;
|
||||
const trimmed = error.trim();
|
||||
const errorType = classifyError(trimmed, extractStatusCode(trimmed));
|
||||
return ['auth', 'permission'].includes(errorType);
|
||||
}
|
||||
@@ -19,3 +19,13 @@ export function filterIssuesBySearch(issues: GitHubIssue[], searchQuery: string)
|
||||
issue.body?.toLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
|
||||
// Re-export GitHub error parser utilities
|
||||
export {
|
||||
parseGitHubError,
|
||||
isRateLimitError,
|
||||
isAuthError,
|
||||
isNetworkError,
|
||||
isRecoverableError,
|
||||
requiresSettingsAction,
|
||||
} from './github-error-parser';
|
||||
|
||||
@@ -88,32 +88,32 @@ export function IdeaCard({ idea, isSelected, onClick, onConvert, onGoToTask, onD
|
||||
{idea.status}
|
||||
</Badge>
|
||||
)}
|
||||
{isCodeImprovementIdea(idea) && (
|
||||
{isCodeImprovementIdea(idea) && typeof (idea as CodeImprovementIdea).estimatedEffort === 'string' && (
|
||||
<Badge variant="outline" className={IDEATION_EFFORT_COLORS[(idea as CodeImprovementIdea).estimatedEffort]}>
|
||||
{(idea as CodeImprovementIdea).estimatedEffort}
|
||||
</Badge>
|
||||
)}
|
||||
{isUIUXIdea(idea) && (
|
||||
{isUIUXIdea(idea) && typeof (idea as UIUXImprovementIdea).category === 'string' && (
|
||||
<Badge variant="outline">
|
||||
{UIUX_CATEGORY_LABELS[(idea as UIUXImprovementIdea).category]}
|
||||
</Badge>
|
||||
)}
|
||||
{isDocumentationGapIdea(idea) && (
|
||||
{isDocumentationGapIdea(idea) && typeof (idea as DocumentationGapIdea).category === 'string' && (
|
||||
<Badge variant="outline">
|
||||
{DOCUMENTATION_CATEGORY_LABELS[(idea as DocumentationGapIdea).category]}
|
||||
</Badge>
|
||||
)}
|
||||
{isSecurityHardeningIdea(idea) && (
|
||||
{isSecurityHardeningIdea(idea) && typeof (idea as SecurityHardeningIdea).severity === 'string' && (
|
||||
<Badge variant="outline" className={SECURITY_SEVERITY_COLORS[(idea as SecurityHardeningIdea).severity]}>
|
||||
{(idea as SecurityHardeningIdea).severity}
|
||||
</Badge>
|
||||
)}
|
||||
{isPerformanceOptimizationIdea(idea) && (
|
||||
{isPerformanceOptimizationIdea(idea) && typeof (idea as PerformanceOptimizationIdea).impact === 'string' && (
|
||||
<Badge variant="outline" className={IDEATION_IMPACT_COLORS[(idea as PerformanceOptimizationIdea).impact]}>
|
||||
{(idea as PerformanceOptimizationIdea).impact} impact
|
||||
</Badge>
|
||||
)}
|
||||
{isCodeQualityIdea(idea) && (
|
||||
{isCodeQualityIdea(idea) && typeof (idea as CodeQualityIdea).severity === 'string' && (
|
||||
<Badge variant="outline" className={CODE_QUALITY_SEVERITY_COLORS[(idea as CodeQualityIdea).severity]}>
|
||||
{(idea as CodeQualityIdea).severity}
|
||||
</Badge>
|
||||
|
||||
@@ -457,7 +457,7 @@ export function MemoryStep({ onNext, onBack }: MemoryStepProps) {
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label className="text-xs text-muted-foreground">{t('memory.embeddingModel')}</Label>
|
||||
<OllamaModelSelector
|
||||
<OllamaModelSelector
|
||||
selectedModel={config.ollamaEmbeddingModel}
|
||||
baseUrl={config.ollamaBaseUrl}
|
||||
onModelSelect={(model, dim) => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ExternalLink, Play, TrendingUp } from 'lucide-react';
|
||||
import { TaskOutcomeBadge, getTaskOutcomeColorClass } from './TaskOutcomeBadge';
|
||||
import { Badge } from '../ui/badge';
|
||||
import { Button } from '../ui/button';
|
||||
import { Card } from '../ui/card';
|
||||
@@ -18,6 +19,7 @@ export function FeatureCard({
|
||||
onGoToTask,
|
||||
hasCompetitorInsight = false,
|
||||
}: FeatureCardProps) {
|
||||
|
||||
return (
|
||||
<Card className="p-4 hover:bg-muted/50 cursor-pointer transition-colors" onClick={onClick}>
|
||||
<div className="flex items-start justify-between">
|
||||
@@ -53,7 +55,11 @@ export function FeatureCard({
|
||||
<h3 className="font-medium">{feature.title}</h3>
|
||||
<p className="text-sm text-muted-foreground line-clamp-2">{feature.description}</p>
|
||||
</div>
|
||||
{feature.linkedSpecId ? (
|
||||
{feature.taskOutcome ? (
|
||||
<Badge variant="outline" className={`text-xs ${getTaskOutcomeColorClass(feature.taskOutcome)}`}>
|
||||
<TaskOutcomeBadge outcome={feature.taskOutcome} size="md" />
|
||||
</Badge>
|
||||
) : feature.linkedSpecId ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
TrendingUp,
|
||||
Trash2,
|
||||
} from 'lucide-react';
|
||||
import { TaskOutcomeBadge } from './TaskOutcomeBadge';
|
||||
import { Badge } from '../ui/badge';
|
||||
import { Button } from '../ui/button';
|
||||
import { Card } from '../ui/card';
|
||||
@@ -214,7 +215,13 @@ export function FeatureDetailPanel({
|
||||
</ScrollArea>
|
||||
|
||||
{/* Actions */}
|
||||
{feature.linkedSpecId ? (
|
||||
{feature.taskOutcome ? (
|
||||
<div className="shrink-0 p-4 border-t border-border">
|
||||
<div className="flex items-center justify-center gap-2 py-2">
|
||||
<TaskOutcomeBadge outcome={feature.taskOutcome} size="lg" />
|
||||
</div>
|
||||
</div>
|
||||
) : feature.linkedSpecId ? (
|
||||
<div className="shrink-0 p-4 border-t border-border">
|
||||
<Button className="w-full" onClick={() => onGoToTask(feature.linkedSpecId!)}>
|
||||
<ExternalLink className="h-4 w-4 mr-2" />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { CheckCircle2, Circle, ExternalLink, Play, TrendingUp } from 'lucide-react';
|
||||
import { TaskOutcomeBadge } from './TaskOutcomeBadge';
|
||||
import { Badge } from '../ui/badge';
|
||||
import { Button } from '../ui/button';
|
||||
import { Card } from '../ui/card';
|
||||
@@ -104,7 +105,11 @@ export function PhaseCard({
|
||||
<TrendingUp className="h-3 w-3 text-primary flex-shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
{feature.status === 'done' ? (
|
||||
{feature.taskOutcome ? (
|
||||
<span className="flex-shrink-0">
|
||||
<TaskOutcomeBadge outcome={feature.taskOutcome} size="lg" showLabel={false} />
|
||||
</span>
|
||||
) : feature.status === 'done' ? (
|
||||
<CheckCircle2 className="h-4 w-4 text-success flex-shrink-0" />
|
||||
) : feature.linkedSpecId ? (
|
||||
<Button
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Archive, CheckCircle2, Trash2 } from 'lucide-react';
|
||||
import type { TaskOutcome } from '../../../shared/types';
|
||||
|
||||
interface TaskOutcomeConfig {
|
||||
icon: typeof CheckCircle2;
|
||||
label: string;
|
||||
colorClass: string;
|
||||
}
|
||||
|
||||
function useTaskOutcomeConfig(outcome: TaskOutcome): TaskOutcomeConfig {
|
||||
const { t } = useTranslation('common');
|
||||
|
||||
switch (outcome) {
|
||||
case 'completed':
|
||||
return { icon: CheckCircle2, label: t('roadmap.taskCompleted'), colorClass: 'text-success' };
|
||||
case 'archived':
|
||||
return { icon: Archive, label: t('roadmap.taskArchived'), colorClass: 'text-success' };
|
||||
case 'deleted':
|
||||
return { icon: Trash2, label: t('roadmap.taskDeleted'), colorClass: 'text-muted-foreground' };
|
||||
}
|
||||
}
|
||||
|
||||
export type TaskOutcomeBadgeSize = 'sm' | 'md' | 'lg';
|
||||
|
||||
const ICON_SIZES: Record<TaskOutcomeBadgeSize, string> = {
|
||||
sm: 'h-2.5 w-2.5',
|
||||
md: 'h-3 w-3',
|
||||
lg: 'h-4 w-4',
|
||||
};
|
||||
|
||||
interface TaskOutcomeBadgeProps {
|
||||
outcome: TaskOutcome;
|
||||
size?: TaskOutcomeBadgeSize;
|
||||
showLabel?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a consistent task outcome icon + label across all roadmap views.
|
||||
* Returns the icon and label as inline elements (caller wraps in Badge/div as needed).
|
||||
*/
|
||||
export function TaskOutcomeBadge({ outcome, size = 'md', showLabel = true }: TaskOutcomeBadgeProps) {
|
||||
const config = useTaskOutcomeConfig(outcome);
|
||||
const Icon = config.icon;
|
||||
const iconSize = ICON_SIZES[size];
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-0.5 ${config.colorClass}`}>
|
||||
<Icon className={iconSize} />
|
||||
{showLabel && <span>{config.label}</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the color class for a task outcome (for use in parent wrapper styling).
|
||||
*/
|
||||
export function getTaskOutcomeColorClass(outcome: TaskOutcome): string {
|
||||
return outcome === 'deleted' ? 'text-muted-foreground border-muted-foreground/50' : 'text-success border-success/50';
|
||||
}
|
||||
@@ -662,4 +662,3 @@ function AutoSyncToggle({ enabled, onToggle }: AutoSyncToggleProps) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -210,14 +210,14 @@ export function StagedInProjectMessage({ task, projectPath, hasWorktree = false,
|
||||
|
||||
const handleReviewAgain = async () => {
|
||||
if (!onReviewAgain) return;
|
||||
|
||||
|
||||
setIsResetting(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Clear the staged flag via IPC
|
||||
const result = await window.electronAPI.clearStagedState(task.id);
|
||||
|
||||
|
||||
if (!result.success) {
|
||||
setError(result.error || 'Failed to reset staged state');
|
||||
return;
|
||||
@@ -297,7 +297,7 @@ export function StagedInProjectMessage({ task, projectPath, hasWorktree = false,
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
{/* Secondary actions row */}
|
||||
<div className="flex gap-2">
|
||||
{/* Mark Done Only (when worktree exists) - allows keeping worktree */}
|
||||
@@ -322,7 +322,7 @@ export function StagedInProjectMessage({ task, projectPath, hasWorktree = false,
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
|
||||
{/* Review Again button - only show if worktree exists and callback provided */}
|
||||
{hasWorktree && onReviewAgain && (
|
||||
<Button
|
||||
@@ -346,11 +346,11 @@ export function StagedInProjectMessage({ task, projectPath, hasWorktree = false,
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
{error && (
|
||||
<p className="text-xs text-destructive">{error}</p>
|
||||
)}
|
||||
|
||||
|
||||
{hasWorktree && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
"Delete Worktree & Mark Done" cleans up the isolated workspace. "Mark Done Only" keeps it for reference.
|
||||
|
||||
@@ -1,149 +1 @@
|
||||
import * as React from 'react';
|
||||
import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog';
|
||||
import { cn } from '../../lib/utils';
|
||||
import { buttonVariants } from './button';
|
||||
|
||||
const AlertDialog = AlertDialogPrimitive.Root;
|
||||
|
||||
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
|
||||
|
||||
const AlertDialogPortal = AlertDialogPrimitive.Portal;
|
||||
|
||||
const AlertDialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-black/80 backdrop-blur-sm',
|
||||
'data-[state=open]:animate-in data-[state=closed]:animate-out',
|
||||
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
));
|
||||
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
|
||||
|
||||
const AlertDialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed left-[50%] top-[50%] z-50 w-full max-w-lg max-h-[90vh]',
|
||||
'translate-x-[-50%] translate-y-[-50%]',
|
||||
'bg-card border border-border rounded-2xl p-6',
|
||||
'shadow-xl',
|
||||
'data-[state=open]:animate-in data-[state=closed]:animate-out',
|
||||
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||
'data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%]',
|
||||
'data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%]',
|
||||
'duration-200',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
));
|
||||
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
|
||||
|
||||
const AlertDialogHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col space-y-2 text-center sm:text-left',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
AlertDialogHeader.displayName = 'AlertDialogHeader';
|
||||
|
||||
const AlertDialogFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-3 mt-6',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
AlertDialogFooter.displayName = 'AlertDialogFooter';
|
||||
|
||||
const AlertDialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn('text-lg font-semibold text-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
|
||||
|
||||
const AlertDialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDialogDescription.displayName =
|
||||
AlertDialogPrimitive.Description.displayName;
|
||||
|
||||
const AlertDialogAction = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Action
|
||||
ref={ref}
|
||||
className={cn(buttonVariants(), className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
|
||||
|
||||
const AlertDialogCancel = React.forwardRef<
|
||||
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
|
||||
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<AlertDialogPrimitive.Cancel
|
||||
ref={ref}
|
||||
className={cn(
|
||||
buttonVariants({ variant: 'outline' }),
|
||||
'mt-2 sm:mt-0',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
};
|
||||
export * from '@auto-claude/ui/primitives/alert-dialog';
|
||||
|
||||
@@ -1,37 +1 @@
|
||||
import * as React from 'react';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
const badgeVariants = cva(
|
||||
'inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: 'border-transparent bg-primary text-primary-foreground',
|
||||
secondary: 'border-transparent bg-secondary text-secondary-foreground',
|
||||
destructive: 'border-transparent bg-destructive text-destructive-foreground',
|
||||
outline: 'text-foreground',
|
||||
success: 'border-transparent bg-success/10 text-success',
|
||||
warning: 'border-transparent bg-warning/10 text-warning',
|
||||
info: 'border-transparent bg-info/10 text-info',
|
||||
purple: 'border-transparent bg-purple-500/10 text-purple-400',
|
||||
muted: 'border-transparent bg-muted text-muted-foreground',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return (
|
||||
<div className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
export * from '@auto-claude/ui/primitives/badge';
|
||||
|
||||
@@ -1,64 +1 @@
|
||||
import * as React from 'react';
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
import { cva, type VariantProps } from 'class-variance-authority';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
const buttonVariants = cva(
|
||||
'inline-flex items-center justify-center whitespace-nowrap font-medium transition-all duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50',
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
'bg-primary text-primary-foreground hover:bg-primary/90 active:scale-[0.98]',
|
||||
destructive:
|
||||
'bg-destructive text-destructive-foreground hover:bg-destructive/90 active:scale-[0.98]',
|
||||
outline:
|
||||
'border border-border bg-transparent hover:bg-accent hover:text-accent-foreground active:scale-[0.98]',
|
||||
secondary:
|
||||
'bg-secondary text-secondary-foreground hover:bg-secondary/80 active:scale-[0.98]',
|
||||
ghost:
|
||||
'hover:bg-accent hover:text-accent-foreground',
|
||||
link:
|
||||
'text-primary underline-offset-4 hover:underline',
|
||||
success:
|
||||
'bg-[var(--success)] text-[var(--success-foreground)] hover:bg-[var(--success)]/90 active:scale-[0.98]',
|
||||
warning:
|
||||
'bg-warning text-warning-foreground hover:bg-warning/90 active:scale-[0.98]',
|
||||
info:
|
||||
'bg-info text-info-foreground hover:bg-info/90 active:scale-[0.98]',
|
||||
},
|
||||
size: {
|
||||
default: 'h-10 px-4 py-2 text-sm rounded-lg',
|
||||
sm: 'h-8 px-3 text-xs rounded-md',
|
||||
lg: 'h-12 px-6 text-base rounded-lg',
|
||||
icon: 'h-10 w-10 rounded-lg',
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: 'default',
|
||||
size: 'default',
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : 'button';
|
||||
return (
|
||||
<Comp
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Button.displayName = 'Button';
|
||||
|
||||
export { Button, buttonVariants };
|
||||
export * from '@auto-claude/ui/primitives/button';
|
||||
|
||||
@@ -1,58 +1 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'rounded-xl border border-border bg-card text-card-foreground transition-all duration-200',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
Card.displayName = 'Card';
|
||||
|
||||
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex flex-col space-y-1.5 p-6', className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardHeader.displayName = 'CardHeader';
|
||||
|
||||
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<h3
|
||||
ref={ref}
|
||||
className={cn('text-xl font-semibold leading-none tracking-tight', className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
CardTitle.displayName = 'CardTitle';
|
||||
|
||||
const CardDescription = React.forwardRef<
|
||||
HTMLParagraphElement,
|
||||
React.HTMLAttributes<HTMLParagraphElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<p ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} />
|
||||
));
|
||||
CardDescription.displayName = 'CardDescription';
|
||||
|
||||
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardContent.displayName = 'CardContent';
|
||||
|
||||
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div ref={ref} className={cn('flex items-center p-6 pt-0', className)} {...props} />
|
||||
)
|
||||
);
|
||||
CardFooter.displayName = 'CardFooter';
|
||||
|
||||
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
|
||||
export * from '@auto-claude/ui/primitives/card';
|
||||
|
||||
@@ -1,36 +1 @@
|
||||
import * as React from 'react';
|
||||
import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
|
||||
import { Check, Minus } from 'lucide-react';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
const Checkbox = React.forwardRef<
|
||||
React.ElementRef<typeof CheckboxPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
|
||||
>(({ className, checked, ...props }, ref) => (
|
||||
<CheckboxPrimitive.Root
|
||||
ref={ref}
|
||||
checked={checked}
|
||||
className={cn(
|
||||
'peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background',
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
|
||||
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||
'data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
|
||||
'data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
className={cn('flex items-center justify-center text-current')}
|
||||
>
|
||||
{checked === 'indeterminate' ? (
|
||||
<Minus className="h-3 w-3" />
|
||||
) : (
|
||||
<Check className="h-3 w-3" />
|
||||
)}
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
));
|
||||
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
|
||||
|
||||
export { Checkbox };
|
||||
export * from '@auto-claude/ui/primitives/checkbox';
|
||||
|
||||
@@ -1,9 +1 @@
|
||||
import * as CollapsiblePrimitive from '@radix-ui/react-collapsible';
|
||||
|
||||
const Collapsible = CollapsiblePrimitive.Root;
|
||||
|
||||
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger;
|
||||
|
||||
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent;
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
|
||||
export * from '@auto-claude/ui/primitives/collapsible';
|
||||
|
||||
@@ -1,301 +1 @@
|
||||
import * as React from 'react';
|
||||
import { Check, ChevronDown, Search } from 'lucide-react';
|
||||
import { cn } from '../../lib/utils';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from './popover';
|
||||
import { ScrollArea } from './scroll-area';
|
||||
|
||||
export interface ComboboxOption {
|
||||
value: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
/** Optional group name for grouping options (e.g., "Local Branches", "Remote Branches") */
|
||||
group?: string;
|
||||
/** Optional icon to display before the label */
|
||||
icon?: React.ReactNode;
|
||||
/** Optional badge to display after the label */
|
||||
badge?: React.ReactNode;
|
||||
}
|
||||
|
||||
interface ComboboxProps {
|
||||
/** Currently selected value */
|
||||
value: string;
|
||||
/** Callback when value changes */
|
||||
onValueChange: (value: string) => void;
|
||||
/** Available options */
|
||||
options: ComboboxOption[];
|
||||
/** Placeholder text for the trigger button */
|
||||
placeholder?: string;
|
||||
/** Placeholder text for the search input */
|
||||
searchPlaceholder?: string;
|
||||
/** Message shown when no results match the search */
|
||||
emptyMessage?: string;
|
||||
/** Whether the combobox is disabled */
|
||||
disabled?: boolean;
|
||||
/** Additional class names for the trigger */
|
||||
className?: string;
|
||||
/** ID for the trigger element */
|
||||
id?: string;
|
||||
}
|
||||
|
||||
const Combobox = React.forwardRef<HTMLButtonElement, ComboboxProps>(
|
||||
(
|
||||
{
|
||||
value,
|
||||
onValueChange,
|
||||
options,
|
||||
placeholder = 'Select...',
|
||||
searchPlaceholder = 'Search...',
|
||||
emptyMessage = 'No results found',
|
||||
disabled = false,
|
||||
className,
|
||||
id,
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [search, setSearch] = React.useState('');
|
||||
const [focusedIndex, setFocusedIndex] = React.useState(-1);
|
||||
const inputRef = React.useRef<HTMLInputElement>(null);
|
||||
const optionRefs = React.useRef<Map<number, HTMLButtonElement>>(new Map());
|
||||
const listboxId = React.useId();
|
||||
|
||||
// Find the selected option's label
|
||||
const selectedOption = options.find((opt) => opt.value === value);
|
||||
const displayValue = selectedOption?.label || placeholder;
|
||||
|
||||
// Filter options based on search
|
||||
const filteredOptions = React.useMemo(() => {
|
||||
if (!search.trim()) return options;
|
||||
const searchLower = search.toLowerCase();
|
||||
return options.filter(
|
||||
(opt) =>
|
||||
opt.label.toLowerCase().includes(searchLower) ||
|
||||
opt.description?.toLowerCase().includes(searchLower)
|
||||
);
|
||||
}, [options, search]);
|
||||
|
||||
// Get option ID for aria-activedescendant
|
||||
const getOptionId = (index: number) => `${listboxId}-option-${index}`;
|
||||
|
||||
// Get the currently focused option ID
|
||||
const activeDescendant =
|
||||
focusedIndex >= 0 && focusedIndex < filteredOptions.length
|
||||
? getOptionId(focusedIndex)
|
||||
: undefined;
|
||||
|
||||
// Focus input when popover opens, reset focused index
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
// Small delay to ensure the popover is rendered
|
||||
const timer = setTimeout(() => {
|
||||
inputRef.current?.focus();
|
||||
}, 0);
|
||||
// Reset focused index when opening
|
||||
setFocusedIndex(-1);
|
||||
return () => clearTimeout(timer);
|
||||
} else {
|
||||
// Clear search when closing
|
||||
setSearch('');
|
||||
setFocusedIndex(-1);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// Reset focused index when filtered options change
|
||||
React.useEffect(() => {
|
||||
setFocusedIndex(-1);
|
||||
}, []);
|
||||
|
||||
// Scroll focused option into view
|
||||
React.useEffect(() => {
|
||||
if (focusedIndex >= 0) {
|
||||
const optionEl = optionRefs.current.get(focusedIndex);
|
||||
optionEl?.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
}, [focusedIndex]);
|
||||
|
||||
const handleSelect = (optionValue: string) => {
|
||||
onValueChange(optionValue);
|
||||
setOpen(false);
|
||||
setSearch('');
|
||||
setFocusedIndex(-1);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (!open) return;
|
||||
|
||||
switch (e.key) {
|
||||
case 'ArrowDown':
|
||||
e.preventDefault();
|
||||
setFocusedIndex((prev) =>
|
||||
prev < filteredOptions.length - 1 ? prev + 1 : 0
|
||||
);
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
e.preventDefault();
|
||||
setFocusedIndex((prev) =>
|
||||
prev > 0 ? prev - 1 : filteredOptions.length - 1
|
||||
);
|
||||
break;
|
||||
case 'Enter':
|
||||
e.preventDefault();
|
||||
if (focusedIndex >= 0 && focusedIndex < filteredOptions.length) {
|
||||
handleSelect(filteredOptions[focusedIndex].value);
|
||||
}
|
||||
break;
|
||||
case 'Escape':
|
||||
e.preventDefault();
|
||||
setOpen(false);
|
||||
break;
|
||||
case 'Home':
|
||||
e.preventDefault();
|
||||
if (filteredOptions.length > 0) {
|
||||
setFocusedIndex(0);
|
||||
}
|
||||
break;
|
||||
case 'End':
|
||||
e.preventDefault();
|
||||
if (filteredOptions.length > 0) {
|
||||
setFocusedIndex(filteredOptions.length - 1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild disabled={disabled}>
|
||||
<button
|
||||
ref={ref}
|
||||
type="button"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
aria-haspopup="listbox"
|
||||
aria-controls={open ? listboxId : undefined}
|
||||
id={id}
|
||||
className={cn(
|
||||
'flex h-10 w-full items-center justify-between rounded-lg',
|
||||
'border border-border bg-card px-3 py-2 text-sm',
|
||||
'text-foreground placeholder:text-muted-foreground',
|
||||
'focus:outline-none focus:ring-2 focus:ring-ring focus:border-primary',
|
||||
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||
'transition-colors duration-200',
|
||||
className
|
||||
)}
|
||||
>
|
||||
<span className={cn('flex items-center gap-2 truncate', !selectedOption && 'text-muted-foreground')}>
|
||||
{selectedOption?.icon && (
|
||||
<span className="shrink-0 text-muted-foreground">{selectedOption.icon}</span>
|
||||
)}
|
||||
<span className="truncate">{displayValue}</span>
|
||||
{selectedOption?.badge && (
|
||||
<span className="shrink-0">{selectedOption.badge}</span>
|
||||
)}
|
||||
</span>
|
||||
<ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
className="w-[var(--radix-popover-trigger-width)] p-0"
|
||||
align="start"
|
||||
sideOffset={4}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
{/* Search input */}
|
||||
<div className="flex items-center border-b border-border px-3">
|
||||
<Search className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
role="searchbox"
|
||||
aria-controls={listboxId}
|
||||
aria-activedescendant={activeDescendant}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder={searchPlaceholder}
|
||||
className={cn(
|
||||
'flex h-10 w-full bg-transparent py-3 px-2 text-sm',
|
||||
'placeholder:text-muted-foreground',
|
||||
'focus:outline-none',
|
||||
'disabled:cursor-not-allowed disabled:opacity-50'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Options list */}
|
||||
<ScrollArea className="max-h-[300px]">
|
||||
<div id={listboxId} role="listbox" aria-label={searchPlaceholder || placeholder} className="p-1">
|
||||
{filteredOptions.length === 0 ? (
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||
{emptyMessage}
|
||||
</div>
|
||||
) : (
|
||||
filteredOptions.map((option, index) => {
|
||||
// Check if we need to render a group header
|
||||
const prevOption = index > 0 ? filteredOptions[index - 1] : null;
|
||||
const showGroupHeader = option.group && option.group !== prevOption?.group;
|
||||
|
||||
return (
|
||||
<React.Fragment key={option.value}>
|
||||
{/* Group header */}
|
||||
{showGroupHeader && (
|
||||
<div
|
||||
role="presentation"
|
||||
className={cn(
|
||||
'px-2 py-1.5 text-xs font-semibold text-muted-foreground',
|
||||
index > 0 && 'mt-1 border-t border-border pt-2'
|
||||
)}
|
||||
>
|
||||
{option.group}
|
||||
</div>
|
||||
)}
|
||||
{/* Option item */}
|
||||
<button
|
||||
ref={(el) => {
|
||||
if (el) {
|
||||
optionRefs.current.set(index, el);
|
||||
} else {
|
||||
optionRefs.current.delete(index);
|
||||
}
|
||||
}}
|
||||
id={getOptionId(index)}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={value === option.value}
|
||||
onClick={() => handleSelect(option.value)}
|
||||
onMouseEnter={() => setFocusedIndex(index)}
|
||||
className={cn(
|
||||
'relative flex w-full cursor-default select-none items-center',
|
||||
'rounded-md py-2 pl-8 pr-2 text-sm outline-none',
|
||||
'hover:bg-accent hover:text-accent-foreground',
|
||||
'transition-colors duration-150',
|
||||
focusedIndex === index && 'bg-accent text-accent-foreground'
|
||||
)}
|
||||
>
|
||||
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
||||
{value === option.value && <Check className="h-4 w-4 text-primary" />}
|
||||
</span>
|
||||
<span className="flex flex-1 items-center gap-2 truncate">
|
||||
{option.icon && (
|
||||
<span className="shrink-0 text-muted-foreground">{option.icon}</span>
|
||||
)}
|
||||
<span className="truncate">{option.label}</span>
|
||||
{option.badge && (
|
||||
<span className="shrink-0">{option.badge}</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
</React.Fragment>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
Combobox.displayName = 'Combobox';
|
||||
|
||||
export { Combobox };
|
||||
export * from '@auto-claude/ui/primitives/combobox';
|
||||
|
||||
@@ -1,126 +1 @@
|
||||
import * as React from 'react';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { X } from 'lucide-react';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
const Dialog = DialogPrimitive.Root;
|
||||
|
||||
const DialogTrigger = DialogPrimitive.Trigger;
|
||||
|
||||
const DialogPortal = DialogPrimitive.Portal;
|
||||
|
||||
const DialogClose = DialogPrimitive.Close;
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed inset-0 z-50 bg-black/80 backdrop-blur-sm',
|
||||
'data-[state=open]:animate-in data-[state=closed]:animate-out',
|
||||
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
|
||||
|
||||
interface DialogContentProps extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
|
||||
hideCloseButton?: boolean;
|
||||
}
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
DialogContentProps
|
||||
>(({ className, children, hideCloseButton, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'fixed left-[50%] top-[50%] z-50 w-full max-w-lg max-h-[90vh]',
|
||||
'translate-x-[-50%] translate-y-[-50%]',
|
||||
'bg-card border border-border rounded-2xl p-6',
|
||||
'shadow-xl',
|
||||
'data-[state=open]:animate-in data-[state=closed]:animate-out',
|
||||
'data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
|
||||
'data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||
'data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%]',
|
||||
'data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%]',
|
||||
'duration-200 overflow-hidden flex flex-col',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{!hideCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
className={cn(
|
||||
'absolute right-4 top-4 rounded-lg p-1 z-10',
|
||||
'text-muted-foreground hover:text-foreground',
|
||||
'hover:bg-accent transition-colors',
|
||||
'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background',
|
||||
'disabled:pointer-events-none'
|
||||
)}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
));
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName;
|
||||
|
||||
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col space-y-2 text-center sm:text-left', className)} {...props} />
|
||||
);
|
||||
DialogHeader.displayName = 'DialogHeader';
|
||||
|
||||
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn('flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-3 mt-6', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
DialogFooter.displayName = 'DialogFooter';
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn('text-lg font-semibold leading-none tracking-tight text-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName;
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn('text-sm text-muted-foreground', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName;
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogClose,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
};
|
||||
export * from '@auto-claude/ui/primitives/dialog';
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user