Commit Graph

88 Commits

Author SHA1 Message Date
Fusion 63ae706dd0 feat(tool-config): add categories, interfaces, and config management
Add support for tool categories, interface types, and per-tool configuration.

Backend:
- Add category and interfaces fields to ToolType model
- Create ToolConfig model for storing tool-specific settings
- Add tool_configs API endpoints (CRUD)
- Update built-in tool types with categories and interfaces:
  - code-server: editor, [web]
  - jupyter-notebook: notebook, [web]
  - opencode: ai-assistant, [terminal]
- Update instance API to include tool type interfaces
- Create Alembic migrations 0008 and 0009

Frontend:
- Update ToolType and Session interfaces with new fields
- Conditionally show Open/Terminal buttons based on tool interfaces
- Add API client for tool configs

OpenSpec: tool-config-management change created and implemented.
2026-05-20 11:03:09 +02:00
Fusion 74b5d0dc8c feat(instance-proxy): add HTTP proxy for tool instances
Add API proxy endpoint so users can access running tool instances
through the backend API instead of internal Docker network.

Backend:
- Add container_name field to ToolInstance model
- Create /instances/{id}/proxy/{path:path} endpoint with ownership checks
- Proxy HTTP requests to containers via docker network using container names
- Support all HTTP methods (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS)
- Store proxy URL in instance.url instead of localhost
- Add Alembic migration 0007 for container_name column
- Add get_container_name() utility to docker.py

Frontend:
- Update Open button to use full proxy URL (API_BASE_URL + instance.url)

Closes instance-proxy OpenSpec change.
2026-05-20 10:37:21 +02:00
Fusion 25662e525c fix(docker): make instance directory configurable and writable
- Add INSTANCE_BASE_PATH config option (defaults to /data/instances)
- Update docker.py to use configured path instead of hardcoded 'data/instances'
- Update Dockerfile to create /data/instances and chown to appuser
- Add instance_data volume to docker-compose.traefik.yml and docker-compose.yml
- Set INSTANCE_BASE_PATH env var in both compose files

This fixes the PermissionError when creating tool instances because
appuser can now write to /data/instances.
2026-05-20 10:09:37 +02:00
Fusion d4e992a9e2 fix(cors): add API domain to CORS origins and improve instance error handling
- Add API base URL to CORS allowed origins alongside web base URL
- Add CORS origin logging on startup for debugging
- Wrap instance creation in try/except with detailed error logging
- Return proper error message instead of raw 500 for instance creation failures

This fixes CORS errors when the frontend makes cross-origin requests and
provides better diagnostics for instance creation failures.
2026-05-20 10:03:53 +02:00
Fusion 35ada0e662 fix(auth): set session cookie on redirect response
The OAuth callback was setting the session cookie on the 'response'
parameter but returning a brand new RedirectResponse, causing the
cookie to be lost. This created an infinite login loop where the
callback succeeded but /auth/me always returned 401.

- Set cookies on the RedirectResponse instead of the unused response param
- Remove unused 'response: Response' parameter from callback handler
- Fixes login loop in production with cross-domain cookies
2026-05-19 23:29:24 +02:00
Fusion c3e2264771 debug: add logging to auth /me endpoint to diagnose login loop 2026-05-19 23:25:30 +02:00
Fusion 76741d3ee6 debug: add logging to settings save to diagnose issue 2026-05-19 23:21:48 +02:00
Fusion 62752a8390 fix: add validation logging and debug info for tool instance creation
- Add RequestValidationError handler to log validation errors
- Add extra=ignore to CreateInstanceRequest to be more lenient
- Add logging to create_instance endpoint to see received data
- Add missing logger import in tool_instances.py
2026-05-19 23:17:08 +02:00
Fusion 94aa88c154 feat: add Sessions Hub page
- Add Sessions tab to navigation between Dashboard and Projects
- Show active session count badge in navigation
- Create SessionsPage with:
  - Last session section with resume button
  - Active sessions grid with open/stop actions
  - Recent sessions list
  - Create session form with project/repo/tool selectors
