Skip to main content

Architecture

System Overview

Open ACE (AI Computing Explorer) is an enterprise AI workspace platform with three layers:

┌─────────────────────────────────────────────────────────┐
│ Browser (React SPA) │
│ Work Mode (all users) Manage Mode (admin only) │
│ ┌────────┬──────────┐ ┌──────────────────────┐ │
│ │Session │Workspace │ │ Dashboard / Admin │ │
│ │ List │(iframe) │ │ Pages (20+) │ │
│ │ │Terminal │ │ │ │
│ └────────┴──────────┘ └──────────────────────┘ │
└──────────────────────┬──────────────────────────────────┘
│ HTTP / WebSocket
┌──────────────────────┴──────────────────────────────────┐
│ Flask API Server │
│ 23 Blueprints │ 14 Services │ 11 Repositories │ 31 Mods │
│ Background Schedulers │ Middleware │ Auth │
└──────────┬───────────────────┬───────────────────────────┘
│ │
┌──────────┴──────┐ ┌────────┴────────────────────────────┐
│ SQLite/PostgreSQL│ │ Remote Agent (daemon) │
│ 35+ tables │ │ HTTP polling │ CLI subprocesses │
│ Alembic │ │ WebSocket PTY │ Session sync │
└─────────────────┘ │ Claude/Qwen/Codex/OpenClaw │
└─────────────────────────────────────┘

Backend Architecture

Layered Architecture

Routes (Flask Blueprints)
→ Services (business logic, schedulers)
→ Repositories (data access)
→ Database abstraction (SQLite or PostgreSQL)

Modules (domain logic):
analytics/ compliance/ governance/ sso/ workspace/

Application Entry Point

app/__init__.pycreate_app() factory:

  1. Creates Flask app
  2. Applies ProxyFix middleware for nginx
  3. Configures SECRET_KEY
  4. Registers error handlers (JSON for API, standard for pages)
  5. Registers 23 Flask Blueprints
  6. Runs ensure_all_tables() for DDL schema initialization
  7. Starts background schedulers

Blueprint Routes

BlueprintPrefixDescription
admin_bp/apiUser CRUD, system account creation
alerts_bp/apiAlert management, WebSocket push
analysis_bp/apiUsage analysis, trends, anomalies
analytics_bp/apiEnterprise analytics, CSV export
auth_bp/apiLogin, register, logout, sessions, avatars
compliance_bp/api/complianceCompliance reports, data retention
fetch_bp/apiData collection scripts, fetch status
fs_bp/apiFile system browsing
governance_bp/apiAudit logs, quotas, content filtering
insights_bp/apiAI conversation insights
messages_bp/apiMessage data, pagination, export
pages_bp/React SPA catch-all
projects_bp/apiProject CRUD, stats, file scanning
quota_bp/apiQuota checking, enforcement
remote_bp/api/remoteRemote machines, sessions, LLM proxy
report_bp/apiUsage reports
roi_bp/apiROI analysis, cost optimization
sso_bp/api/ssoSSO provider management, OAuth2/OIDC
tenant_bp/api/tenantsMulti-tenant management
tool_accounts_bp/apiUser-tool-account mapping
upload_bp/apiExternal data ingestion
usage_bp/apiUsage data, CSV export
workspace_bp/api/workspaceSessions, prompts, tool connections

Services

ServiceDescription
AnalysisServiceBatch analysis, metrics, anomaly detection (ThreadPoolExecutor 4)
AuthServiceAuthentication, session management, rate limiting
DataFetchSchedulerBackground scheduler, runs fetch scripts every 5 min
InsightsServiceAI insights via GLM-5 model
MessageServiceMessage query, filter, pagination
PermissionServiceRBAC, role-permission mapping, custom permissions
QuotaEnforcementSchedulerQuota checking every 60s, session termination
SummaryServicePre-aggregated usage summary
TenantServiceMulti-tenant CRUD, plan-based quotas
UsageServiceUsage data, per-tool stats
UserDailyStatsAggregatorAggregates daily_messages to user_daily_stats
WebUIManagerPer-user qwen-code-webui processes (ports 3100-3200)
WorkspaceServiceCoordinates collaboration, prompts, sessions

Repositories

RepositoryDescription
DailyStatsRepositoryPre-aggregated daily statistics
GovernanceRepositoryContent filter rules, security settings
InsightsReportRepositoryInsights report CRUD
MessageRepositoryMessage data access against daily_messages
ProjectRepositoryProject CRUD, stats
TenantRepositoryTenant CRUD, settings, users
UsageRepositoryDaily usage, per-tool stats, CSV export
UserRepositoryUser CRUD, auth lookups
UserToolAccountRepositoryUser-tool-account mapping

Module Packages

