Skip to main content

Architecture

System Overview

For a detailed explanation of how Claude / Codex / ZCode / Qwen local token usage is collected, computed, stored, and consumed across the stack, see TOKEN_ACCOUNTING.md.

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 │
│ 39 Blueprints │ 41 Services │ 26 Repositories │ 6 Modules│
│ Background Schedulers │ Middleware │ Auth │
└──────────┬───────────────────┬───────────────────────────┘
│ │
┌──────────┴──────┐ ┌────────┴────────────────────────────┐
│ SQLite/PostgreSQL│ │ Remote Agent (daemon) │
│ 103 tables │ │ HTTP polling │ CLI subprocesses │
│ Alembic │ │ WS terminal │ Session sync │
└─────────────────┘ │ Claude/Qwen/Codex/ZCode/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/ policy/ 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 39 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
ai_agent_settings_bp/apiAI agent settings management
alerts_bp/apiAlert management, WebSocket push
analysis_bp/apiUsage analysis, trends, anomalies
analytics_bp/apiEnterprise analytics, CSV export
api_keys_bp/apiAPI key management and scoping
autonomous_bp/api/autonomousAutonomous development workflows, CI repair, acceptance
auth_bp/apiLogin, register, logout, sessions, avatars
encryption_keys_bp/apiEncryption key management
feature_flags_bp/apiFeature flag management
feishu_config_bp/apiFeishu integration configuration
frontend_errors_bp/apiFrontend error reporting
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
mapping_rules_bp/apiTenant isolation mapping rules
model_gateway_bp/apiModel gateway configuration (LiteLLM-compatible)
messages_bp/apiMessage data, pagination, export
notification_integrations_bp/apiNotification and collaboration settings
pages_bp/React SPA catch-all
policy_bp/apiPolicy rules engine
project_categories_bp/apiProject category management
projects_bp/apiProject CRUD, stats, file scanning
quota_bp/apiQuota checking, enforcement
run_timeline_bp/apiAutonomous session run timeline events
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/SAML
smtp_config_bp/apiSMTP configuration management
system_bp/apiScheduler status and system info
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
workspace_isolation_bp/api/workspaceWorkspace isolation capability contract

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, and SAML 2.0 SP metadata/AuthnRequest/ACS handling

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 loopback WebUI origins plus explicit allowlist entries
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.