- Add last_session_id to user config
- Update UserConfig schemas (backend and frontend)
- Add comprehensive CSS for sessions page

Quality gates: typecheck ✓, lint ✓, build ✓
2026-05-19 23:06:54 +02:00
Fusion 4f695d7e62 fix: accept tool instance creation params in request body
The create_instance endpoint was expecting tool_type_id and display_name
as query parameters, but the frontend sends them in the JSON body.
Added CreateInstanceRequest Pydantic model to properly parse the request body.

Fixes 422 Unprocessable Content error on instance creation.
2026-05-19 22:55:47 +02:00
Fusion 7a48180dc3 fix: correct get_db_session import in tool_instances.py
Import get_db_session from src.auth.dependencies instead of src.database.
Fixes ImportError on application startup.
2026-05-19 21:39:29 +02:00
Fusion a0b0944709 fix: correct get_db_session import in terminal.py
Import get_db_session from src.auth.dependencies instead of src.database.
Fixes ImportError on application startup.
2026-05-19 21:37:00 +02:00
Fusion 40a940304b docs: comprehensive API documentation
- Create enhanced health endpoints with /health and /health/db
- Add comprehensive docstrings to all API endpoints
- Add Pydantic response models with Field descriptions
- Create apps/api/README.md with setup guide
- Create ADR-001 for session auth decision
- Create ADR-002 for async SQLAlchemy decision
- Quality gates: Python syntax OK, TypeScript OK
2026-05-19 21:31:20 +02:00
Fusion e344e961d6 feat: implement web terminal for tool instances
- Add TerminalSession backend service for docker exec subprocess management
- Add TerminalManager for WebSocket session lifecycle management
- Create WebSocket endpoint at /ws/tool-instances/{id}/terminal
- Add session cookie authentication and instance ownership verification
- Install xterm.js with fit and web-links addons
- Create TerminalComponent with xterm.js integration
- Create TerminalPage with full-screen terminal view
- Add terminal route at /instances/:id/terminal
- Add terminal button to InstanceList for running instances
- Add terminal and arrow-left icons to icon registry
- Add comprehensive terminal CSS styles (dark theme, responsive)

Quality gates: typecheck ✓, lint ✓, build ✓, Python syntax ✓
2026-05-19 21:11:29 +02:00
Fusion c795f8f873 feat: implement tool instances backend and session navigation
Backend:
- Create ToolInstance model with status tracking
- Add Alembic migration for tool_instances table
- Create Docker service for compose template rendering and container execution
- Add CRUD API endpoints for tool instances
- Add lifecycle endpoints (start/stop/restart)
- Add user sessions endpoint for navigation
- Register routers in main.py

Frontend:
- Create SessionsProvider with React context
- Create sessions API client
- Update AppShell with sessions section in navigation
- Add session status indicators and polling
- Add CSS for session navigation

Quality gates: typecheck ✓, lint ✓, build ✓
2026-05-19 20:42:59 +02:00
Fusion cccc4a9d5a fix: correct binary file detection in git file viewer
- Remove useless git diff --numstat call that failed in bare repos
- Use raw bytes instead of text decoding to avoid encoding issues
- Properly check subprocess return codes

Fixes false positive binary detection for text files like .env.sample
2026-05-19 18:55:58 +02:00
Fusion 7fc8b82621 fix: add missing GET /projects/{id} endpoint
Frontend workspace was calling GET /projects/{id} which didn't exist,
causing 405 errors and preventing WorkspaceHeader from rendering.