app/modules/analytics/ — Usage analytics, ROI calculation, cost optimization

app/modules/compliance/ — Audit analysis, compliance reports (SOX/GDPR/HIPAA), data retention

app/modules/governance/ — Audit logging, alert notifications, quota management, content filtering (PII detection)

app/modules/sso/ — SSO provider lifecycle, OAuth2 authorization code flow, OIDC with ID token verification

app/modules/workspace/ — API key proxy (encrypted storage), collaboration, prompt library, remote agent/session managers, session persistence, state sync, terminal store, tool connector, WebSocket proxy

Data Models

ModelDescription
User + UserRole + PermissionUser management with role-based access
MessageMessage tracking with tokens and metadata
SessionAuthentication session
Tenant + TenantSettings + TenantUsageMulti-tenant with plan-based quotas
UsageUsage tracking per date/tool
Project + ProjectStatsProject management and statistics
UserToolAccountMaps users to AI tool sender names

Database

Dual-Database Support

The Database abstraction layer in app/repositories/database.py transparently supports both SQLite (single-machine) and PostgreSQL (production):

  • adapt_sql(query) — Converts ? placeholders to %s for PostgreSQL
  • is_postgresql() — Detects active database type from DATABASE_URL
  • Connection poolingpsycopg2.pool.ThreadedConnectionPool (min=1, max=10)
  • Database class — DI-friendly wrapper with execute(), fetch_one(), fetch_all(), table_exists()
  • Default SQLite path: ~/.open-ace/ace.db

See DATABASE-SCHEMA.md for the full table reference.

Middleware

MiddlewarePurpose
ProxyFixTrusts X-Forwarded-For / X-Forwarded-Proto from nginx
CORS headersafter_request handler for /api/ routes from localhost
OPTIONS handlerPreflight CORS responses
Error handlersJSON for API routes, standard HTTP for pages
/healthReturns service status and git commit hash

Background Services

SchedulerIntervalDescription
DataFetchScheduler5 min (min 60s)Runs fetch scripts, refreshes materialized views, aggregates stats, checks quotas
QuotaEnforcementScheduler60s (min 30s)Checks user quotas, terminates exceeded sessions, generates alerts

Both are singleton daemon threads started in create_app(), wrapped in try/except to prevent startup failure.

Frontend Architecture

Tech Stack

  • React 18 + TypeScript + Vite 6
  • TanStack React Query v5 — data fetching with 1-min stale time
  • Zustand v5 — state management with localStorage persistence
  • Bootstrap 5 + Headless UI — styling and accessible components
  • Chart.js + react-chartjs-2 — data visualization
  • xterm.js — terminal emulation
  • react-router-dom v7 — dual-track routing

Dual-Track Routing

Work Mode (/work/*) — all users:

  • 3-panel layout: session list + workspace (iframe) + assist panel
  • Routes: sessions, prompts, usage, insights, workspace

Manage Mode (/manage/*) — admin only:

  • Sidebar navigation layout with 20+ admin pages
  • Routes: dashboard, analysis, messages, audit, quota, compliance, security, users, tenants, projects, remote machines, SSO settings

See FRONTEND-GUIDE.md for the complete frontend reference.

Remote Agent Architecture

┌──────────┐ HTTP Polling ┌──────────────┐
│ Agent │ ◄──────────────► │ Flask API │
│ (daemon) │ 1s interval │ │
└────┬─────┘ └──────────────┘
│ subprocess

┌──────────────────────────────────────────────┐
│ CLI Adapters │
│ Claude Code │ Qwen Code │ Codex │ OpenClaw │
└──────────────────────────────────────────────┘
│ WebSocket

┌──────────────────────────────────────────────┐
│ Terminal Server (PTY) │
│ 64KB output buffer │ HMAC auth │ reconnect │
└──────────────────────────────────────────────┘

The remote agent runs as a Python daemon on remote machines, providing:

  • HTTP polling — registers machine, polls for commands every 1s, heartbeats every 60s
  • CLI subprocess management — spawns Claude Code, Qwen Code, Codex, or OpenClaw
  • WebSocket terminal — browser connects to PTY via terminal server
  • Session sync — scans ~/.claude/, ~/.qwen/, ~/.codex/ for session history, syncs to server every 30s

See REMOTE-AGENT.md for the client-side guide and REMOTE-WORKSPACE.md for the server-side guide.

Authentication

Three auth decorators in app/auth/decorators.py:

DecoratorPurpose
@auth_requiredValid session token required; optional ownership='session' or 'machine'
@admin_requiredAdmin role required
@public_endpointMarks intentionally public endpoints

Token extraction order: session_token cookie → Authorization: Bearer header → token query param.

See PERMISSION-MODEL.md for the full permission model.