Add get_project endpoint that returns a single project by ID with
ownership verification.
2026-05-19 15:34:26 +02:00
Fusion 965f6f6585 feat: add git control tests and mark all tasks complete
- Add integration tests for git control utilities
- Test status, branch operations, and commit functionality
- All 9 tests passing
2026-05-19 15:10:31 +02:00
Fusion 762e0de44c feat: add git control endpoints (status, branch, commit, fetch, pull, push, merge)
- Add GitStatus dataclass and git control utilities
- Add endpoints:
  - GET /status - working directory status
  - POST /branches - create branch
  - DELETE /branches/{name} - delete branch
  - POST /checkout - checkout branch
  - POST /commit - commit changes
  - POST /fetch - fetch from remote
  - POST /pull - pull updates
  - POST /push - push changes
  - POST /merge - merge branches

Quality gates: ruff ✓, mypy ✓
2026-05-19 14:49:22 +02:00
Fusion 6807f449b7 feat: add repository workspace as default project view
- Create git file utilities (list_tree, get_file_content, list_branches, commit_file)
- Add file browsing API endpoints (list, content, branches, update)
- Create RepoWorkspace page with sidebar + main content layout
- Add FileTree component with directory navigation
- Add FileViewer component for viewing file contents
- Update project list to link to workspace
- Add workspace CSS styles
- Update router with workspace route

Quality gates: ruff ✓, mypy ✓, typecheck ✓, build ✓
2026-05-19 13:43:49 +02:00
Fusion 92d0d5b891 fix: don't combine --all with branch name in git log
Using 'git log --all <branch>' creates ambiguous behavior. Now:
- Without branch: uses --all to show all commits from all refs
- With branch: shows only commits from that specific branch

This ensures consistent commit counts between git CLI and API.
2026-05-19 13:19:36 +02:00
Fusion 9873a8186a fix: send ISO format dates instead of Unix timestamps
Backend was sending Unix timestamps as strings (e.g. '1716112800')
which JavaScript Date couldn't parse. Now sends proper ISO 8601
format dates that work with new Date() in the browser.
2026-05-19 13:10:10 +02:00
Fusion d4b52668aa fix: align backend commit response with frontend expectations
Backend was returning fields like 'author', 'email', 'date' but frontend
expected 'author_name', 'author_email', 'author_date'. Also 'branches' and
'tags' were separate but frontend expects unified 'refs' array.

- Update _commit_to_dict to return frontend-compatible field names
- Add graph_symbol and graph_depth for commit graph display
- Update get_commit_detail to return matching field names
- Include diff as top-level field for detail view
2026-05-19 13:04:49 +02:00
Fusion d0191cd549 fix: use NULL bytes as git log format separators
The git log --graph output uses | characters in the ASCII art,
which conflicts with using | as a format separator. Switch to
NULL bytes (\x00) which won't appear in commit data.

Also removed --graph flag since we build graph data from
parent relationships instead.
2026-05-19 13:00:22 +02:00
Fusion 0ae0e3fec1 feat: add git history backend implementation
- Add git_history.py utility for extracting commit history and details
- Add API endpoints for repository history and commit details
- Integrate with existing git_repositories router

This completes the backend for git history visualization.
2026-05-19 12:50:57 +02:00
Fusion 8b70daed53 feat: smart git URL parsing for browser URLs
- Add git URL parsing utilities (extract_base_repo_url, parse_git_url)
- Support GitHub, GitLab, Bitbucket browser URL detection
- Add /projects/repositories/parse-url endpoint
- Enhance repository creation to detect browser URLs and suggest corrections
- Add real-time URL validation in frontend with debouncing
- Show visual indicators (green/yellow/red) for URL validity
- Display inline suggestions with 'Use Suggested' button
- Add comprehensive unit tests for URL parsing
- Quality gates: ruff ✓, mypy ✓, typecheck ✓, lint ✓, build ✓
2026-05-19 12:25:44 +02:00
Fusion ac6c97b6ce fix: add missing timestamps to ssh_keys model
SSHKey model was missing created_at/updated_at columns which the API
response model expected. Add TimestampMixin and Alembic migration.
2026-05-19 11:51:39 +02:00
Fusion a433c82488 fix: datetime serialization in API response models
Tool types and git repositories response models declared created_at/
updated_at as str but ORM returns datetime objects. Change to datetime
type so Pydantic serializes correctly to ISO format strings.
2026-05-19 11:42:14 +02:00
Fusion f8700fd7ed fix: dashboard endpoint and SSH key Fernet key generation
- Create missing /dashboard/summary endpoint that frontend expects
- Fix SSH key Fernet key generation to use proper base64 encoding
  (was using raw session secret slice which failed validation)
2026-05-19 11:38:25 +02:00
Fusion 0fcfc745ff fix: add alias=session to Cookie dependencies
FastAPI uses parameter name as cookie name by default.
get_current_user_id was looking for 'session_cookie' but we set
the cookie as 'session'. Add alias='session' to match.
2026-05-19 10:56:11 +02:00
Fusion d214ab82db debug: add logging to auth cookie handling
Add debug logging to understand why /auth/me succeeds but
/users/me/config fails with 401.
2026-05-19 10:52:33 +02:00
Fusion 753f1506b6 fix: wrap /auth/me response in user object to match frontend types
Frontend expects {user: {id, email, name, avatar_url}} but backend
was returning flat object. This caused auth state to fail parsing.
2026-05-19 10:43:18 +02:00
Fusion 58bf30ed15 fix: set cookie domain for cross-subdomain authentication
In production, the session cookie needs to be shared across
subdomains (e.g., api.example.com and app.example.com).

- Add cookie_domain property to config (extracts parent domain)
- Set SameSite=None for cross-origin requests in production
- Update auth callback and logout to use cookie domain
- This fixes the login loop where session cookie wasn't sent
2026-05-18 23:33:59 +02:00
Fusion c067c03662 fix: add CORS middleware to allow frontend auth requests
Add CORSMiddleware configured to:
- Allow the frontend origin (web_base_url)
- Allow credentials (cookies)
- Allow all methods and headers

This fixes cross-origin requests between frontend and API
when they're on different subdomains.
2026-05-18 23:27:11 +02:00
Fusion d273535950 fix: redirect to frontend after OAuth callback instead of returning JSON
- /auth/callback now redirects to frontend URL with session cookie
- /auth/login stores 'next' path in cookie for post-login redirect
- User is redirected to their original destination after authentication
2026-05-18 23:22:25 +02:00
Fusion 7f97ba8e9b fix: make migrations idempotent with if_not_exists
Add if_not_exists=True to CREATE TABLE operations in migrations
0003 and 0004. This prevents DuplicateTableError when migrations
are re-run on databases where tables were partially created.
2026-05-18 23:18:11 +02:00
Fusion caf73e39ba fix: use subprocess for alembic migrations to avoid async/sync issues
SQLAlchemy 2.0 async engines conflict with alembic's sync context manager.
Instead of trying to bridge async/sync, use subprocess to run
'alembic upgrade head' directly. This is simpler and more reliable.

- Remove psycopg2-binary dependency (no longer needed)
- Simplify init_database to use subprocess.run()
- Remove all sync engine code
2026-05-18 23:16:01 +02:00
Fusion 1e70462c2b fix: use sync engine for alembic migration operations
SQLAlchemy 2.0 async engines don't support the sync context manager
protocol needed by alembic. Create a separate sync engine (using
psycopg2) for migration operations while keeping async engine for
application queries.

- Add psycopg2-binary dependency
- Rename async connection variable to avoid mypy confusion
- Use sync engine for MigrationContext and alembic commands
2026-05-18 23:09:44 +02:00
Fusion b9684b0107 fix: fail fast on startup if database migrations fail
- Exit with error code 1 if init_database() returns False
- Update health check to verify database connectivity
- Prevents confusing 'table does not exist' errors later
2026-05-18 23:05:30 +02:00
Fusion 2ce7862058 feat: simplify auth flow - replace JWT with session cookies
Replace complex JWT + refresh token authentication with simple
session-based auth using signed cookies.

**Removed:**
- JWT token service (jwt_service.py)
- Refresh token store (refresh_store.py)
- Refresh token model and database table
- JWKS fetching and OIDC token verification
- python-jose dependency

**Added:**
- Session service (session.py) with HMAC-SHA256 signed cookies
- Auth dependencies module for shared auth logic
- Session-based auth endpoints

**Updated:**
- All API endpoints to use session-based auth
- Config: removed JWT settings, added SESSION_SECRET/SESSION_TTL_HOURS
- Tests: rewritten for session-based flow
- Frontend: no changes needed (already uses cookies)

Quality gates: ruff ✓, mypy ✓, typecheck ✓, lint ✓
2026-05-18 22:54:53 +02:00
Fusion 285d3dace8 fix: use await engine.connect() instead of async with
SQLAlchemy 2.0 async engine.connect() doesn't support context manager.
Use explicit connect/close instead.
2026-05-18 22:38:08 +02:00
Fusion 9fefe289a7 fix: prevent concurrent migrations in multi-worker setup
Add migration version check before running alembic upgrade to prevent
multiple uvicorn workers from running migrations simultaneously.

- Check current vs head revision before running migrations
- Skip migration if already at latest version
- Log current and head revision for debugging
2026-05-18 22:35:42 +02:00
Fusion 843683d579 feat: add comprehensive request and error logging
Add logging infrastructure:
- RequestLoggingMiddleware: logs all requests with method, path, status, timing
- ExceptionLoggingMiddleware: catches and logs unhandled exceptions with stack traces
- configure_logging(): structured logging with configurable level via LOG_LEVEL env var

Add detailed auth flow logging:
- Login initiation
- Token exchange success/failure
- JWKS fetch success/failure
- Token verification
- User lookup/creation
- Database errors
- Final response

This enables tracing Internal Server Errors through the logs.
2026-05-18 22:22:56 +02:00
Fusion ea6c466c6c feat: add automatic database initialization and recovery
- Add init_database() with alembic programmatic API and retry logic
- Add connection retry with exponential backoff (5 attempts)
- Improve error messages for connection/auth failures
- Add table existence check before seeding data
- Update startup event to run migrations before seeding
- Add wait-for-db.sh script for Docker containers
- Update Docker and docker-compose configurations

Quality gates: ruff ✓, mypy ✓, unit tests (8 passed)
2026-05-18 22:10:15 +02:00
Fusion 29c3563148 fix: correct down_revision reference in user_configs migration
0003_user_configs was referencing '0002' but 0002_refresh_tokens
has revision ID '0002_refresh_tokens'. Fix the chain.
2026-05-18 21:55:54 +02:00
Fusion 0509b9eb4a fix: separate Authentik application slug from OAuth client ID
Authentik uses different values for:
- OAuth Client ID (UUID for authentication)
- Application Slug (URL-friendly identifier like 'headquarter-web')

Add AUTHENTIK_APPLICATION_SLUG config to build correct Authentik URLs
while keeping AUTHENTIK_CLIENT_ID for OAuth token exchange.
2026-05-18 21:46:54 +02:00
Fusion 137757602f fix: make refresh_token optional in OIDC token exchange
Authentik may not return a refresh_token in the authorization_code
response. Use .get() instead of direct dict access to prevent KeyError.
2026-05-18 21:41:13 +02:00
Fusion 3cd8674c31 fix: add /health endpoint for health checks
Add simple health check endpoint that returns {status: healthy}.
Needed for Traefik health checks and monitoring.
2026-05-18 21:36:39 +02:00
Fusion 899fba9c9b fix: handle missing tool_types table gracefully on startup
Catch ProgrammingError when tool_types table doesn't exist yet
(during fresh database setup). Log warning and skip seeding instead
of crashing.
2026-05-18 21:29:48 +02:00
Fusion 6dbd55a9ac fix: correct uvicorn module path in Dockerfile
main.py is located at src/main.py, not at the root.
Changed CMD from 'main:app' to 'src.main:app' to fix ASGI import error.
2026-05-18 17:53:40 +02:00