Skip to content

🙌 OpenHands: AI-Driven Development

feat(org): Add organization conversation admin dashboard (#14846)

Saurya Velagapudi25ab318cbb27
diff --git a/enterprise/scripts/seed_conversation_data.py b/enterprise/scripts/seed_conversation_data.py
new file mode 100644
index 0000000000..917d04d393
--- /dev/null
+++ b/enterprise/scripts/seed_conversation_data.py
@@ -0,0 +1,480 @@
+#!/usr/bin/env python3
+"""
+Seed script to populate the database with realistic conversation data for testing.
+
+Usage:
+ # With default settings (assumes local PostgreSQL)
+ python -m enterprise.scripts.seed_conversation_data
+
+ # With custom database URL
+ DATABASE_URL=postgresql://user:pass@host:5432/db python -m enterprise.scripts.seed_conversation_data
+
+ # With options
+ python -m enterprise.scripts.seed_conversation_data --org-count 3 --conversations-per-org 50
+"""
+
+import argparse
+import random
+import uuid
+from datetime import UTC, datetime, timedelta
+
+from sqlalchemy import create_engine, text
+from sqlalchemy.orm import Session, sessionmaker
+
+# Configuration
+DEFAULT_DB_URL = 'postgresql://postgres:postgres@localhost:5432/openhands'
+
+
+# Sample data
+FIRST_NAMES = [
+ 'Sarah',
+ 'Michael',
+ 'Emma',
+ 'James',
+ 'Olivia',
+ 'William',
+ 'Sophia',
+ 'Benjamin',
+ 'Isabella',
+ 'Lucas',
+ 'Mia',
+ 'Henry',
+ 'Charlotte',
+ 'Alexander',
+ 'Amelia',
+ 'Daniel',
+ 'Harper',
+ 'Matthew',
+ 'Evelyn',
+ 'Sebastian',
+ 'Aria',
+ 'Jack',
+ 'Luna',
+ 'Owen',
+]
+
+LAST_NAMES = [
+ 'Chen',
+ 'Williams',
+ 'Rodriguez',
+ 'Kim',
+ 'Patel',
+ 'Johnson',
+ 'Martinez',
+ 'Anderson',
+ 'Thompson',
+ 'Garcia',
+ 'Lee',
+ 'Wilson',
+ 'Taylor',
+ 'Brown',
+ 'Davis',
+ 'Miller',
+ 'Moore',
+ 'Jackson',
+ 'Martin',
+ 'Thompson',
+ 'White',
+ 'Harris',
+ 'Clark',
+ 'Lewis',
+]
+
+DOMAINS = ['techcorp.io', 'acme.com', 'startupxyz.com', 'enterprise.net', 'devco.org']
+
+LLM_MODELS = [
+ 'claude-sonnet-4-5',
+ 'claude-opus-4',
+ 'gpt-4o',
+ 'gpt-4-turbo',
+ 'gemini-1.5-pro',
+ 'claude-3-5-sonnet',
+ 'gpt-4o-mini',
+ 'claude-3-opus',
+]
+
+AGENT_KINDS = [
+ 'CodeAgent',
+ 'AnalysisAgent',
+ 'DebugAgent',
+ 'ReviewAgent',
+ 'DocumentAgent',
+ 'TestAgent',
+ 'RefactorAgent',
+]
+
+REPO_NAMES = [
+ 'frontend-app',
+ 'backend-api',
+ 'mobile-app',
+ 'data-pipeline',
+ 'ml-service',
+ 'auth-service',
+ 'payment-gateway',
+ 'notification-system',
+ 'analytics-dashboard',
+ 'admin-portal',
+ 'e-commerce-platform',
+ 'inventory-management',
+]
+
+BRANCHES = [
+ 'main',
+ 'develop',
+ 'feature/user-auth',
+ 'bugfix/login-issue',
+ 'release/v2.1',
+]
+
+TRIGGERS = ['manual', 'scheduled', 'webhook', 'api', 'cli']
+
+CONVERSATION_TITLES = [
+ 'Fix authentication flow',
+ 'Implement new dashboard features',
+ 'Code review for PR #234',
+ 'Debug memory leak in service',
+ 'Add unit tests for auth module',
+ 'Refactor database queries',
+ 'Setup CI/CD pipeline',
+ 'Performance optimization',
+ 'Security audit fixes',
+ 'Update API documentation',
+ 'Migrate to new framework',
+ 'Add dark mode support',
+ 'Implement search functionality',
+ 'Fix responsive layout',
+ 'Add user analytics',
+ 'Optimize image loading',
+ 'Create API endpoints',
+ 'Write integration tests',
+ 'Fix CSS bugs',
+ 'Deploy to staging',
+]
+
+EXECUTIONS_STATUSES = ['running', 'idle', 'paused', 'finished', 'error', 'stuck']
+SANDBOX_STATUSES = ['RUNNING', 'STARTING', 'PAUSED', 'ERROR', 'MISSING']
+
+
+def random_email(first_name: str, last_name: str) -> str:
+ """Generate a random email address."""
+ domain = random.choice(DOMAINS)
+ return f'{first_name.lower()}.{last_name.lower()}@{domain}'
+
+
+def random_datetime(days_back: int = 90) -> datetime:
+ """Generate a random datetime within the last N days."""
+ now = datetime.now(UTC)
+ random_days = random.uniform(0, days_back)
+ return now - timedelta(days=random_days)
+
+
+def generate_conversation_data(
+ conversation_id: str,
+ org_id: str,
+ user_id: str,
+ created_at: datetime,
+) -> dict:
+ """Generate realistic conversation metadata."""
+ updated_at = created_at + timedelta(
+ minutes=random.randint(5, 480), hours=random.randint(0, 72)
+ )
+
+ # Ensure updated_at is in the past
+ if updated_at > datetime.now(UTC):
+ updated_at = datetime.now(UTC) - timedelta(hours=random.randint(1, 24))
+
+ execution_status = random.choice(EXECUTIONS_STATUSES)
+ sandbox_status = random.choice(SANDBOX_STATUSES)
+
+ # Running conversations should have RUNNING sandbox
+ if execution_status == 'running':
+ sandbox_status = 'RUNNING'
+
+ # Completed conversations typically have finished status
+ if random.random() < 0.7 and execution_status in ['finished', 'error', 'stuck']:
+ sandbox_status = 'MISSING'
+
+ prompt_tokens = random.randint(1000, 50000)
+ completion_tokens = random.randint(500, 25000)
+ cache_read_tokens = random.randint(0, 10000)
+ cache_write_tokens = random.randint(0, 5000)
+
+ # Rough cost estimation (varies by model)
+ cost_per_1k_prompt = random.uniform(0.001, 0.015)
+ cost_per_1k_completion = random.uniform(0.003, 0.075)
+ accumulated_cost = (prompt_tokens / 1000) * cost_per_1k_prompt + (
+ completion_tokens / 1000
+ ) * cost_per_1k_completion
+
+ return {
+ 'conversation_id': conversation_id,
+ 'conversation_version': 'V1',
+ 'title': random.choice(CONVERSATION_TITLES),
+ 'llm_model': random.choice(LLM_MODELS),
+ 'agent_kind': random.choice(AGENT_KINDS),
+ 'user_id': user_id,
+ 'created_at': created_at,
+ 'last_updated_at': updated_at,
+ 'sandbox_id': f'sb-{uuid.uuid4().hex[:12]}',
+ 'sandbox_status': sandbox_status,
+ 'runtime_url': f'https://runtime-{uuid.uuid4().hex[:8]}.example.com'
+ if sandbox_status == 'RUNNING'
+ else None,
+ 'execution_status': execution_status,
+ 'selected_repository': random.choice(REPO_NAMES),
+ 'selected_branch': random.choice(BRANCHES),
+ 'trigger': random.choice(TRIGGERS),
+ 'accumulated_cost': round(accumulated_cost, 4),
+ 'prompt_tokens': prompt_tokens,
+ 'completion_tokens': completion_tokens,
+ 'total_tokens': prompt_tokens + completion_tokens,
+ 'cache_read_tokens': cache_read_tokens,
+ 'cache_write_tokens': cache_write_tokens,
+ 'org_id': org_id,
+ }
+
+
+def create_tables_if_not_exist(engine) -> None:
+ """Create the required tables if they don't exist."""
+ with engine.connect() as conn:
+ # Check if tables exist
+ result = conn.execute(
+ text("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_schema = 'public'
+ AND table_name = 'conversation_metadata'
+ );
+ """)
+ )
+ tables_exist = result.scalar()
+
+ if not tables_exist:
+ print("Tables don't exist. Running migrations...")
+ # Run migrations - this assumes alembic is available
+ import subprocess
+
+ result = subprocess.run(
+ ['python', '-m', 'alembic', 'upgrade', 'head'],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ print(f'Migration failed: {result.stderr}')
+ raise Exception('Failed to run migrations')
+ print('Migrations complete.')
+ else:
+ print('Tables already exist.')
+
+
+def seed_data(
+ db_url: str,
+ org_count: int = 3,
+ conversations_per_org: int = 30,
+ users_per_org: int = 10,
+) -> None:
+ """Seed the database with conversation data.
+
+ Uses the correct OpenHands schema: org, user, org_member tables.
+ """
+
+ engine = create_engine(db_url)
+ create_tables_if_not_exist(engine)
+
+ SessionLocal = sessionmaker(bind=engine)
+ session: Session = SessionLocal()
+
+ try:
+ with session.begin():
+ # Create orgs
+ org_ids = []
+ print(f'Creating {org_count} orgs...')
+ for i in range(org_count):
+ org_id = str(uuid.uuid4())
+ org_ids.append(org_id)
+
+ session.execute(
+ text("""
+ INSERT INTO org (id, name, created_at, updated_at, is_github_org, org_type)
+ VALUES (:id, :name, :created_at, :updated_at, false, 'team')
+ ON CONFLICT (id) DO NOTHING
+ """),
+ {
+ 'id': org_id,
+ 'name': f'Test Org {i + 1}',
+ 'created_at': datetime.now(UTC),
+ 'updated_at': datetime.now(UTC),
+ },
+ )
+
+ print(f'Created {len(org_ids)} orgs')
+
+ # Create users and conversations for each org
+ total_conversations = 0
+
+ for org_id in org_ids:
+ print(f'Creating users and conversations for org {org_id}...')
+
+ user_ids = []
+ for j in range(users_per_org):
+ user_id = str(uuid.uuid4())
+ user_ids.append(user_id)
+ first_name = random.choice(FIRST_NAMES)
+ last_name = random.choice(LAST_NAMES)
+ email = random_email(first_name, last_name)
+
+ # First user is the owner, next 2 are admins, rest are members
+ role_id = (
+ 1 if j == 0 else (2 if j < 3 else 3)
+ ) # owner, admin, member
+
+ session.execute(
+ text("""
+ INSERT INTO "user" (id, current_org_id, role_id, email, created_at, updated_at)
+ VALUES (:id, :current_org_id, :role_id, :email, :created_at, :updated_at)
+ ON CONFLICT (id) DO NOTHING
+ """),
+ {
+ 'id': user_id,
+ 'current_org_id': org_id,
+ 'role_id': role_id,
+ 'email': email,
+ 'created_at': datetime.now(UTC),
+ 'updated_at': datetime.now(UTC),
+ },
+ )
+
+ # Add user to org_member
+ session.execute(
+ text("""
+ INSERT INTO org_member (org_id, user_id, role_id, _llm_api_key, status, agent_settings_diff, conversation_settings_diff, has_custom_llm_api_key, created_at, updated_at)
+ VALUES (:org_id, :user_id, :role_id, '', 'active', '{}', '{}', false, :created_at, :updated_at)
+ ON CONFLICT (org_id, user_id) DO NOTHING
+ """),
+ {
+ 'org_id': org_id,
+ 'user_id': user_id,
+ 'role_id': role_id,
+ 'created_at': datetime.now(UTC),
+ 'updated_at': datetime.now(UTC),
+ },
+ )
+
+ print(f' Created {len(user_ids)} users')
+
+ # Create conversations for this org
+ for k in range(conversations_per_org):
+ conversation_id = str(uuid.uuid4())
+ user_id = random.choice(user_ids)
+ created_at = random_datetime(days_back=90)
+
+ conv_data = generate_conversation_data(
+ conversation_id=conversation_id,
+ org_id=org_id,
+ user_id=user_id,
+ created_at=created_at,
+ )
+
+ # Insert into conversation_metadata
+ session.execute(
+ text("""
+ INSERT INTO conversation_metadata (
+ conversation_id, conversation_version, title, llm_model,
+ agent_kind, user_id, created_at, last_updated_at,
+ sandbox_id, sandbox_status, runtime_url, execution_status,
+ selected_repository, selected_branch, trigger,
+ accumulated_cost, prompt_tokens, completion_tokens,
+ total_tokens, cache_read_tokens, cache_write_tokens
+ ) VALUES (
+ :conversation_id, :conversation_version, :title, :llm_model,
+ :agent_kind, :user_id, :created_at, :last_updated_at,
+ :sandbox_id, :sandbox_status, :runtime_url, :execution_status,
+ :selected_repository, :selected_branch, :trigger,
+ :accumulated_cost, :prompt_tokens, :completion_tokens,
+ :total_tokens, :cache_read_tokens, :cache_write_tokens
+ )
+ ON CONFLICT (conversation_id) DO NOTHING
+ """),
+ conv_data,
+ )
+
+ # Insert into conversation_metadata_saas
+ session.execute(
+ text("""
+ INSERT INTO conversation_metadata_saas (conversation_id, org_id)
+ VALUES (:conversation_id, :org_id)
+ ON CONFLICT (conversation_id) DO NOTHING
+ """),
+ {
+ 'conversation_id': conversation_id,
+ 'org_id': org_id,
+ },
+ )
+
+ total_conversations += conversations_per_org
+ print(f' Created {conversations_per_org} conversations')
+
+ print('\n✅ Seed complete!')
+ print(f' Organizations: {org_count}')
+ print(f' Total users: {org_count * users_per_org}')
+ print(f' Total conversations: {total_conversations}')
+ print(f'\nDatabase: {db_url}')
+
+ except Exception as e:
+ session.rollback()
+ print(f'❌ Error seeding data: {e}')
+ raise
+ finally:
+ session.close()
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description='Seed database with realistic conversation data for testing.'
+ )
+ parser.add_argument(
+ '--db-url',
+ type=str,
+ default=None,
+ help=f'Database URL (default: DATABASE_URL env var or {DEFAULT_DB_URL})',
+ )
+ parser.add_argument(
+ '--org-count',
+ type=int,
+ default=3,
+ help='Number of organizations to create (default: 3)',
+ )
+ parser.add_argument(
+ '--conversations-per-org',
+ type=int,
+ default=30,
+ help='Number of conversations per organization (default: 30)',
+ )
+ parser.add_argument(
+ '--users-per-org',
+ type=int,
+ default=10,
+ help='Number of users per organization (default: 10)',
+ )
+
+ args = parser.parse_args()
+
+ db_url = args.db_url or DEFAULT_DB_URL
+ if not db_url:
+ print(
+ 'Error: No database URL provided. Set DATABASE_URL env var or use --db-url'
+ )
+ return 1
+
+ seed_data(
+ db_url=db_url,
+ org_count=args.org_count,
+ conversations_per_org=args.conversations_per_org,
+ users_per_org=args.users_per_org,
+ )
+
+ return 0
+
+
+if __name__ == '__main__':
+ exit(main())
diff --git a/enterprise/scripts/setup_and_seed.py b/enterprise/scripts/setup_and_seed.py
new file mode 100644
index 0000000000..64b343f90b
--- /dev/null
+++ b/enterprise/scripts/setup_and_seed.py
@@ -0,0 +1,626 @@
+#!/usr/bin/env python3
+"""
+Standalone script to create tables and seed conversation data.
+This bypasses the full enterprise migration system for simpler local testing.
+
+Usage:
+ python enterprise/scripts/setup_and_seed.py
+"""
+
+import argparse
+import random
+import uuid
+from datetime import UTC, datetime, timedelta
+
+from sqlalchemy import create_engine, text
+from sqlalchemy.orm import sessionmaker
+
+DEFAULT_DB_URL = 'postgresql://postgres:postgres@localhost:5432/openhands'
+
+
+# Sample data
+FIRST_NAMES = [
+ 'Sarah',
+ 'Michael',
+ 'Emma',
+ 'James',
+ 'Olivia',
+ 'William',
+ 'Sophia',
+ 'Benjamin',
+ 'Isabella',
+ 'Lucas',
+ 'Mia',
+ 'Henry',
+ 'Charlotte',
+ 'Alexander',
+ 'Amelia',
+ 'Daniel',
+ 'Harper',
+ 'Matthew',
+ 'Evelyn',
+ 'Sebastian',
+ 'Aria',
+ 'Jack',
+ 'Luna',
+ 'Owen',
+]
+
+LAST_NAMES = [
+ 'Chen',
+ 'Williams',
+ 'Rodriguez',
+ 'Kim',
+ 'Patel',
+ 'Johnson',
+ 'Martinez',
+ 'Anderson',
+ 'Thompson',
+ 'Garcia',
+ 'Lee',
+ 'Wilson',
+ 'Taylor',
+ 'Brown',
+ 'Davis',
+ 'Miller',
+ 'Moore',
+ 'Jackson',
+ 'Martin',
+ 'White',
+ 'Harris',
+ 'Clark',
+ 'Lewis',
+]
+
+DOMAINS = ['techcorp.io', 'acme.com', 'startupxyz.com', 'enterprise.net', 'devco.org']
+
+LLM_MODELS = [
+ 'claude-sonnet-4-5',
+ 'claude-opus-4',
+ 'gpt-4o',
+ 'gpt-4-turbo',
+ 'gemini-1.5-pro',
+ 'claude-3-5-sonnet',
+ 'gpt-4o-mini',
+ 'claude-3-opus',
+]
+
+AGENT_KINDS = [
+ 'CodeAgent',
+ 'AnalysisAgent',
+ 'DebugAgent',
+ 'ReviewAgent',
+ 'DocumentAgent',
+ 'TestAgent',
+ 'RefactorAgent',
+]
+
+REPO_NAMES = [
+ 'frontend-app',
+ 'backend-api',
+ 'mobile-app',
+ 'data-pipeline',
+ 'ml-service',
+ 'auth-service',
+ 'payment-gateway',
+ 'notification-system',
+ 'analytics-dashboard',
+ 'admin-portal',
+ 'e-commerce-platform',
+ 'inventory-management',
+]
+
+BRANCHES = [
+ 'main',
+ 'develop',
+ 'feature/user-auth',
+ 'bugfix/login-issue',
+ 'release/v2.1',
+]
+
+TRIGGERS = ['manual', 'scheduled', 'webhook', 'api', 'cli']
+
+CONVERSATION_TITLES = [
+ 'Fix authentication flow',
+ 'Implement new dashboard features',
+ 'Code review for PR #234',
+ 'Debug memory leak in service',
+ 'Add unit tests for auth module',
+ 'Refactor database queries',
+ 'Setup CI/CD pipeline',
+ 'Performance optimization',
+ 'Security audit fixes',
+ 'Update API documentation',
+ 'Migrate to new framework',
+ 'Add dark mode support',
+ 'Implement search functionality',
+ 'Fix responsive layout',
+ 'Add user analytics',
+ 'Optimize image loading',
+ 'Create API endpoints',
+ 'Write integration tests',
+ 'Fix CSS bugs',
+ 'Deploy to staging',
+]
+
+EXECUTIONS_STATUSES = ['running', 'idle', 'paused', 'finished', 'error', 'stuck']
+SANDBOX_STATUSES = ['RUNNING', 'STARTING', 'PAUSED', 'ERROR', 'MISSING']
+
+
+def random_email(first_name: str, last_name: str) -> str:
+ domain = random.choice(DOMAINS)
+ return f'{first_name.lower()}.{last_name.lower()}@{domain}'
+
+
+def random_datetime(days_back: int = 90) -> datetime:
+ now = datetime.now(UTC)
+ return now - timedelta(days=random.uniform(0, days_back))
+
+
+def create_tables(engine):
+ """Create required tables if they don't exist.
+
+ Note: This script seeds data into the OpenHands enterprise schema which uses:
+ - org (not organizations)
+ - user (not users)
+ - org_member (not organization_members)
+
+ This schema is created by enterprise/migrations/versions/089_create_org_tables.py
+ """
+ print('Creating tables...')
+
+ with engine.connect() as _:
+ # Check if org table exists (we use org, not organizations)
+ result = _.execute(
+ text("""
+ SELECT EXISTS (
+ SELECT FROM information_schema.tables
+ WHERE table_schema = 'public'
+ AND table_name = 'org'
+ );
+ """)
+ )
+ tables_exist = result.scalar()
+
+ if tables_exist:
+ print('Tables already exist, skipping creation.')
+ return
+
+ # Create role table
+ _.execute(
+ text("""
+ CREATE TABLE IF NOT EXISTS role (
+ id SERIAL PRIMARY KEY,
+ name VARCHAR NOT NULL UNIQUE,
+ rank INTEGER NOT NULL
+ );
+ """)
+ )
+
+ # Insert default roles
+ _.execute(
+ text("""
+ INSERT INTO role (name, rank) VALUES ('owner', 10), ('admin', 20), ('member', 1000)
+ ON CONFLICT (name) DO NOTHING;
+ """)
+ )
+
+ # Create org table
+ _.execute(
+ text("""
+ CREATE TABLE IF NOT EXISTS org (
+ id UUID PRIMARY KEY,
+ name VARCHAR(255) NOT NULL,
+ contact_name VARCHAR,
+ contact_email VARCHAR,
+ conversation_expiration INTEGER,
+ agent VARCHAR,
+ default_max_iterations INTEGER,
+ security_analyzer VARCHAR,
+ confirmation_mode BOOLEAN DEFAULT false,
+ default_llm_model VARCHAR,
+ default_llm_base_url VARCHAR,
+ remote_runtime_resource_factor INTEGER,
+ enable_default_condenser BOOLEAN DEFAULT true,
+ billing_margin FLOAT,
+ enable_proactive_conversation_starters BOOLEAN DEFAULT true,
+ sandbox_base_container_image VARCHAR,
+ sandbox_runtime_container_image VARCHAR,
+ org_version INTEGER DEFAULT 0,
+ mcp_config JSON,
+ _search_api_key VARCHAR,
+ _sandbox_api_key VARCHAR,
+ max_budget_per_task FLOAT,
+ enable_solvability_analysis BOOLEAN DEFAULT false,
+ v1_enabled BOOLEAN,
+ condenser_max_size INTEGER,
+ created_at TIMESTAMP WITH TIME ZONE,
+ updated_at TIMESTAMP WITH TIME ZONE,
+ is_github_org BOOLEAN DEFAULT FALSE,
+ org_type VARCHAR(50) DEFAULT 'team',
+ github_installation_id INTEGER,
+ gitlab_group_id INTEGER,
+ is_default BOOLEAN DEFAULT false
+ );
+ """)
+ )
+
+ # Create user table
+ _.execute(
+ text("""
+ CREATE TABLE IF NOT EXISTS "user" (
+ id UUID PRIMARY KEY,
+ current_org_id UUID NOT NULL,
+ role_id INTEGER,
+ accepted_tos TIMESTAMP,
+ enable_sound_notifications BOOLEAN DEFAULT false,
+ language VARCHAR,
+ user_consents_to_analytics BOOLEAN,
+ email VARCHAR,
+ email_verified BOOLEAN,
+ git_user_name VARCHAR,
+ git_user_email VARCHAR,
+ sandbox_grouping_strategy VARCHAR,
+ disabled_skills JSON,
+ onboarding_completed BOOLEAN,
+ llm_profiles TEXT,
+ created_at TIMESTAMP WITH TIME ZONE,
+ updated_at TIMESTAMP WITH TIME ZONE
+ );
+ """)
+ )
+
+ # Create org_member table
+ _.execute(
+ text("""
+ CREATE TABLE IF NOT EXISTS org_member (
+ org_id UUID NOT NULL,
+ user_id UUID NOT NULL,
+ role_id INTEGER NOT NULL,
+ _llm_api_key VARCHAR NOT NULL DEFAULT '',
+ _llm_api_key_for_byor VARCHAR,
+ max_iterations INTEGER,
+ llm_model VARCHAR,
+ llm_base_url VARCHAR,
+ status VARCHAR,
+ agent_settings_diff JSON DEFAULT '{}',
+ conversation_settings_diff JSON DEFAULT '{}',
+ has_custom_llm_api_key BOOLEAN DEFAULT false,
+ created_at TIMESTAMP WITH TIME ZONE,
+ updated_at TIMESTAMP WITH TIME ZONE,
+ PRIMARY KEY (org_id, user_id),
+ FOREIGN KEY (org_id) REFERENCES org(id),
+ FOREIGN KEY (user_id) REFERENCES "user"(id),
+ FOREIGN KEY (role_id) REFERENCES role(id)
+ );
+ """)
+ )
+
+ # Create conversation_metadata table
+ _.execute(
+ text("""
+ CREATE TABLE IF NOT EXISTS conversation_metadata (
+ conversation_id VARCHAR(255) PRIMARY KEY,
+ github_user_id VARCHAR,
+ selected_repository VARCHAR,
+ title VARCHAR,
+ last_updated_at TIMESTAMP WITH TIME ZONE NOT NULL,
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL,
+ selected_branch VARCHAR,
+ user_id VARCHAR,
+ accumulated_cost DOUBLE PRECISION DEFAULT 0,
+ prompt_tokens INTEGER DEFAULT 0,
+ completion_tokens INTEGER DEFAULT 0,
+ total_tokens INTEGER DEFAULT 0,
+ trigger VARCHAR,
+ pr_number JSON,
+ git_provider VARCHAR,
+ llm_model VARCHAR,
+ max_budget_per_task DOUBLE PRECISION,
+ cache_read_tokens INTEGER DEFAULT 0,
+ cache_write_tokens INTEGER DEFAULT 0,
+ reasoning_tokens INTEGER DEFAULT 0,
+ context_window INTEGER DEFAULT 0,
+ per_turn_token INTEGER DEFAULT 0,
+ conversation_version VARCHAR(50) NOT NULL DEFAULT 'V0',
+ sandbox_id VARCHAR,
+ parent_conversation_id VARCHAR,
+ public BOOLEAN,
+ tags JSON,
+ agent_kind VARCHAR,
+ execution_status VARCHAR(50),
+ sandbox_status VARCHAR(50),
+ runtime_url TEXT
+ );
+ """)
+ )
+
+ # Create conversation_metadata_saas table
+ _.execute(
+ text("""
+ CREATE TABLE IF NOT EXISTS conversation_metadata_saas (
+ conversation_id VARCHAR(255) PRIMARY KEY,
+ user_id UUID NOT NULL,
+ org_id UUID NOT NULL,
+ FOREIGN KEY (conversation_id) REFERENCES conversation_metadata(conversation_id) ON DELETE CASCADE,
+ FOREIGN KEY (user_id) REFERENCES "user"(id),
+ FOREIGN KEY (org_id) REFERENCES org(id)
+ );
+ """)
+ )
+
+ _.commit()
+ print('Tables created successfully!')
+
+
+def seed_data(
+ engine,
+ org_count: int = 3,
+ conversations_per_org: int = 30,
+ users_per_org: int = 10,
+):
+ """Seed the database with conversation data.
+
+ Uses the correct OpenHands schema: org, user, org_member tables.
+ """
+ SessionLocal = sessionmaker(bind=engine)
+ session = SessionLocal()
+
+ try:
+ with session.begin():
+ # Create orgs
+ org_ids = []
+ print(f'\nCreating {org_count} orgs...')
+ for i in range(org_count):
+ org_id = str(uuid.uuid4())
+ org_ids.append(org_id)
+
+ session.execute(
+ text("""
+ INSERT INTO org (id, name, created_at, updated_at, is_github_org, org_type)
+ VALUES (:id, :name, :created_at, :updated_at, false, 'team')
+ ON CONFLICT (id) DO NOTHING
+ """),
+ {
+ 'id': org_id,
+ 'name': f'Test Org {i + 1}',
+ 'created_at': datetime.now(UTC),
+ 'updated_at': datetime.now(UTC),
+ },
+ )
+
+ print(f'Created {len(org_ids)} orgs')
+
+ # Create users and conversations for each org
+ total_conversations = 0
+
+ for org_id in org_ids:
+ print('\nCreating users and conversations for org...')
+
+ user_ids = []
+ for j in range(users_per_org):
+ user_id = str(uuid.uuid4())
+ user_ids.append(user_id)
+ first_name = random.choice(FIRST_NAMES)
+ last_name = random.choice(LAST_NAMES)
+ email = random_email(first_name, last_name)
+
+ # First user is the owner/admin, rest are members
+ role_id = (
+ 1 if j == 0 else (2 if j < 3 else 3)
+ ) # owner, admin, member
+
+ session.execute(
+ text("""
+ INSERT INTO "user" (id, current_org_id, role_id, email, created_at, updated_at)
+ VALUES (:id, :current_org_id, :role_id, :email, :created_at, :updated_at)
+ ON CONFLICT (id) DO NOTHING
+ """),
+ {
+ 'id': user_id,
+ 'current_org_id': org_id,
+ 'role_id': role_id,
+ 'email': email,
+ 'created_at': datetime.now(UTC),
+ 'updated_at': datetime.now(UTC),
+ },
+ )
+
+ # Add user to org_member
+ session.execute(
+ text("""
+ INSERT INTO org_member (org_id, user_id, role_id, _llm_api_key, status, agent_settings_diff, conversation_settings_diff, has_custom_llm_api_key, created_at, updated_at)
+ VALUES (:org_id, :user_id, :role_id, '', 'active', '{}', '{}', false, :created_at, :updated_at)
+ ON CONFLICT (org_id, user_id) DO NOTHING
+ """),
+ {
+ 'org_id': org_id,
+ 'user_id': user_id,
+ 'role_id': role_id,
+ 'created_at': datetime.now(UTC),
+ 'updated_at': datetime.now(UTC),
+ },
+ )
+
+ print(f' Created {len(user_ids)} users')
+
+ # Create conversations for this org
+ for k in range(conversations_per_org):
+ conversation_id = str(uuid.uuid4())
+ user_id = random.choice(user_ids)
+ created_at = random_datetime(days_back=90)
+
+ # Ensure updated_at is after created_at
+ updated_at = created_at + timedelta(
+ minutes=random.randint(5, 480), hours=random.randint(0, 72)
+ )
+ if updated_at > datetime.now(UTC):
+ updated_at = datetime.now(UTC) - timedelta(
+ hours=random.randint(1, 24)
+ )
+
+ execution_status = random.choice(EXECUTIONS_STATUSES)
+ sandbox_status = random.choice(SANDBOX_STATUSES)
+
+ if execution_status == 'running':
+ sandbox_status = 'RUNNING'
+
+ if random.random() < 0.7 and execution_status in [
+ 'finished',
+ 'error',
+ 'stuck',
+ ]:
+ sandbox_status = 'MISSING'
+
+ prompt_tokens = random.randint(1000, 50000)
+ completion_tokens = random.randint(500, 25000)
+ cache_read_tokens = random.randint(0, 10000)
+ cache_write_tokens = random.randint(0, 5000)
+
+ cost_per_1k_prompt = random.uniform(0.001, 0.015)
+ cost_per_1k_completion = random.uniform(0.003, 0.075)
+ accumulated_cost = (prompt_tokens / 1000) * cost_per_1k_prompt + (
+ completion_tokens / 1000
+ ) * cost_per_1k_completion
+
+ # Insert into conversation_metadata
+ session.execute(
+ text("""
+ INSERT INTO conversation_metadata (
+ conversation_id, conversation_version, title, llm_model,
+ agent_kind, user_id, created_at, last_updated_at,
+ sandbox_id, sandbox_status, runtime_url, execution_status,
+ selected_repository, selected_branch, trigger,
+ accumulated_cost, prompt_tokens, completion_tokens,
+ total_tokens, cache_read_tokens, cache_write_tokens
+ ) VALUES (
+ :conversation_id, :conversation_version, :title, :llm_model,
+ :agent_kind, :user_id, :created_at, :last_updated_at,
+ :sandbox_id, :sandbox_status, :runtime_url, :execution_status,
+ :selected_repository, :selected_branch, :trigger,
+ :accumulated_cost, :prompt_tokens, :completion_tokens,
+ :total_tokens, :cache_read_tokens, :cache_write_tokens
+ )
+ ON CONFLICT (conversation_id) DO NOTHING
+ """),
+ {
+ 'conversation_id': conversation_id,
+ 'conversation_version': 'V1',
+ 'title': random.choice(CONVERSATION_TITLES),
+ 'llm_model': random.choice(LLM_MODELS),
+ 'agent_kind': random.choice(AGENT_KINDS),
+ 'user_id': user_id,
+ 'created_at': created_at,
+ 'last_updated_at': updated_at,
+ 'sandbox_id': f'sb-{uuid.uuid4().hex[:12]}'
+ if random.random() > 0.1
+ else None,
+ 'sandbox_status': sandbox_status,
+ 'runtime_url': f'https://runtime-{uuid.uuid4().hex[:8]}.example.com'
+ if sandbox_status == 'RUNNING'
+ else None,
+ 'execution_status': execution_status,
+ 'selected_repository': random.choice(REPO_NAMES),
+ 'selected_branch': random.choice(BRANCHES),
+ 'trigger': random.choice(TRIGGERS),
+ 'accumulated_cost': round(accumulated_cost, 4),
+ 'prompt_tokens': prompt_tokens,
+ 'completion_tokens': completion_tokens,
+ 'total_tokens': prompt_tokens + completion_tokens,
+ 'cache_read_tokens': cache_read_tokens,
+ 'cache_write_tokens': cache_write_tokens,
+ },
+ )
+
+ # Insert into conversation_metadata_saas
+ session.execute(
+ text("""
+ INSERT INTO conversation_metadata_saas (conversation_id, user_id, org_id)
+ VALUES (:conversation_id, :user_id, :org_id)
+ ON CONFLICT (conversation_id) DO NOTHING
+ """),
+ {
+ 'conversation_id': conversation_id,
+ 'user_id': user_id,
+ 'org_id': org_id,
+ },
+ )
+
+ total_conversations += conversations_per_org
+ print(f' Created {conversations_per_org} conversations')
+
+ print('\n✅ Seed complete!')
+ print(f' Orgs: {org_count}')
+ print(f' Total users: {org_count * users_per_org}')
+ print(f' Total conversations: {total_conversations}')
+
+ except Exception as e:
+ session.rollback()
+ print(f'❌ Error seeding data: {e}')
+ raise
+ finally:
+ session.close()
+
+
+def main():
+ parser = argparse.ArgumentParser(
+ description='Create tables and seed conversation data for testing.'
+ )
+ parser.add_argument(
+ '--db-url',
+ type=str,
+ default=None,
+ help=f'Database URL (default: DATABASE_URL env var or {DEFAULT_DB_URL})',
+ )
+ parser.add_argument(
+ '--org-count',
+ type=int,
+ default=3,
+ help='Number of organizations to create (default: 3)',
+ )
+ parser.add_argument(
+ '--conversations-per-org',
+ type=int,
+ default=30,
+ help='Number of conversations per organization (default: 30)',
+ )
+ parser.add_argument(
+ '--users-per-org',
+ type=int,
+ default=10,
+ help='Number of users per organization (default: 10)',
+ )
+
+ args = parser.parse_args()
+
+ db_url = args.db_url or DEFAULT_DB_URL
+ print(f'Using database: {db_url}')
+
+ engine = create_engine(db_url)
+
+ # Test connection
+ try:
+ with engine.connect() as _:
+ print('✅ Connected to database')
+ except Exception as e:
+ print(f'❌ Could not connect to database: {e}')
+ return 1
+
+ # Create tables
+ create_tables(engine)
+
+ # Seed data
+ seed_data(
+ engine=engine,
+ org_count=args.org_count,
+ conversations_per_org=args.conversations_per_org,
+ users_per_org=args.users_per_org,
+ )
+
+ print(f'\n📊 Database ready at: {db_url}')
+
+ return 0
+
+
+if __name__ == '__main__':
+ exit(main())
diff --git a/enterprise/scripts/standalone_server.py b/enterprise/scripts/standalone_server.py
new file mode 100644
index 0000000000..7c8389b77e
--- /dev/null
+++ b/enterprise/scripts/standalone_server.py
@@ -0,0 +1,626 @@
+#!/usr/bin/env python3
+"""
+Standalone server to serve the admin dashboard API for testing.
+Runs the conversation stats API with data from the seeded PostgreSQL database.
+
+Usage:
+ python enterprise/scripts/standalone_server.py
+"""
+
+import argparse
+from datetime import UTC, datetime, timedelta
+from typing import Optional
+
+import uvicorn
+from fastapi import FastAPI, HTTPException, Query
+from fastapi.middleware.cors import CORSMiddleware
+from pydantic import BaseModel
+from sqlalchemy import create_engine, text
+from sqlalchemy.orm import sessionmaker
+from starlette.responses import HTMLResponse
+
+DEFAULT_DB_URL = 'postgresql://postgres:postgres@localhost:5432/openhands'
+DEFAULT_PORT = 8080
+
+
+# Pydantic models
+class ConversationStats(BaseModel):
+ active_conversations: int
+ running_runtimes: int
+ completed_24h: int
+ completed_7d: int
+ completed_30d: int
+ total_cost: float
+ total_prompt_tokens: int
+ total_completion_tokens: int
+ total_tokens: int
+
+
+class Conversation(BaseModel):
+ conversation_id: str
+ title: str
+ user_id: str
+ user_name: Optional[str] = None
+ user_email: Optional[str] = None
+ llm_model: str
+ agent_kind: str
+ status: str
+ sandbox_status: str
+ created_at: str
+ last_updated_at: str
+ selected_repository: str
+ selected_branch: str
+ trigger: str
+ accumulated_cost: float
+ prompt_tokens: int
+ completion_tokens: int
+ total_tokens: int
+
+
+class ConversationsResponse(BaseModel):
+ conversations: list[Conversation]
+ total: int
+ page: int
+ page_size: int
+ total_pages: int
+
+
+# Create FastAPI app
+app = FastAPI(title='OpenHands Admin API', version='1.0.0')
+
+# CORS
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=['*'],
+ allow_credentials=True,
+ allow_methods=['*'],
+ allow_headers=['*'],
+)
+
+# Global engine and session
+_engine = None
+_SessionLocal = None
+
+
+def get_engine(db_url: str):
+ global _engine, _SessionLocal
+ if _engine is None:
+ _engine = create_engine(db_url)
+ _SessionLocal = sessionmaker(bind=_engine)
+ return _engine, _SessionLocal
+
+
+async def root():
+ return {'message': 'OpenHands Admin API', 'docs': '/docs'}
+
+
+ '/api/organizations/{org_id}/conversations/stats', response_model=ConversationStats
+)
+async def get_conversation_stats(org_id: str, db_url: str = Query(None)):
+ """Get aggregated conversation statistics for an organization."""
+ db_url = db_url or DEFAULT_DB_URL
+ engine, _ = get_engine(db_url)
+
+ with engine.connect() as conn:
+ now = datetime.now(UTC)
+ time_24h_ago = now - timedelta(hours=24)
+ time_7d_ago = now - timedelta(days=7)
+ time_30d_ago = now - timedelta(days=30)
+
+ # Get conversation counts
+ stats = conn.execute(
+ text("""
+ SELECT
+ COUNT(*) FILTER (WHERE cm.execution_status IN ('running', 'idle', 'paused')) as active_conversations,
+ COUNT(*) FILTER (WHERE cm.sandbox_status = 'RUNNING') as running_runtimes,
+ COUNT(*) FILTER (WHERE cm.execution_status = 'finished' AND cm.last_updated_at >= :time_24h) as completed_24h,
+ COUNT(*) FILTER (WHERE cm.execution_status = 'finished' AND cm.last_updated_at >= :time_7d) as completed_7d,
+ COUNT(*) FILTER (WHERE cm.execution_status = 'finished' AND cm.last_updated_at >= :time_30d) as completed_30d,
+ COALESCE(SUM(cm.accumulated_cost), 0) as total_cost,
+ COALESCE(SUM(cm.prompt_tokens), 0) as total_prompt_tokens,
+ COALESCE(SUM(cm.completion_tokens), 0) as total_completion_tokens,
+ COALESCE(SUM(cm.total_tokens), 0) as total_tokens
+ FROM conversation_metadata cm
+ JOIN conversation_metadata_saas cms ON cm.conversation_id = cms.conversation_id
+ WHERE cms.org_id = :org_id
+ """),
+ {
+ 'org_id': org_id,
+ 'time_24h': time_24h_ago,
+ 'time_7d': time_7d_ago,
+ 'time_30d': time_30d_ago,
+ },
+ ).fetchone()
+
+ return ConversationStats(
+ active_conversations=stats[0] or 0,
+ running_runtimes=stats[1] or 0,
+ completed_24h=stats[2] or 0,
+ completed_7d=stats[3] or 0,
+ completed_30d=stats[4] or 0,
+ total_cost=float(stats[5] or 0),
+ total_prompt_tokens=int(stats[6] or 0),
+ total_completion_tokens=int(stats[7] or 0),
+ total_tokens=int(stats[8] or 0),
+ )
+
+
+ '/api/organizations/{org_id}/conversations', response_model=ConversationsResponse
+)
+async def list_conversations(
+ org_id: str,
+ status: Optional[str] = None,
+ time_window: Optional[str] = None,
+ search: Optional[str] = None,
+ sort_by: str = 'created_at',
+ sort_order: str = 'desc',
+ page: int = 1,
+ page_size: int = 20,
+ db_url: str = Query(None),
+):
+ """List conversations for an organization with filtering and pagination."""
+ db_url = db_url or DEFAULT_DB_URL
+ engine, _ = get_engine(db_url)
+
+ with engine.connect() as conn:
+ # Build query
+ base_query = """
+ SELECT
+ cm.conversation_id,
+ cm.title,
+ cm.user_id,
+ u.name as user_name,
+ u.email as user_email,
+ cm.llm_model,
+ cm.agent_kind,
+ cm.execution_status as status,
+ cm.sandbox_status,
+ cm.created_at,
+ cm.last_updated_at,
+ cm.selected_repository,
+ cm.selected_branch,
+ cm.trigger,
+ cm.accumulated_cost,
+ cm.prompt_tokens,
+ cm.completion_tokens,
+ cm.total_tokens
+ FROM conversation_metadata cm
+ JOIN conversation_metadata_saas cms ON cm.conversation_id = cms.conversation_id
+ LEFT JOIN users u ON cm.user_id = u.id
+ WHERE cms.org_id = :org_id
+ """
+
+ params = {'org_id': org_id}
+
+ # Add filters
+ if status and status != 'all':
+ if status == 'running':
+ base_query += " AND cm.execution_status = 'running'"
+ elif status == 'finished':
+ base_query += " AND cm.execution_status = 'finished'"
+ elif status == 'error':
+ base_query += " AND cm.execution_status IN ('error', 'stuck')"
+
+ if time_window:
+ now = datetime.now(UTC)
+ if time_window == '24h':
+ base_query += ' AND cm.created_at >= :time_filter'
+ params['time_filter'] = now - timedelta(hours=24)
+ elif time_window == '7d':
+ base_query += ' AND cm.created_at >= :time_filter'
+ params['time_filter'] = now - timedelta(days=7)
+ elif time_window == '30d':
+ base_query += ' AND cm.created_at >= :time_filter'
+ params['time_filter'] = now - timedelta(days=30)
+
+ if search:
+ base_query += (
+ ' AND (cm.title ILIKE :search OR cm.selected_repository ILIKE :search)'
+ )
+ params['search'] = f'%{search}%'
+
+ # Count total
+ count_query = f'SELECT COUNT(*) FROM ({base_query}) as subquery'
+ total = conn.execute(text(count_query), params).scalar()
+
+ # Add sorting and pagination
+ valid_sort_columns = [
+ 'created_at',
+ 'last_updated_at',
+ 'title',
+ 'llm_model',
+ 'accumulated_cost',
+ ]
+ if sort_by not in valid_sort_columns:
+ sort_by = 'created_at'
+
+ sort_direction = 'DESC' if sort_order.lower() == 'desc' else 'ASC'
+ base_query += (
+ f' ORDER BY cm.{sort_by} {sort_direction} LIMIT :limit OFFSET :offset'
+ )
+
+ params['limit'] = page_size
+ params['offset'] = (page - 1) * page_size
+
+ # Execute
+ rows = conn.execute(text(base_query), params).fetchall()
+
+ conversations = [
+ Conversation(
+ conversation_id=row[0],
+ title=row[1] or 'Untitled',
+ user_id=row[2],
+ user_name=row[3],
+ user_email=row[4],
+ llm_model=row[5] or 'unknown',
+ agent_kind=row[6] or 'unknown',
+ status=row[7] or 'unknown',
+ sandbox_status=row[8] or 'unknown',
+ created_at=row[9].isoformat() if row[9] else '',
+ last_updated_at=row[10].isoformat() if row[10] else '',
+ selected_repository=row[11] or 'unknown',
+ selected_branch=row[12] or 'unknown',
+ trigger=row[13] or 'unknown',
+ accumulated_cost=float(row[14] or 0),
+ prompt_tokens=int(row[15] or 0),
+ completion_tokens=int(row[16] or 0),
+ total_tokens=int(row[17] or 0),
+ )
+ for row in rows
+ ]
+
+ total_pages = (total + page_size - 1) // page_size
+
+ return ConversationsResponse(
+ conversations=conversations,
+ total=total,
+ page=page,
+ page_size=page_size,
+ total_pages=total_pages,
+ )
+
+
[email protected]('/api/organizations')
+async def list_organizations(db_url: str = Query(None)):
+ """List all organizations with basic info."""
+ db_url = db_url or DEFAULT_DB_URL
+ engine, _ = get_engine(db_url)
+
+ with engine.connect() as conn:
+ orgs = conn.execute(
+ text("""
+ SELECT
+ o.id,
+ o.name,
+ COUNT(DISTINCT om.user_id) as member_count,
+ COUNT(cm.conversation_id) as conversation_count
+ FROM organizations o
+ LEFT JOIN organization_members om ON o.id = om.organization_id
+ LEFT JOIN conversation_metadata_saas cms ON o.id = cms.org_id
+ LEFT JOIN conversation_metadata cm ON cms.conversation_id = cm.conversation_id
+ GROUP BY o.id, o.name
+ """)
+ ).fetchall()
+
+ return [
+ {
+ 'id': str(row[0]),
+ 'name': row[1],
+ 'member_count': row[2],
+ 'conversation_count': row[3],
+ }
+ for row in orgs
+ ]
+
+
[email protected]('/api/organizations/{org_id}')
+async def get_organization(org_id: str, db_url: str = Query(None)):
+ """Get organization details."""
+ db_url = db_url or DEFAULT_DB_URL
+ engine, _ = get_engine(db_url)
+
+ with engine.connect() as conn:
+ org = conn.execute(
+ text("""
+ SELECT
+ o.id,
+ o.name,
+ COUNT(DISTINCT om.user_id) as member_count,
+ COUNT(DISTINCT CASE WHEN om.role = 'owner' THEN om.user_id END) as owner_count,
+ COUNT(DISTINCT CASE WHEN om.role = 'admin' THEN om.user_id END) as admin_count
+ FROM organizations o
+ LEFT JOIN organization_members om ON o.id = om.organization_id
+ WHERE o.id = :org_id
+ GROUP BY o.id, o.name
+ """),
+ {'org_id': org_id},
+ ).fetchone()
+
+ if not org:
+ raise HTTPException(status_code=404, detail='Organization not found')
+
+ return {
+ 'id': str(org[0]),
+ 'name': org[1],
+ 'member_count': org[2],
+ 'owner_count': org[3],
+ 'admin_count': org[4],
+ }
+
+
+def create_standalone_frontend():
+ """Create a simple standalone HTML frontend for the admin dashboard."""
+ return r"""
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>OpenHands Admin Dashboard</title>
+ <style>
+ * { box-sizing: border-box; margin: 0; padding: 0; }
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0f0f0f; color: #e0e0e0; min-height: 100vh; }
+ .container { max-width: 1400px; margin: 0 auto; padding: 2rem; }
+ header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; padding-bottom: 1rem; border-bottom: 1px solid #333; }
+ h1 { font-size: 1.5rem; font-weight: 600; }
+ .org-select { background: #1a1a1a; color: #e0e0e0; border: 1px solid #333; padding: 0.5rem 1rem; border-radius: 6px; min-width: 200px; }
+
+ /* Stats Grid */
+ .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem; }
+ .stat-card { background: #1a1a1a; border-radius: 12px; padding: 1.5rem; border: 1px solid #333; }
+ .stat-card h3 { font-size: 0.875rem; color: #888; margin-bottom: 0.5rem; text-transform: uppercase; letter-spacing: 0.05em; }
+ .stat-card .value { font-size: 2rem; font-weight: 700; color: #fff; }
+ .stat-card .sub { font-size: 0.875rem; color: #666; margin-top: 0.25rem; }
+
+ /* Filter Bar */
+ .filter-bar { display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; align-items: center; }
+ .filter-bar input, .filter-bar select { background: #1a1a1a; color: #e0e0e0; border: 1px solid #333; padding: 0.5rem 1rem; border-radius: 6px; }
+ .filter-bar input { flex: 1; min-width: 200px; }
+ .filter-bar button { background: #3b82f6; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; }
+ .filter-bar button:hover { background: #2563eb; }
+
+ /* Table */
+ .table-container { background: #1a1a1a; border-radius: 12px; border: 1px solid #333; overflow: hidden; }
+ table { width: 100%; border-collapse: collapse; }
+ th { text-align: left; padding: 1rem; background: #252525; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: #888; }
+ td { padding: 1rem; border-top: 1px solid #333; font-size: 0.875rem; }
+ tr:hover td { background: #252525; }
+ .status { display: inline-block; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.75rem; font-weight: 500; }
+ .status.running { background: #22c55e20; color: #22c55e; }
+ .status.finished { background: #3b82f620; color: #3b82f6; }
+ .status.error { background: #ef444420; color: #ef4444; }
+ .status.idle { background: #f59e0b20; color: #f59e0b; }
+ .cost { font-family: monospace; color: #22c55e; }
+
+ /* Pagination */
+ .pagination { display: flex; justify-content: center; align-items: center; gap: 0.5rem; margin-top: 1.5rem; }
+ .pagination button { background: #1a1a1a; color: #e0e0e0; border: 1px solid #333; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; }
+ .pagination button:disabled { opacity: 0.5; cursor: not-allowed; }
+ .pagination span { color: #888; }
+
+ .loading { text-align: center; padding: 2rem; color: #888; }
+ .error { background: #ef444420; color: #ef4444; padding: 1rem; border-radius: 8px; margin-bottom: 1rem; }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <header>
+ <h1>🎯 OpenHands Admin Dashboard</h1>
+ <select id="orgSelect" class="org-select">
+ <option value="">Select Organization</option>
+ </select>
+ </header>
+
+ <div id="error" class="error" style="display: none;"></div>
+
+ <div class="stats-grid" id="stats">
+ <div class="stat-card">
+ <h3>Active Conversations</h3>
+ <div class="value" id="activeConversations">-</div>
+ </div>
+ <div class="stat-card">
+ <h3>Running Runtimes</h3>
+ <div class="value" id="runningRuntimes">-</div>
+ </div>
+ <div class="stat-card">
+ <h3>Completed (24H)</h3>
+ <div class="value" id="completed24h">-</div>
+ </div>
+ <div class="stat-card">
+ <h3>Completed (7D)</h3>
+ <div class="value" id="completed7d">-</div>
+ </div>
+ <div class="stat-card">
+ <h3>Total Cost</h3>
+ <div class="value" id="totalCost">-</div>
+ <div class="sub" id="totalTokens">- tokens</div>
+ </div>
+ </div>
+
+ <div class="filter-bar">
+ <input type="text" id="searchInput" placeholder="Search conversations...">
+ <select id="statusFilter">
+ <option value="all">All Status</option>
+ <option value="running">Running</option>
+ <option value="finished">Finished</option>
+ <option value="error">Error</option>
+ </select>
+ <select id="timeWindow">
+ <option value="">All Time</option>
+ <option value="24h">Last 24 Hours</option>
+ <option value="7d">Last 7 Days</option>
+ <option value="30d">Last 30 Days</option>
+ </select>
+ <select id="sortBy">
+ <option value="created_at">Sort: Created</option>
+ <option value="last_updated_at">Sort: Updated</option>
+ <option value="title">Sort: Title</option>
+ <option value="accumulated_cost">Sort: Cost</option>
+ </select>
+ <button onclick="loadConversations(1)">Apply Filters</button>
+ </div>
+
+ <div class="table-container">
+ <table>
+ <thead>
+ <tr>
+ <th>Title</th>
+ <th>User</th>
+ <th>Model</th>
+ <th>Status</th>
+ <th>Created</th>
+ <th>Cost</th>
+ <th>Tokens</th>
+ </tr>
+ </thead>
+ <tbody id="conversationsTable">
+ <tr><td colspan="7" class="loading">Select an organization to view conversations</td></tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div class="pagination" id="pagination"></div>
+ </div>
+
+ <script>
+ const API_BASE = window.location.origin;
+ let currentOrg = null;
+ let currentPage = 1;
+
+ async function loadOrganizations() {
+ try {
+ const res = await fetch(API_BASE + '/api/organizations');
+ const orgs = await res.json();
+ const select = document.getElementById('orgSelect');
+ select.innerHTML = '<option value="">Select Organization</option>';
+ orgs.forEach(org => {
+ select.innerHTML += `<option value="${org.id}">${org.name} (${org.conversation_count} convos)</option>`;
+ });
+ } catch (e) {
+ showError('Failed to load organizations: ' + e.message);
+ }
+ }
+
+ async function loadStats(orgId) {
+ try {
+ const res = await fetch(API_BASE + '/api/organizations/' + orgId + '/conversations/stats');
+ const stats = await res.json();
+ document.getElementById('activeConversations').textContent = stats.active_conversations;
+ document.getElementById('runningRuntimes').textContent = stats.running_runtimes;
+ document.getElementById('completed24h').textContent = stats.completed_24h;
+ document.getElementById('completed7d').textContent = stats.completed_7d;
+ document.getElementById('totalCost').textContent = '$' + stats.total_cost.toFixed(2);
+ document.getElementById('totalTokens').textContent = formatNumber(stats.total_tokens) + ' tokens';
+ } catch (e) {
+ showError('Failed to load stats: ' + e.message);
+ }
+ }
+
+ async function loadConversations(page = 1) {
+ if (!currentOrg) return;
+ currentPage = page;
+
+ const search = document.getElementById('searchInput').value;
+ const status = document.getElementById('statusFilter').value;
+ const timeWindow = document.getElementById('timeWindow').value;
+ const sortBy = document.getElementById('sortBy').value;
+
+ const params = new URLSearchParams({ page, sort_by: sortBy });
+ if (search) params.append('search', search);
+ if (status !== 'all') params.append('status', status);
+ if (timeWindow) params.append('time_window', timeWindow);
+
+ try {
+ const res = await fetch(API_BASE + '/api/organizations/' + currentOrg + '/conversations?' + params);
+ const data = await res.json();
+ renderTable(data.conversations);
+ renderPagination(data);
+ } catch (e) {
+ showError('Failed to load conversations: ' + e.message);
+ }
+ }
+
+ function renderTable(conversations) {
+ const tbody = document.getElementById('conversationsTable');
+ if (conversations.length === 0) {
+ tbody.innerHTML = '<tr><td colspan="7" class="loading">No conversations found</td></tr>';
+ return;
+ }
+ tbody.innerHTML = conversations.map(c => {
+ const statusClass = c.status === 'running' ? 'running' : c.status === 'finished' ? 'finished' : 'error';
+ const date = new Date(c.created_at).toLocaleDateString();
+ return \`
+ <tr>
+ <td>\${c.title}</td>
+ <td>\${c.user_name || c.user_email || 'Unknown'}</td>
+ <td>\${c.llm_model}</td>
+ <td><span class="status \${statusClass}">\${c.status}</span></td>
+ <td>\${date}</td>
+ <td class="cost">$\${c.accumulated_cost.toFixed(4)}</td>
+ <td>\${formatNumber(c.total_tokens)}</td>
+ </tr>
+ \`;
+ }).join('');
+ }
+
+ function renderPagination(data) {
+ const div = document.getElementById('pagination');
+ let html = \`<button onclick="loadConversations(\${data.page - 1})" \${data.page <= 1 ? 'disabled' : ''}>Previous</button>\`;
+ html += \`<span>Page \${data.page} of \${data.total_pages}</span>\`;
+ html += \`<button onclick="loadConversations(\${data.page + 1})" \${data.page >= data.total_pages ? 'disabled' : ''}>Next</button>\`;
+ div.innerHTML = html;
+ }
+
+ function formatNumber(n) {
+ if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
+ if (n >= 1000) return (n / 1000).toFixed(1) + 'K';
+ return n.toString();
+ }
+
+ function showError(msg) {
+ document.getElementById('error').textContent = msg;
+ document.getElementById('error').style.display = 'block';
+ }
+
+ document.getElementById('orgSelect').addEventListener('change', async (e) => {
+ currentOrg = e.target.value;
+ if (currentOrg) {
+ await loadStats(currentOrg);
+ await loadConversations(1);
+ }
+ });
+
+ // Initialize
+ loadOrganizations();
+ </script>
+</body>
+</html>
+"""
+
+
+# Add static file route for the frontend
[email protected]('/dashboard')
+async def dashboard():
+ return HTMLResponse(create_standalone_frontend())
+
+
+def main():
+ parser = argparse.ArgumentParser(description='Run standalone admin API server')
+ parser.add_argument('--port', type=int, default=DEFAULT_PORT, help='Port to run on')
+ parser.add_argument('--db-url', type=str, default=None, help='Database URL')
+ args = parser.parse_args()
+
+ db_url = args.db_url or DEFAULT_DB_URL
+ print(f'Starting server on port {args.port}')
+ print(f'Database: {db_url}')
+ print(f'API Docs: http://localhost:{args.port}/docs')
+ print(f'Dashboard: http://localhost:{args.port}/dashboard')
+
+ uvicorn.run(app, host='0.0.0.0', port=args.port)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/enterprise/server/auth/authorization.py b/enterprise/server/auth/authorization.py
index 469076b1d3..6a981aff30 100644
--- a/enterprise/server/auth/authorization.py
+++ b/enterprise/server/auth/authorization.py
@@ -93,6 +93,9 @@ class Permission(str, Enum):
# User provisioning (create new Keycloak/OpenHands users directly in an org)
PROVISION_USER = 'provision_user'
+ # Organization Conversations (Admin/Owner only)
+ VIEW_ORG_CONVERSATIONS = 'view_org_conversations'
+
class RoleName(str, Enum):
"""Role names used in the system."""
@@ -133,6 +136,8 @@ ROLE_PERMISSIONS: dict[RoleName, frozenset[Permission]] = {
Permission.MANAGE_AUTOMATIONS,
# User provisioning
Permission.PROVISION_USER,
+ # Organization Conversations (Admin/Owner only)
+ Permission.VIEW_ORG_CONVERSATIONS,
]
),
RoleName.ADMIN: frozenset(
@@ -160,6 +165,8 @@ ROLE_PERMISSIONS: dict[RoleName, frozenset[Permission]] = {
Permission.MANAGE_AUTOMATIONS,
# User provisioning
Permission.PROVISION_USER,
+ # Organization Conversations (Admin/Owner only)
+ Permission.VIEW_ORG_CONVERSATIONS,
]
),
RoleName.MEMBER: frozenset(
diff --git a/enterprise/server/routes/org_models.py b/enterprise/server/routes/org_models.py
index 11c20a4d51..2ed6dd0b9e 100644
--- a/enterprise/server/routes/org_models.py
+++ b/enterprise/server/routes/org_models.py
@@ -1,3 +1,4 @@
+from datetime import datetime
from typing import Annotated, Any
from pydantic import (
@@ -658,3 +659,102 @@ class OrgMemberFinancialPage(BaseModel):
current_page: int = 1
per_page: int = 10
next_page_id: str | None = None
+
+
+class OrgConversationResponse(BaseModel):
+ """Response model for a single conversation in an organization."""
+
+ id: str # conversation_id
+ title: str | None = None
+ llm_model: str | None = None
+ agent_kind: str = 'openhands'
+ user_id: str # UUID of user who created the conversation
+ user_email: str | None = None # Email of user who created the conversation
+ created_at: datetime | None = None
+ updated_at: datetime | None = None
+ sandbox_id: str | None = None
+ sandbox_status: str | None = None # STARTING, RUNNING, PAUSED, ERROR, MISSING
+ runtime_url: str | None = None # URL to access the conversation runtime
+ execution_status: str | None = (
+ None # Agent execution status (requires agent server call)
+ )
+ selected_repository: str | None = None
+ selected_branch: str | None = None
+ trigger: str | None = None
+ tags: dict[str, str] = Field(default_factory=dict)
+ # Cost and token metrics
+ accumulated_cost: float = 0.0
+ prompt_tokens: int = 0
+ completion_tokens: int = 0
+ total_tokens: int = 0
+ cache_read_tokens: int = 0
+ cache_write_tokens: int = 0
+
+
+class OrgConversationPage(BaseModel):
+ """Paginated response for organization conversations."""
+
+ items: list[OrgConversationResponse]
+ total_items: int = 0 # Total count for pagination controls
+ page: int = 1 # Current page number
+ per_page: int = 100 # Items per page
+ total_pages: int = 0 # Total number of pages
+ pagination_accurate: bool = (
+ True # False when sandbox_status filter lacks sandbox data
+ )
+
+
+class OrgConversationStats(BaseModel):
+ """Aggregated statistics for organization conversations."""
+
+ # Conversation counts
+ active_conversations: int = (
+ 0 # Count of conversations with execution_status='running'
+ )
+ running_runtimes: int = 0 # Count of distinct sandboxes currently running
+
+ # Completion metrics
+ completed_24h: int = 0 # Conversations that finished (terminal status) in last 24h
+ completed_7d: int = 0 # Conversations that finished in last 7 days
+ completed_30d: int = 0 # Conversations that finished in last 30 days
+
+ # Cost and usage aggregation
+ total_cost: float = 0.0 # Sum of accumulated_cost
+ total_prompt_tokens: int = 0
+ total_completion_tokens: int = 0
+ total_tokens: int = 0 # Combined token count
+
+
+class DailyUsageData(BaseModel):
+ """Daily usage data for a single day."""
+
+ date: str # ISO date string (YYYY-MM-DD)
+ tokens: int = 0
+ conversations: int = 0
+
+
+class TeamUsageData(BaseModel):
+ """Usage data for a single user/team."""
+
+ user_id: str
+ user_email: str | None = None
+ user_name: str | None = None
+ conversation_count: int = 0
+ total_tokens: int = 0
+ percentage: float = 0.0
+
+
+class OrgUsageStats(BaseModel):
+ """Detailed usage statistics for organization dashboard."""
+
+ # Top-level metrics
+ active_users: int = 0 # Users with activity in last 7 days
+ agent_runs: int = 0 # Total conversations in last 7 days
+ total_tokens: int = 0 # Total tokens in last 7 days
+ estimated_spend: float = 0.0 # Estimated cost in last 7 days
+
+ # Daily breakdown (last 7 days)
+ daily_usage: list[DailyUsageData] = Field(default_factory=list)
+
+ # Team breakdown (by user)
+ team_usage: list[TeamUsageData] = Field(default_factory=list)
diff --git a/enterprise/server/routes/orgs.py b/enterprise/server/routes/orgs.py
index 4cc893a210..5253a194b6 100644
--- a/enterprise/server/routes/orgs.py
+++ b/enterprise/server/routes/orgs.py
@@ -1,7 +1,11 @@
+import csv
+import io
+from datetime import datetime, timezone
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query, status
+from fastapi.responses import StreamingResponse
from server.auth.authorization import (
Permission,
require_financial_data_access,
@@ -23,6 +27,9 @@ from server.routes.org_models import (
OrgAppSettingsResponse,
OrgAppSettingsUpdate,
OrgAuthorizationError,
+ OrgConversationPage,
+ OrgConversationResponse,
+ OrgConversationStats,
OrgCreate,
OrgDatabaseError,
OrgDefaultsSettingsResponse,
@@ -36,6 +43,7 @@ from server.routes.org_models import (
OrgPage,
OrgResponse,
OrgUpdate,
+ OrgUsageStats,
OrphanedUserError,
RoleNotFoundError,
)
@@ -43,6 +51,11 @@ from server.services.org_app_settings_service import (
OrgAppSettingsService,
OrgAppSettingsServiceInjector,
)
+from server.services.org_conversation_service import (
+ OrgConversationFilterError,
+ OrgConversationService,
+ OrgConversationServiceInjector,
+)
from server.services.org_member_financial_service import OrgMemberFinancialService
from server.services.org_member_service import OrgMemberService
from sqlalchemy.exc import IntegrityError
@@ -66,6 +79,11 @@ org_router = APIRouter(
_org_app_settings_injector = OrgAppSettingsServiceInjector()
org_app_settings_service_dependency = Depends(_org_app_settings_injector.depends)
+_org_conversation_service_injector = OrgConversationServiceInjector()
+org_conversation_service_dependency = Depends(
+ _org_conversation_service_injector.depends
+)
+
@org_router.get('', response_model=OrgPage)
async def list_user_orgs(
@@ -1484,3 +1502,592 @@ async def disconnect_git_organization(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to disconnect Git organization',
)
+
+
+@org_router.get(
+ '/{org_id}/conversations',
+ response_model=OrgConversationPage,
+)
+async def list_org_conversations(
+ org_id: UUID,
+ # Search
+ search: Annotated[
+ str | None,
+ Query(
+ title='Search text matching conversation name, creator name, email, or sandbox ID'
+ ),
+ ] = None,
+ # Sorting
+ sort_by: Annotated[
+ str,
+ Query(
+ title='Field to sort by',
+ description='Options: created_at, updated_at, llm_model, accumulated_cost, title',
+ ),
+ ] = 'updated_at',
+ sort_order: Annotated[
+ str,
+ Query(
+ title='Sort order',
+ description='Options: desc (default), asc',
+ ),
+ ] = 'desc',
+ # Filters
+ execution_status: Annotated[
+ list[str] | None,
+ Query(
+ title='Filter by execution status',
+ description='Comma-separated list: idle, running, paused, finished, error, stuck',
+ ),
+ ] = None,
+ sandbox_status: Annotated[
+ str | None,
+ Query(
+ title='Filter by sandbox status',
+ description='Filter by sandbox status: STARTING, RUNNING, PAUSED, ERROR, MISSING. '
+ 'Note: when filtering by sandbox_status, total_items reflects the unfiltered '
+ 'count since the filter is applied post-query. This may result in pagination '
+ 'showing fewer items per page than expected.',
+ ),
+ ] = None,
+ time_window: Annotated[
+ str | None,
+ Query(
+ title='Time window filter',
+ description='Options: all, 7d, 30d, 90d',
+ ),
+ ] = None,
+ # Pagination
+ page: Annotated[
+ int,
+ Query(
+ title='Page number',
+ ge=1,
+ ),
+ ] = 1,
+ per_page: Annotated[
+ int,
+ Query(
+ title='Items per page',
+ ge=1,
+ le=100,
+ ),
+ ] = 20,
+ include_sub_conversations: Annotated[
+ bool,
+ Query(
+ title='If True, include sub-conversations. If False (default), exclude them.'
+ ),
+ ] = False,
+ user_id: str = Depends(require_permission(Permission.VIEW_ORG_CONVERSATIONS)),
+ service: OrgConversationService = org_conversation_service_dependency,
+) -> OrgConversationPage:
+ """List all conversations for an organization.
+
+ This endpoint returns a paginated list of all conversations within an organization,
+ including details about each conversation such as the creator, timestamps, and metrics.
+
+ **Access Control**: Requires VIEW_ORG_CONVERSATIONS permission (Admin or Owner role).
+
+ Args:
+ org_id: Organization UUID
+ search: Search text matching conversation name, creator name, email, or sandbox ID
+ sort_by: Field to sort by (created_at, updated_at, llm_model, accumulated_cost, title)
+ sort_order: Sort order (desc or asc)
+ execution_status: Filter by execution status (idle, running, paused, finished, error, stuck)
+ sandbox_status: Filter by sandbox status (STARTING, RUNNING, PAUSED, ERROR, MISSING)
+ time_window: Time window filter (all, 7d, 30d, 90d)
+ page: Page number (1-indexed)
+ per_page: Items per page (1-100)
+ include_sub_conversations: If True, include sub-conversations in results
+ user_id: Authenticated user ID (injected by require_permission dependency)
+ service: OrgConversationService instance
+
+ Returns:
+ OrgConversationPage: Paginated list of conversations with total count
+
+ Raises:
+ HTTPException: 401 if user is not authenticated
+ HTTPException: 403 if user lacks VIEW_ORG_CONVERSATIONS permission
+ HTTPException: 500 if retrieval fails
+ """
+ logger.info(
+ 'Listing organization conversations',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'search': search,
+ 'sort_by': sort_by,
+ 'sort_order': sort_order,
+ 'execution_status': execution_status,
+ 'sandbox_status': sandbox_status,
+ 'time_window': time_window,
+ 'page': page,
+ 'per_page': per_page,
+ },
+ )
+
+ try:
+ # Convert single string to list for service compatibility
+ sandbox_status_list = [sandbox_status] if sandbox_status else None
+ result = await service.list_org_conversations(
+ org_id=org_id,
+ search=search,
+ sort_by=sort_by,
+ sort_order=sort_order,
+ execution_status=execution_status,
+ sandbox_status=sandbox_status_list,
+ time_window=time_window,
+ page=page,
+ per_page=per_page,
+ include_sub_conversations=include_sub_conversations,
+ )
+
+ logger.info(
+ 'Successfully retrieved organization conversations',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'count': len(result.items),
+ 'total_items': result.total_items,
+ },
+ )
+
+ return result
+
+ except OrgConversationFilterError as e:
+ logger.warning(
+ 'Invalid organization conversation filter',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'error': e.message,
+ 'error_code': e.error_code,
+ },
+ )
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=e.message,
+ )
+ except Exception as e:
+ logger.exception(
+ 'Unexpected error listing organization conversations',
+ extra={'user_id': user_id, 'org_id': str(org_id), 'error': str(e)},
+ )
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail='Failed to retrieve organization conversations',
+ )
+
+
+@org_router.get(
+ '/{org_id}/conversations/stats',
+ response_model=OrgConversationStats,
+)
+async def get_org_conversation_stats(
+ org_id: UUID,
+ user_id: str = Depends(require_permission(Permission.VIEW_ORG_CONVERSATIONS)),
+ service: OrgConversationService = org_conversation_service_dependency,
+) -> OrgConversationStats:
+ """Get aggregated statistics for organization conversations.
+
+ Returns counts of active conversations, running runtimes, completed conversations,
+ and aggregated cost/token usage for the organization.
+
+ **Access Control**: Requires VIEW_ORG_CONVERSATIONS permission (Admin or Owner role).
+
+ Returns:
+ OrgConversationStats: Aggregated statistics for the org
+ """
+ logger.info(
+ 'Getting organization conversation stats',
+ extra={'user_id': user_id, 'org_id': str(org_id)},
+ )
+
+ try:
+ stats = await service.get_stats(org_id=org_id)
+
+ logger.info(
+ 'Successfully retrieved organization conversation stats',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'active_conversations': stats.active_conversations,
+ 'running_runtimes': stats.running_runtimes,
+ 'total_cost': stats.total_cost,
+ },
+ )
+
+ return stats
+
+ except Exception as e:
+ logger.exception(
+ 'Unexpected error getting organization conversation stats',
+ extra={'user_id': user_id, 'org_id': str(org_id), 'error': str(e)},
+ )
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail='Failed to retrieve organization conversation stats',
+ )
+
+
+@org_router.get(
+ '/{org_id}/conversations/usage-stats',
+ response_model=OrgUsageStats,
+)
+async def get_org_conversation_usage_stats(
+ org_id: UUID,
+ days: int = Query(
+ default=7, ge=1, le=90, description='Number of days to look back'
+ ),
+ user_id: str = Depends(require_permission(Permission.VIEW_ORG_CONVERSATIONS)),
+ service: OrgConversationService = org_conversation_service_dependency,
+) -> OrgUsageStats:
+ """Get detailed usage statistics for organization dashboard.
+
+ Returns detailed metrics including active users, agent runs, token usage,
+ daily breakdown, and team usage for the specified time window.
+
+ **Access Control**: Requires VIEW_ORG_CONVERSATIONS permission (Admin or Owner role).
+
+ Args:
+ org_id: The organization ID
+ days: Number of days to look back (1-90, default 7)
+
+ Returns:
+ OrgUsageStats: Detailed usage statistics for the org
+ """
+ logger.info(
+ 'Getting organization conversation usage stats',
+ extra={'user_id': user_id, 'org_id': str(org_id), 'days': days},
+ )
+
+ try:
+ stats = await service.get_usage_stats(org_id=org_id, days=days)
+
+ logger.info(
+ 'Successfully retrieved organization conversation usage stats',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'days': days,
+ 'active_users': stats.active_users,
+ 'agent_runs': stats.agent_runs,
+ 'total_tokens': stats.total_tokens,
+ },
+ )
+
+ return stats
+
+ except Exception as e:
+ logger.exception(
+ 'Unexpected error getting organization conversation usage stats',
+ extra={'user_id': user_id, 'org_id': str(org_id), 'error': str(e)},
+ )
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail='Failed to retrieve organization conversation usage stats',
+ )
+
+
+@org_router.get(
+ '/{org_id}/conversations/export',
+ response_class=StreamingResponse,
+)
+async def export_org_conversations_csv(
+ org_id: UUID,
+ search: Annotated[
+ str | None,
+ Query(
+ title='Search text matching conversation name, creator name, email, or sandbox ID'
+ ),
+ ] = None,
+ sort_by: Annotated[
+ str,
+ Query(title='Field to sort by'),
+ ] = 'updated_at',
+ sort_order: Annotated[
+ str,
+ Query(title='Sort order'),
+ ] = 'desc',
+ execution_status: Annotated[
+ list[str] | None,
+ Query(title='Filter by execution status'),
+ ] = None,
+ sandbox_status: Annotated[
+ str | None,
+ Query(title='Filter by sandbox status'),
+ ] = None,
+ time_window: Annotated[
+ str | None,
+ Query(title='Time window filter (7d, 30d, 90d)'),
+ ] = None,
+ include_sub_conversations: Annotated[
+ bool,
+ Query(title='If True, include sub-conversations'),
+ ] = False,
+ user_id: str = Depends(require_permission(Permission.VIEW_ORG_CONVERSATIONS)),
+ service: OrgConversationService = org_conversation_service_dependency,
+) -> StreamingResponse:
+ """Export organization conversations as CSV.
+
+ Returns the filtered conversation dataset as a downloadable CSV file.
+
+ **Access Control**: Requires VIEW_ORG_CONVERSATIONS permission (Admin or Owner role).
+ """
+ logger.info(
+ 'Exporting organization conversations as CSV',
+ extra={'user_id': user_id, 'org_id': str(org_id)},
+ )
+
+ try:
+ # Fetch all conversations (no pagination for export)
+ result = await service.list_org_conversations(
+ org_id=org_id,
+ search=search,
+ sort_by=sort_by,
+ sort_order=sort_order,
+ execution_status=execution_status,
+ sandbox_status=[sandbox_status] if sandbox_status else None,
+ time_window=time_window,
+ page=1,
+ per_page=10000, # Export up to 10k records
+ include_sub_conversations=include_sub_conversations,
+ )
+
+ # Build response headers
+ timestamp = datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')
+ filename = f'conversations_export_{timestamp}.csv'
+ headers = {'Content-Disposition': f'attachment; filename="{filename}"'}
+ if result.total_items > 10000:
+ headers['X-Export-Truncated'] = 'true'
+
+ async def generate():
+ output = io.StringIO()
+ writer = csv.writer(output)
+
+ # Write header row
+ writer.writerow(
+ [
+ 'id',
+ 'title',
+ 'llm_model',
+ 'agent_kind',
+ 'user_id',
+ 'user_email',
+ 'created_at',
+ 'updated_at',
+ 'sandbox_id',
+ 'sandbox_status',
+ 'runtime_url',
+ 'execution_status',
+ 'selected_repository',
+ 'selected_branch',
+ 'trigger',
+ 'accumulated_cost',
+ 'prompt_tokens',
+ 'completion_tokens',
+ 'total_tokens',
+ 'cache_read_tokens',
+ 'cache_write_tokens',
+ ]
+ )
+
+ # Write data rows
+ for item in result.items:
+ writer.writerow(
+ [
+ item.id,
+ item.title,
+ item.llm_model,
+ item.agent_kind,
+ item.user_id,
+ item.user_email,
+ item.created_at,
+ item.updated_at,
+ item.sandbox_id,
+ item.sandbox_status,
+ item.runtime_url,
+ item.execution_status,
+ item.selected_repository,
+ item.selected_branch,
+ item.trigger,
+ item.accumulated_cost,
+ item.prompt_tokens,
+ item.completion_tokens,
+ item.total_tokens,
+ item.cache_read_tokens,
+ item.cache_write_tokens,
+ ]
+ )
+
+ yield output.getvalue()
+
+ return StreamingResponse(
+ generate(),
+ media_type='text/csv',
+ headers=headers,
+ )
+
+ except OrgConversationFilterError as e:
+ logger.warning(
+ 'Invalid organization conversation filter for export',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'error': e.message,
+ 'error_code': e.error_code,
+ },
+ )
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=e.message,
+ )
+ except Exception as e:
+ logger.exception(
+ 'Unexpected error exporting organization conversations',
+ extra={'user_id': user_id, 'org_id': str(org_id), 'error': str(e)},
+ )
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail='Failed to export organization conversations',
+ )
+
+
+@org_router.get(
+ '/{org_id}/conversations/{conversation_id}',
+ response_model=OrgConversationResponse,
+)
+async def get_org_conversation(
+ org_id: UUID,
+ conversation_id: str,
+ user_id: str = Depends(require_permission(Permission.VIEW_ORG_CONVERSATIONS)),
+ service: OrgConversationService = org_conversation_service_dependency,
+) -> OrgConversationResponse:
+ """Get a specific conversation by ID.
+
+ Returns full conversation details including logs/history reference.
+
+ **Access Control**: Requires VIEW_ORG_CONVERSATIONS permission (Admin or Owner role).
+
+ Raises:
+ HTTPException: 404 if conversation not found or not in org
+ """
+ logger.info(
+ 'Getting organization conversation',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'conversation_id': conversation_id,
+ },
+ )
+
+ try:
+ result = await service.get_org_conversation(
+ org_id=org_id,
+ conversation_id=conversation_id,
+ )
+
+ if result is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail='Conversation not found',
+ )
+
+ return result
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.exception(
+ 'Unexpected error getting organization conversation',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'conversation_id': conversation_id,
+ 'error': str(e),
+ },
+ )
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail='Failed to retrieve conversation',
+ )
+
+
+@org_router.post(
+ '/{org_id}/conversations/{conversation_id}/stop',
+)
+async def stop_org_conversation(
+ org_id: UUID,
+ conversation_id: str,
+ user_id: str = Depends(require_permission(Permission.VIEW_ORG_CONVERSATIONS)),
+ service: OrgConversationService = org_conversation_service_dependency,
+):
+ """Stop a running conversation and its runtime.
+
+ Safely terminates active agent loops and shuts down the underlying
+ runtime execution cell.
+
+ **Access Control**: Requires VIEW_ORG_CONVERSATIONS permission (Admin or Owner role).
+
+ Returns:
+ Success message with stopped conversation details
+
+ Raises:
+ HTTPException: 404 if conversation not found
+ HTTPException: 409 if conversation is not running
+ HTTPException: 503 if runtime stop fails
+ """
+ logger.info(
+ 'Stopping organization conversation',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'conversation_id': conversation_id,
+ },
+ )
+
+ try:
+ result = await service.stop_conversation(
+ org_id=org_id,
+ conversation_id=conversation_id,
+ user_id=user_id,
+ )
+
+ if result is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail='Conversation not found',
+ )
+
+ if result.get('error'):
+ error_code = result.get('error_code')
+ if error_code == 'sandbox_shared':
+ status_code = status.HTTP_409_CONFLICT
+ elif error_code in {'sandbox_unavailable', 'sandbox_stop_failed'}:
+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE
+ else:
+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE
+ raise HTTPException(
+ status_code=status_code,
+ detail=result['error'],
+ )
+
+ return result
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.exception(
+ 'Unexpected error stopping organization conversation',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'conversation_id': conversation_id,
+ 'error': str(e),
+ },
+ )
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail='Failed to stop conversation',
+ )
diff --git a/enterprise/server/services/org_conversation_service.py b/enterprise/server/services/org_conversation_service.py
new file mode 100644
index 0000000000..4c8ee7dc6e
--- /dev/null
+++ b/enterprise/server/services/org_conversation_service.py
@@ -0,0 +1,868 @@
+"""Service class for organization conversation listing.
+
+Separates business logic from route handlers.
+Uses dependency injection for db_session and sandbox_service.
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from typing import AsyncGenerator
+from uuid import UUID
+
+from fastapi import Request
+from server.routes.org_models import (
+ DailyUsageData,
+ OrgConversationPage,
+ OrgConversationResponse,
+ OrgConversationStats,
+ OrgUsageStats,
+ TeamUsageData,
+)
+from sqlalchemy import func, or_, select
+from sqlalchemy.ext.asyncio import AsyncSession
+from storage.stored_conversation_metadata import StoredConversationMetadata
+from storage.stored_conversation_metadata_saas import StoredConversationMetadataSaas
+from storage.user import User
+
+from openhands.app_server.sandbox.sandbox_models import AGENT_SERVER, SandboxInfo
+from openhands.app_server.services.injector import Injector, InjectorState
+from openhands.app_server.utils.logger import openhands_logger as logger
+from openhands.sdk.llm import MetricsSnapshot, TokenUsage
+
+# Valid sort fields
+VALID_SORT_FIELDS = {
+ 'created_at': StoredConversationMetadata.created_at,
+ 'updated_at': StoredConversationMetadata.last_updated_at,
+ 'llm_model': StoredConversationMetadata.llm_model,
+ 'accumulated_cost': StoredConversationMetadata.accumulated_cost,
+ 'title': StoredConversationMetadata.title,
+}
+
+# Time window options (in days)
+TIME_WINDOW_OPTIONS = {
+ '7d': 7,
+ '30d': 30,
+ '90d': 90,
+}
+
+MAX_SANDBOX_STATUS_FILTER_ROWS = 5000
+
+
+class OrgConversationFilterError(ValueError):
+ def __init__(self, message: str, error_code: str) -> None:
+ super().__init__(message)
+ self.error_code = error_code
+ self.message = message
+
+
+@dataclass
+class OrgConversationService:
+ """Service for organization conversations with injected dependencies."""
+
+ db_session: AsyncSession
+ sandbox_service = None # Optional: SandboxService for live status
+
+ def set_sandbox_service(self, sandbox_service):
+ """Set the sandbox service for live status fetching."""
+ self.sandbox_service = sandbox_service
+
+ def _build_conversation_response(
+ self,
+ metadata: StoredConversationMetadata,
+ saas_metadata: StoredConversationMetadataSaas,
+ user: User | None,
+ sandbox_info: SandboxInfo | None,
+ ) -> OrgConversationResponse:
+ """Build an OrgConversationResponse from a row and sandbox info."""
+ resolved_sandbox_status = sandbox_info.status.value if sandbox_info else None
+
+ # Construct runtime URL from exposed URLs
+ runtime_url = None
+ if sandbox_info and sandbox_info.exposed_urls:
+ agent_server_url = next(
+ (
+ exposed_url.url
+ for exposed_url in sandbox_info.exposed_urls
+ if exposed_url.name == AGENT_SERVER
+ ),
+ None,
+ )
+ if agent_server_url:
+ runtime_url = (
+ f'{agent_server_url}/api/conversations/{metadata.conversation_id}'
+ )
+
+ # Build metrics
+ token_usage = TokenUsage(
+ prompt_tokens=metadata.prompt_tokens or 0,
+ completion_tokens=metadata.completion_tokens or 0,
+ cache_read_tokens=metadata.cache_read_tokens or 0,
+ cache_write_tokens=metadata.cache_write_tokens or 0,
+ context_window=metadata.context_window or 0,
+ per_turn_token=metadata.per_turn_token or 0,
+ )
+ metrics = MetricsSnapshot(
+ accumulated_cost=metadata.accumulated_cost or 0.0,
+ max_budget_per_task=metadata.max_budget_per_task,
+ accumulated_token_usage=token_usage,
+ )
+
+ return OrgConversationResponse(
+ id=metadata.conversation_id,
+ title=metadata.title,
+ llm_model=metadata.llm_model,
+ agent_kind=metadata.agent_kind or 'openhands',
+ user_id=str(saas_metadata.user_id),
+ user_email=user.email if user else None,
+ created_at=metadata.created_at,
+ updated_at=metadata.last_updated_at,
+ sandbox_id=metadata.sandbox_id,
+ sandbox_status=resolved_sandbox_status,
+ runtime_url=runtime_url,
+ execution_status=metadata.execution_status,
+ selected_repository=metadata.selected_repository,
+ selected_branch=metadata.selected_branch,
+ trigger=metadata.trigger,
+ tags=metadata.tags or {},
+ accumulated_cost=metrics.accumulated_cost,
+ prompt_tokens=metrics.accumulated_token_usage.prompt_tokens, # type: ignore[union-attr]
+ completion_tokens=metrics.accumulated_token_usage.completion_tokens, # type: ignore[union-attr]
+ total_tokens=(
+ metrics.accumulated_token_usage.prompt_tokens # type: ignore[union-attr]
+ + metrics.accumulated_token_usage.completion_tokens # type: ignore[union-attr]
+ ),
+ cache_read_tokens=metrics.accumulated_token_usage.cache_read_tokens, # type: ignore[union-attr]
+ cache_write_tokens=metrics.accumulated_token_usage.cache_write_tokens, # type: ignore[union-attr]
+ )
+
+ async def _count_conversations_by_sandbox_id(self, sandbox_id: str) -> int:
+ count_query = (
+ select(func.count())
+ .select_from(StoredConversationMetadata)
+ .where(
+ StoredConversationMetadata.conversation_version == 'V1',
+ StoredConversationMetadata.sandbox_id == sandbox_id,
+ )
+ )
+ result = await self.db_session.execute(count_query)
+ return result.scalar() or 0
+
+ async def list_org_conversations(
+ self,
+ org_id: UUID,
+ search: str | None = None,
+ sort_by: str = 'updated_at',
+ sort_order: str = 'desc',
+ execution_status: list[str] | None = None,
+ sandbox_status: list[str] | None = None,
+ time_window: str | None = None,
+ page: int = 1,
+ per_page: int = 20,
+ include_sub_conversations: bool = False,
+ ) -> OrgConversationPage:
+ """List all conversations for an organization with filtering, sorting, and pagination.
+
+ Args:
+ org_id: The organization ID
+ search: Search text matching conversation name, creator name, email, or sandbox ID
+ sort_by: Field to sort by (created_at, updated_at, llm_model, accumulated_cost, title)
+ sort_order: Sort order ('desc' or 'asc')
+ execution_status: Filter by execution status values
+ sandbox_status: Filter by sandbox status values
+ time_window: Time window filter ('7d', '30d', '90d', or None for all)
+ page: Page number (1-indexed)
+ per_page: Items per page (1-100)
+ include_sub_conversations: If True, include sub-conversations
+
+ Returns:
+ OrgConversationPage: Paginated list of conversations with total count
+ """
+ # Base query with joins
+ query = (
+ select(StoredConversationMetadata, StoredConversationMetadataSaas, User)
+ .join(
+ StoredConversationMetadataSaas,
+ StoredConversationMetadata.conversation_id
+ == StoredConversationMetadataSaas.conversation_id,
+ )
+ .outerjoin(User, StoredConversationMetadataSaas.user_id == User.id)
+ .where(StoredConversationMetadata.conversation_version == 'V1')
+ .where(StoredConversationMetadataSaas.org_id == org_id)
+ )
+
+ # Exclude sub-conversations unless explicitly requested
+ if not include_sub_conversations:
+ query = query.where(
+ StoredConversationMetadata.parent_conversation_id.is_(None)
+ )
+
+ # Apply search filter
+ if search:
+ search_pattern = f'%{search}%'
+ query = query.where(
+ or_(
+ StoredConversationMetadata.title.ilike(search_pattern),
+ StoredConversationMetadata.sandbox_id.ilike(search_pattern),
+ User.email.ilike(search_pattern),
+ User.git_user_name.ilike(search_pattern),
+ )
+ )
+
+ # Apply execution_status filter
+ if execution_status:
+ query = query.where(
+ StoredConversationMetadata.execution_status.in_(execution_status)
+ )
+
+ # Apply time_window filter
+ if time_window and time_window in TIME_WINDOW_OPTIONS:
+ days = TIME_WINDOW_OPTIONS[time_window]
+ cutoff_date = datetime.now(UTC) - timedelta(days=days)
+ query = query.where(StoredConversationMetadata.created_at >= cutoff_date)
+
+ # Apply sorting
+ sort_column = VALID_SORT_FIELDS.get(
+ sort_by, StoredConversationMetadata.last_updated_at
+ )
+ if sort_order.lower() == 'asc':
+ query = query.order_by(sort_column.asc().nullslast())
+ else:
+ query = query.order_by(sort_column.desc().nullslast())
+
+ pagination_accurate = not (sandbox_status and not self.sandbox_service)
+ sandbox_info_map: dict[str, SandboxInfo | None] = {}
+
+ if sandbox_status:
+ limited_query = query.limit(MAX_SANDBOX_STATUS_FILTER_ROWS + 1)
+ result = await self.db_session.execute(limited_query)
+ rows = result.all()
+
+ if len(rows) > MAX_SANDBOX_STATUS_FILTER_ROWS:
+ raise OrgConversationFilterError(
+ 'Sandbox status filter is too broad; refine filters or remove '
+ 'the sandbox_status filter.',
+ error_code='sandbox_status_too_broad',
+ )
+
+ sandbox_ids = [
+ metadata.sandbox_id for metadata, _, _ in rows if metadata.sandbox_id
+ ]
+
+ if sandbox_ids and self.sandbox_service:
+ try:
+ sandbox_results = await self.sandbox_service.batch_get_sandboxes(
+ sandbox_ids
+ )
+ for sandbox_id, sandbox_info in zip(sandbox_ids, sandbox_results):
+ sandbox_info_map[sandbox_id] = sandbox_info
+ except Exception as e:
+ logger.warning(
+ 'Failed to fetch sandbox info for org conversations',
+ extra={'org_id': str(org_id), 'error': str(e)},
+ )
+
+ rows = [
+ row
+ for row in rows
+ if row[0].sandbox_id
+ and sandbox_info_map.get(row[0].sandbox_id)
+ and sandbox_info_map[row[0].sandbox_id].status.value in sandbox_status # type: ignore[union-attr]
+ ]
+
+ total_items = len(rows)
+ total_pages = math.ceil(total_items / per_page) if total_items > 0 else 0
+
+ offset = (page - 1) * per_page
+ rows = rows[offset : offset + per_page]
+ else:
+ count_query = select(func.count()).select_from(query.subquery())
+ count_result = await self.db_session.execute(count_query)
+ total_items = count_result.scalar() or 0
+ total_pages = math.ceil(total_items / per_page) if total_items > 0 else 0
+
+ offset = (page - 1) * per_page
+ query = query.offset(offset).limit(per_page)
+
+ result = await self.db_session.execute(query)
+ rows = result.all()
+
+ sandbox_ids = [
+ metadata.sandbox_id for metadata, _, _ in rows if metadata.sandbox_id
+ ]
+
+ if sandbox_ids and self.sandbox_service:
+ try:
+ sandbox_results = await self.sandbox_service.batch_get_sandboxes(
+ sandbox_ids
+ )
+ for sandbox_id, sandbox_info in zip(sandbox_ids, sandbox_results):
+ sandbox_info_map[sandbox_id] = sandbox_info
+ except Exception as e:
+ logger.warning(
+ 'Failed to fetch sandbox info for org conversations',
+ extra={'org_id': str(org_id), 'error': str(e)},
+ )
+
+ # Build response items
+ items: list[OrgConversationResponse] = []
+ for metadata, saas_metadata, user in rows:
+ sandbox_info = sandbox_info_map.get(metadata.sandbox_id)
+ items.append(
+ self._build_conversation_response(
+ metadata, saas_metadata, user, sandbox_info
+ )
+ )
+
+ logger.info(
+ 'Listed organization conversations',
+ extra={
+ 'org_id': str(org_id),
+ 'count': len(items),
+ 'total_items': total_items,
+ 'page': page,
+ 'per_page': per_page,
+ },
+ )
+
+ return OrgConversationPage(
+ items=items,
+ total_items=total_items,
+ page=page,
+ per_page=per_page,
+ total_pages=total_pages,
+ pagination_accurate=pagination_accurate,
+ )
+
+ async def get_stats(
+ self,
+ org_id: UUID,
+ ) -> OrgConversationStats:
+ """Get aggregated statistics for organization conversations.
+
+ Args:
+ org_id: The organization ID
+
+ Returns:
+ OrgConversationStats with aggregated stats for the org
+ """
+ now = datetime.now(UTC)
+ cutoff_24h = now - timedelta(hours=24)
+ cutoff_7d = now - timedelta(days=7)
+ cutoff_30d = now - timedelta(days=30)
+
+ # Base query for org conversations
+ base_filter = [
+ StoredConversationMetadata.conversation_version == 'V1',
+ StoredConversationMetadataSaas.org_id == org_id,
+ ]
+
+ # 1. Active conversations (execution_status = 'running')
+ active_query = (
+ select(func.count(StoredConversationMetadata.conversation_id))
+ .select_from(StoredConversationMetadata)
+ .join(
+ StoredConversationMetadataSaas,
+ StoredConversationMetadata.conversation_id
+ == StoredConversationMetadataSaas.conversation_id,
+ )
+ .where(*base_filter)
+ .where(StoredConversationMetadata.execution_status == 'running')
+ )
+ result = await self.db_session.execute(active_query)
+ active_conversations = result.scalar() or 0
+
+ # 2. Aggregate cost and tokens (all time)
+ aggregate_query = (
+ select(
+ func.coalesce(func.sum(StoredConversationMetadata.accumulated_cost), 0),
+ func.coalesce(func.sum(StoredConversationMetadata.prompt_tokens), 0),
+ func.coalesce(
+ func.sum(StoredConversationMetadata.completion_tokens), 0
+ ),
+ )
+ .select_from(StoredConversationMetadata)
+ .join(
+ StoredConversationMetadataSaas,
+ StoredConversationMetadata.conversation_id
+ == StoredConversationMetadataSaas.conversation_id,
+ )
+ .where(*base_filter)
+ )
+ result = await self.db_session.execute(aggregate_query)
+ total_cost, total_prompt, total_completion = result.one()
+
+ # 3. Completed in 24h, 7d, 30d (terminal status = finished, error, stuck)
+ terminal_statuses = ['finished', 'error', 'stuck']
+
+ # Helper to count completed conversations since a given cutoff
+ async def count_completed(cutoff: datetime) -> int:
+ completed_query = (
+ select(func.count(StoredConversationMetadata.conversation_id))
+ .select_from(StoredConversationMetadata)
+ .join(
+ StoredConversationMetadataSaas,
+ StoredConversationMetadata.conversation_id
+ == StoredConversationMetadataSaas.conversation_id,
+ )
+ .where(*base_filter)
+ .where(
+ StoredConversationMetadata.execution_status.in_(terminal_statuses)
+ )
+ .where(StoredConversationMetadata.last_updated_at >= cutoff)
+ )
+ res = await self.db_session.execute(completed_query)
+ return res.scalar() or 0
+
+ completed_24h = await count_completed(cutoff_24h)
+ completed_7d = await count_completed(cutoff_7d)
+ completed_30d = await count_completed(cutoff_30d)
+
+ # 4. Running runtimes (requires sandbox service)
+ running_runtimes = 0
+ if self.sandbox_service:
+ try:
+ # Get distinct sandbox IDs from active conversations
+ sandbox_ids_query = (
+ select(StoredConversationMetadata.sandbox_id)
+ .select_from(StoredConversationMetadata)
+ .join(
+ StoredConversationMetadataSaas,
+ StoredConversationMetadata.conversation_id
+ == StoredConversationMetadataSaas.conversation_id,
+ )
+ .where(*base_filter)
+ .where(StoredConversationMetadata.execution_status == 'running')
+ .where(StoredConversationMetadata.sandbox_id.isnot(None))
+ .distinct()
+ )
+ result = await self.db_session.execute(sandbox_ids_query)
+ sandbox_ids = [row[0] for row in result.all()]
+
+ # Batch fetch all sandbox statuses in one call
+ if sandbox_ids:
+ sandbox_results = await self.sandbox_service.batch_get_sandboxes(
+ sandbox_ids
+ )
+ for sandbox in sandbox_results:
+ if sandbox and sandbox.status.value == 'RUNNING':
+ running_runtimes += 1
+ except Exception as e:
+ logger.warning(
+ 'Failed to get running runtimes count',
+ extra={'org_id': str(org_id), 'error': str(e)},
+ )
+
+ return OrgConversationStats(
+ active_conversations=active_conversations,
+ running_runtimes=running_runtimes,
+ completed_24h=completed_24h,
+ completed_7d=completed_7d,
+ completed_30d=completed_30d,
+ total_cost=float(total_cost or 0),
+ total_prompt_tokens=int(total_prompt or 0),
+ total_completion_tokens=int(total_completion or 0),
+ total_tokens=int((total_prompt or 0) + (total_completion or 0)),
+ )
+
+ async def get_usage_stats(
+ self,
+ org_id: UUID,
+ days: int = 7,
+ ) -> OrgUsageStats:
+ """Get detailed usage statistics for organization dashboard.
+
+ Args:
+ org_id: The organization ID
+ days: Number of days to look back (default 7)
+
+ Returns:
+ OrgUsageStats with detailed usage data
+ """
+ now = datetime.now(UTC)
+ cutoff = now - timedelta(days=days)
+
+ # Base filter for org conversations
+ base_filter = [
+ StoredConversationMetadata.conversation_version == 'V1',
+ StoredConversationMetadataSaas.org_id == org_id,
+ ]
+
+ # 1. Active users (users with activity in the time window)
+ active_users_query = (
+ select(func.count(func.distinct(StoredConversationMetadataSaas.user_id)))
+ .select_from(StoredConversationMetadata)
+ .join(
+ StoredConversationMetadataSaas,
+ StoredConversationMetadata.conversation_id
+ == StoredConversationMetadataSaas.conversation_id,
+ )
+ .where(*base_filter)
+ .where(StoredConversationMetadata.created_at >= cutoff)
+ )
+ result = await self.db_session.execute(active_users_query)
+ active_users = result.scalar() or 0
+
+ # 2. Total agent runs (conversations) in time window
+ agent_runs_query = (
+ select(func.count(StoredConversationMetadata.conversation_id))
+ .select_from(StoredConversationMetadata)
+ .join(
+ StoredConversationMetadataSaas,
+ StoredConversationMetadata.conversation_id
+ == StoredConversationMetadataSaas.conversation_id,
+ )
+ .where(*base_filter)
+ .where(StoredConversationMetadata.created_at >= cutoff)
+ )
+ result = await self.db_session.execute(agent_runs_query)
+ agent_runs = result.scalar() or 0
+
+ # 3. Total tokens and cost in time window
+ totals_query = (
+ select(
+ func.coalesce(func.sum(StoredConversationMetadata.accumulated_cost), 0),
+ func.coalesce(func.sum(StoredConversationMetadata.prompt_tokens), 0),
+ func.coalesce(
+ func.sum(StoredConversationMetadata.completion_tokens), 0
+ ),
+ )
+ .select_from(StoredConversationMetadata)
+ .join(
+ StoredConversationMetadataSaas,
+ StoredConversationMetadata.conversation_id
+ == StoredConversationMetadataSaas.conversation_id,
+ )
+ .where(*base_filter)
+ .where(StoredConversationMetadata.created_at >= cutoff)
+ )
+ result = await self.db_session.execute(totals_query)
+ total_cost, total_prompt_tokens, total_completion_tokens = result.one()
+
+ # 4. Daily usage breakdown (single query instead of N queries)
+ from sqlalchemy import Date, cast
+
+ daily_query = (
+ select(
+ cast(StoredConversationMetadata.created_at, Date).label('day'),
+ func.count(StoredConversationMetadata.conversation_id),
+ func.coalesce(
+ func.sum(
+ StoredConversationMetadata.prompt_tokens
+ + StoredConversationMetadata.completion_tokens
+ ),
+ 0,
+ ),
+ )
+ .select_from(StoredConversationMetadata)
+ .join(
+ StoredConversationMetadataSaas,
+ StoredConversationMetadata.conversation_id
+ == StoredConversationMetadataSaas.conversation_id,
+ )
+ .where(*base_filter)
+ .where(StoredConversationMetadata.created_at >= cutoff)
+ .group_by(cast(StoredConversationMetadata.created_at, Date))
+ .order_by(cast(StoredConversationMetadata.created_at, Date).asc())
+ )
+ result = await self.db_session.execute(daily_query)
+ daily_rows = result.all()
+
+ # Build a map of date -> (conv_count, token_count)
+ daily_map = {row[0]: (row[1], row[2]) for row in daily_rows}
+
+ # Generate entries for all days in range (including days with no data)
+ daily_usage = []
+ for i in range(days - 1, -1, -1):
+ day_start = (now - timedelta(days=i)).replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ day_date = day_start.date() if hasattr(day_start, 'date') else day_start
+ conv_count, token_count = daily_map.get(day_date, (0, 0))
+ daily_usage.append(
+ DailyUsageData(
+ date=day_start.strftime('%Y-%m-%d'),
+ tokens=int(token_count or 0),
+ conversations=int(conv_count or 0),
+ )
+ )
+
+ # 5. Team usage (by user)
+ team_query = (
+ select(
+ StoredConversationMetadataSaas.user_id,
+ User.email,
+ User.git_user_name,
+ func.count(StoredConversationMetadata.conversation_id).label(
+ 'conv_count'
+ ),
+ func.coalesce(
+ func.sum(
+ StoredConversationMetadata.prompt_tokens
+ + StoredConversationMetadata.completion_tokens
+ ),
+ 0,
+ ).label('token_count'),
+ )
+ .select_from(StoredConversationMetadata)
+ .join(
+ StoredConversationMetadataSaas,
+ StoredConversationMetadata.conversation_id
+ == StoredConversationMetadataSaas.conversation_id,
+ )
+ .outerjoin(User, StoredConversationMetadataSaas.user_id == User.id)
+ .where(*base_filter)
+ .where(StoredConversationMetadata.created_at >= cutoff)
+ .group_by(
+ StoredConversationMetadataSaas.user_id,
+ User.email,
+ User.git_user_name,
+ )
+ .order_by(func.count(StoredConversationMetadata.conversation_id).desc())
+ )
+ result = await self.db_session.execute(team_query)
+ team_rows = result.all()
+
+ # Calculate percentages
+ total_team_convs = sum(row.conv_count or 0 for row in team_rows)
+ team_usage = []
+ for row in team_rows:
+ pct = (
+ (row.conv_count / total_team_convs * 100) if total_team_convs > 0 else 0
+ )
+ team_usage.append(
+ TeamUsageData(
+ user_id=str(row.user_id),
+ user_email=row.email,
+ user_name=row.git_user_name,
+ conversation_count=int(row.conv_count or 0),
+ total_tokens=int(row.token_count or 0),
+ percentage=round(pct, 1),
+ )
+ )
+
+ return OrgUsageStats(
+ active_users=int(active_users),
+ agent_runs=int(agent_runs),
+ total_tokens=int(total_prompt_tokens or 0)
+ + int(total_completion_tokens or 0),
+ estimated_spend=float(total_cost or 0),
+ daily_usage=daily_usage,
+ team_usage=team_usage,
+ )
+
+ async def get_org_conversation(
+ self,
+ org_id: UUID,
+ conversation_id: str,
+ ) -> OrgConversationResponse | None:
+ """Get a single conversation by ID.
+
+ Args:
+ org_id: The organization ID
+ conversation_id: The conversation ID
+
+ Returns:
+ OrgConversationResponse if found, None otherwise
+ """
+ query = (
+ select(StoredConversationMetadata, StoredConversationMetadataSaas, User)
+ .join(
+ StoredConversationMetadataSaas,
+ StoredConversationMetadata.conversation_id
+ == StoredConversationMetadataSaas.conversation_id,
+ )
+ .outerjoin(User, StoredConversationMetadataSaas.user_id == User.id)
+ .where(StoredConversationMetadata.conversation_version == 'V1')
+ .where(StoredConversationMetadataSaas.org_id == org_id)
+ .where(StoredConversationMetadata.conversation_id == conversation_id)
+ )
+
+ result = await self.db_session.execute(query)
+ row = result.one_or_none()
+
+ if row is None:
+ return None
+
+ metadata, saas_metadata, user = row
+
+ # Get sandbox info if available
+ sandbox_info = None
+ if metadata.sandbox_id and self.sandbox_service:
+ try:
+ sandbox_info = await self.sandbox_service.get_sandbox(
+ metadata.sandbox_id
+ )
+ except Exception as e:
+ logger.warning(
+ 'Failed to fetch sandbox info for conversation',
+ extra={'conversation_id': conversation_id, 'error': str(e)},
+ )
+
+ return self._build_conversation_response(
+ metadata, saas_metadata, user, sandbox_info
+ )
+
+ async def stop_conversation(
+ self,
+ org_id: UUID,
+ conversation_id: str,
+ user_id: str,
+ ) -> dict | None:
+ """Stop a running conversation and its runtime.
+
+ Args:
+ org_id: The organization ID
+ conversation_id: The conversation ID
+ user_id: The user performing the action
+
+ Returns:
+ Dict with success status and message
+ """
+ # First, verify the conversation exists and belongs to the org
+ query = (
+ select(StoredConversationMetadata)
+ .join(
+ StoredConversationMetadataSaas,
+ StoredConversationMetadata.conversation_id
+ == StoredConversationMetadataSaas.conversation_id,
+ )
+ .where(StoredConversationMetadata.conversation_version == 'V1')
+ .where(StoredConversationMetadataSaas.org_id == org_id)
+ .where(StoredConversationMetadata.conversation_id == conversation_id)
+ )
+
+ result = await self.db_session.execute(query)
+ metadata = result.scalar_one_or_none()
+
+ if metadata is None:
+ return None
+
+ # Check if there's a sandbox to stop
+ if not metadata.sandbox_id:
+ return {
+ 'success': True,
+ 'message': 'Conversation has no running sandbox',
+ 'conversation_id': conversation_id,
+ }
+
+ # Try to stop via sandbox service
+ if self.sandbox_service:
+ try:
+ sandbox_info = await self.sandbox_service.get_sandbox(
+ metadata.sandbox_id
+ )
+ if sandbox_info is None:
+ return {
+ 'success': True,
+ 'message': 'Sandbox already stopped or not found',
+ 'conversation_id': conversation_id,
+ }
+
+ conversation_count = await self._count_conversations_by_sandbox_id(
+ metadata.sandbox_id
+ )
+ if conversation_count > 1:
+ return {
+ 'success': False,
+ 'error': 'Sandbox is shared by multiple conversations',
+ 'error_code': 'sandbox_shared',
+ 'conversation_id': conversation_id,
+ 'sandbox_id': metadata.sandbox_id,
+ }
+
+ # Update execution status to indicate stopping
+ previous_status = metadata.execution_status
+ metadata.execution_status = 'deleting'
+ await self.db_session.commit()
+
+ # Actually terminate the sandbox
+ try:
+ deleted = await self.sandbox_service.delete_sandbox(
+ metadata.sandbox_id
+ )
+ if not deleted:
+ metadata.execution_status = previous_status
+ await self.db_session.commit()
+ return {
+ 'success': False,
+ 'error': 'Failed to stop sandbox',
+ 'error_code': 'sandbox_stop_failed',
+ 'conversation_id': conversation_id,
+ 'sandbox_id': metadata.sandbox_id,
+ }
+ except Exception:
+ # Rollback the status change so the row isn't left as 'deleting'
+ metadata.execution_status = previous_status
+ await self.db_session.commit()
+ raise
+
+ logger.info(
+ 'Stopping sandbox for org conversation',
+ extra={
+ 'conversation_id': conversation_id,
+ 'sandbox_id': metadata.sandbox_id,
+ 'user_id': user_id,
+ },
+ )
+
+ return {
+ 'success': True,
+ 'message': 'Stop request sent to sandbox',
+ 'conversation_id': conversation_id,
+ 'sandbox_id': metadata.sandbox_id,
+ }
+ except Exception as e:
+ logger.exception(
+ 'Failed to stop sandbox',
+ extra={
+ 'conversation_id': conversation_id,
+ 'sandbox_id': metadata.sandbox_id,
+ 'error': str(e),
+ },
+ )
+ return {
+ 'success': False,
+ 'error': 'Failed to stop sandbox',
+ 'error_code': 'sandbox_stop_failed',
+ 'conversation_id': conversation_id,
+ }
+ else:
+ return {
+ 'success': False,
+ 'error': 'Sandbox service not available',
+ 'error_code': 'sandbox_unavailable',
+ 'conversation_id': conversation_id,
+ }
+
+
+class OrgConversationServiceInjector(Injector[OrgConversationService]):
+ """Injector that composes db_session and sandbox_service for OrgConversationService."""
+
+ async def inject(
+ self, state: InjectorState, request: Request | None = None
+ ) -> AsyncGenerator[OrgConversationService, None]:
+ # Local imports to avoid circular dependencies
+ from openhands.app_server.config import get_db_session, get_sandbox_service
+
+ async with get_db_session(state, request) as db_session:
+ service = OrgConversationService(db_session=db_session)
+
+ # Try to inject sandbox service if available
+ try:
+ async with get_sandbox_service(state, request) as sandbox_service:
+ service.set_sandbox_service(sandbox_service)
+ yield service
+ return
+ except AssertionError as e:
+ # Sandbox service not configured - log at warning level since
+ # this is a SaaS-specific feature that requires it
+ logger.warning(
+ 'Sandbox service not available for OrgConversationService; '
+ 'live sandbox status will not be available',
+ extra={'error': str(e)},
+ )
+
+ yield service
diff --git a/enterprise/storage/user_store.py b/enterprise/storage/user_store.py
index e1ee4e0725..18cdfb1a64 100644
--- a/enterprise/storage/user_store.py
+++ b/enterprise/storage/user_store.py
@@ -16,6 +16,7 @@ from server.constants import (
)
from server.logger import logger
from sqlalchemy import select, text
+from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import selectinload
from storage.database import a_session_maker
from storage.encrypt_utils import (
@@ -70,16 +71,36 @@ class UserStore:
on the old values.
"""
async with a_session_maker() as session:
- # create personal org
- org = Org(
- id=uuid.UUID(user_id),
- name=f'user_{user_id}_org',
- contact_name=resolve_display_name(user_info)
- or user_info.get('preferred_username', ''),
- contact_email=user_info['email'],
- v1_enabled=True,
+ user_uuid = uuid.UUID(user_id)
+ result = await session.execute(
+ select(User)
+ .options(selectinload(User.org_members))
+ .filter(User.id == user_uuid)
)
- session.add(org)
+ existing_user = result.scalars().first()
+ if existing_user:
+ return existing_user
+
+ org = await session.get(Org, user_uuid)
+ org_created = False
+ if not org:
+ org = Org(
+ id=user_uuid,
+ name=f'user_{user_id}_org',
+ contact_name=resolve_display_name(user_info)
+ or user_info.get('preferred_username', ''),
+ contact_email=user_info['email'],
+ v1_enabled=True,
+ )
+ session.add(org)
+ org_created = True
+ else:
+ if not org.contact_name:
+ org.contact_name = resolve_display_name(user_info) or user_info.get(
+ 'preferred_username', ''
+ )
+ if not org.contact_email:
+ org.contact_email = user_info.get('email')
settings = await UserStore.create_default_settings(
org_id=str(org.id), user_id=user_id
@@ -88,16 +109,17 @@ class UserStore:
if not settings:
return None
- from storage.org_store import OrgStore
+ if org_created:
+ from storage.org_store import OrgStore
- org_kwargs = OrgStore.get_kwargs_from_settings(settings)
- for key, value in org_kwargs.items():
- if hasattr(org, key):
- setattr(org, key, value)
+ org_kwargs = OrgStore.get_kwargs_from_settings(settings)
+ for key, value in org_kwargs.items():
+ if hasattr(org, key):
+ setattr(org, key, value)
user_kwargs = UserStore.get_kwargs_from_settings(settings)
user = User(
- id=uuid.UUID(user_id),
+ id=user_uuid,
current_org_id=org.id,
role_id=role_id,
**user_kwargs,
@@ -121,7 +143,23 @@ class UserStore:
**org_member_kwargs,
)
session.add(org_member)
- await session.commit()
+ try:
+ await session.commit()
+ except IntegrityError:
+ await session.rollback()
+ logger.warning(
+ 'user_store:create_user:integrity_error',
+ extra={'user_id': user_id},
+ )
+ result = await session.execute(
+ select(User)
+ .options(selectinload(User.org_members))
+ .filter(User.id == user_uuid)
+ )
+ existing_user = result.scalars().first()
+ if existing_user:
+ return existing_user
+ raise
await session.refresh(user)
await session.refresh(user, ['org_members']) # load org_members
return user
diff --git a/enterprise/tests/unit/test_authorization.py b/enterprise/tests/unit/test_authorization.py
index 62394fec94..4e3f329ef8 100644
--- a/enterprise/tests/unit/test_authorization.py
+++ b/enterprise/tests/unit/test_authorization.py
@@ -57,6 +57,7 @@ class TestPermission:
assert Permission.CHANGE_ORGANIZATION_NAME.value == 'change_organization_name'
assert Permission.DELETE_ORGANIZATION.value == 'delete_organization'
assert Permission.MANAGE_AUTOMATIONS.value == 'manage_automations'
+ assert Permission.VIEW_ORG_CONVERSATIONS.value == 'view_org_conversations'
def test_permission_from_string(self):
"""
@@ -144,6 +145,7 @@ class TestRolePermissions:
assert Permission.CHANGE_ORGANIZATION_NAME in owner_perms
assert Permission.DELETE_ORGANIZATION in owner_perms
assert Permission.MANAGE_AUTOMATIONS in owner_perms
+ assert Permission.VIEW_ORG_CONVERSATIONS in owner_perms
def test_admin_has_admin_permissions(self):
"""
@@ -162,6 +164,7 @@ class TestRolePermissions:
assert Permission.CHANGE_USER_ROLE_MEMBER in admin_perms
assert Permission.CHANGE_USER_ROLE_ADMIN in admin_perms
assert Permission.MANAGE_AUTOMATIONS in admin_perms
+ assert Permission.VIEW_ORG_CONVERSATIONS in admin_perms
# Admin should NOT have owner-only permissions
assert Permission.CHANGE_USER_ROLE_OWNER not in admin_perms
assert Permission.CHANGE_ORGANIZATION_NAME not in admin_perms
@@ -193,6 +196,7 @@ class TestRolePermissions:
assert Permission.CHANGE_USER_ROLE_OWNER not in member_perms
assert Permission.CHANGE_ORGANIZATION_NAME not in member_perms
assert Permission.DELETE_ORGANIZATION not in member_perms
+ assert Permission.VIEW_ORG_CONVERSATIONS not in member_perms
# =============================================================================
diff --git a/enterprise/tests/unit/test_user_store.py b/enterprise/tests/unit/test_user_store.py
index 95124233e4..99fb610ffe 100644
--- a/enterprise/tests/unit/test_user_store.py
+++ b/enterprise/tests/unit/test_user_store.py
@@ -10,6 +10,8 @@ import pytest
from pydantic import SecretStr
from sqlalchemy import select
from storage.org import Org
+from storage.org_member import OrgMember
+from storage.role import Role
from storage.user import User
from storage.user_store import UserStore
@@ -243,6 +245,79 @@ async def test_create_default_settings_v1_enabled_false_when_default_is_false(
assert captured_settings.v1_enabled is False
+async def test_create_user_reuses_existing_org(async_session_maker):
+ user_id = str(uuid.uuid4())
+ user_uuid = uuid.UUID(user_id)
+ user_info = {
+ 'email': '[email protected]',
+ 'preferred_username': 'test-user',
+ 'name': 'Test User',
+ }
+
+ mock_settings = Settings(language='en')
+ mock_settings.update(
+ {
+ 'agent_settings_diff': {
+ 'agent': 'CodeActAgent',
+ 'llm': {
+ 'model': 'anthropic/claude-sonnet-4-5-20250929',
+ 'api_key': 'test_api_key',
+ 'base_url': 'http://test.url',
+ },
+ },
+ }
+ )
+
+ async with async_session_maker() as session:
+ session.add(
+ Org(
+ id=user_uuid,
+ name=f'user_{user_id}_org',
+ contact_name='Existing User',
+ contact_email='[email protected]',
+ )
+ )
+ session.add(Role(id=1, name='owner', rank=10))
+ await session.commit()
+
+ with (
+ patch('storage.user_store.a_session_maker', async_session_maker),
+ patch('storage.role_store.a_session_maker', async_session_maker),
+ patch(
+ 'storage.user_store.UserStore.create_default_settings',
+ new_callable=AsyncMock,
+ return_value=mock_settings,
+ ),
+ ):
+ user = await UserStore.create_user(user_id, user_info)
+
+ assert user is not None
+ assert user.id == user_uuid
+ assert user.current_org_id == user_uuid
+
+ async with async_session_maker() as session:
+ db_user = (
+ (await session.execute(select(User).filter(User.id == user_uuid)))
+ .scalars()
+ .first()
+ )
+ org_member = (
+ (
+ await session.execute(
+ select(OrgMember).filter(
+ OrgMember.org_id == user_uuid, OrgMember.user_id == user_uuid
+ )
+ )
+ )
+ .scalars()
+ .first()
+ )
+
+ assert db_user is not None
+ assert org_member is not None
+
+
# --- Tests for get_user_by_id ---
diff --git a/frontend/__tests__/components/features/user/user-context-menu.test.tsx b/frontend/__tests__/components/features/user/user-context-menu.test.tsx
index d0769fa958..0bd3e5f091 100644
--- a/frontend/__tests__/components/features/user/user-context-menu.test.tsx
+++ b/frontend/__tests__/components/features/user/user-context-menu.test.tsx
@@ -196,6 +196,9 @@ describe("UserContextMenu", () => {
// In SaaS, personal LLM/Condenser/Verification routes are hidden in favor
// of /settings/org-defaults/* (visible only when an org is selected, which
// this test does not seed). Org-only and billing routes are also filtered.
+ // The admin dashboard link is also hidden because the test renders as a
+ // non-admin "member" user; useSettingsNavItems() suppresses it for members
+ // and personal orgs (see use-settings-nav-items.ts).
const personalLlmPaths = new Set([
"/settings",
"/settings/condenser",
@@ -206,9 +209,9 @@ describe("UserContextMenu", () => {
item.to !== "/settings/org-members" &&
item.to !== "/settings/org" &&
item.to !== "/settings/billing" &&
+ item.to !== "/settings/admin-dashboard" &&
!item.to.startsWith("/settings/org-defaults") &&
- !personalLlmPaths.has(item.to) &&
- true,
+ !personalLlmPaths.has(item.to),
);
await waitFor(() => {
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 4408fc5a17..9826fa76e8 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -254,6 +254,7 @@
"integrity": "sha512-H3mcG6ZDLTlYfaSNi0iOKkigqMFvkTKlGUYlD8GW7nNOYRrevuA46iTypPyv+06V3fEmvvazfntkBU34L0azAw==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@babel/code-frame": "^7.28.6",
"@babel/generator": "^7.28.6",
@@ -793,6 +794,7 @@
}
],
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=18"
},
@@ -833,6 +835,7 @@
}
],
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=18"
}
@@ -2482,6 +2485,7 @@
"resolved": "https://registry.npmjs.org/@heroui/system/-/system-2.4.26.tgz",
"integrity": "sha512-XqcsMmygWKcJYaviexO+FnZQBt2bd8z1vKIegRPsOmZytJXO/xJavbcwcuKP8A2Csk7fwYQANVx8qtN/r/wFOg==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"@heroui/react-utils": "2.1.14",
"@heroui/system-rsc": "2.3.22",
@@ -2565,6 +2569,7 @@
"resolved": "https://registry.npmjs.org/@heroui/theme/-/theme-2.4.26.tgz",
"integrity": "sha512-TYatChq7YyGDcPJytgOMqQwK72qWYb+vIa7mLmX3Cu9+JzFs2VSHu2QqzdhnOHoK0uJr8giDMy0gvJEDuu31vw==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"@heroui/shared-utils": "2.1.12",
"color": "^4.2.3",
@@ -3346,6 +3351,7 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",
"integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",
"license": "Apache-2.0",
+ "peer": true,
"engines": {
"node": ">=8.0.0"
}
@@ -4492,6 +4498,7 @@
"resolved": "https://registry.npmjs.org/@react-router/serve/-/serve-7.17.0.tgz",
"integrity": "sha512-cjVz/HiZbkZe4urdImO6V+KFYDIGJk59DJXGnJ5XeDoltRi+buba0K6oTHIh0G0uoYJMm3gKqHKSiCN/a0dhJw==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"@mjackson/node-fetch-server": "^0.2.0",
"@react-router/express": "7.17.0",
@@ -5909,6 +5916,7 @@
"integrity": "sha512-8QqtOQT5ACVlmsvKOJNEaWmRPmcojMOzCz4Hs2BGG/toAp/K38LcsMRyLp349glq5AzJbCEeimEoxaX6v/fLrA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@babel/core": "^7.21.3",
"@svgr/babel-preset": "8.1.0",
@@ -6392,6 +6400,7 @@
"integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@babel/code-frame": "^7.10.4",
"@babel/runtime": "^7.12.5",
@@ -6587,6 +6596,7 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@@ -6597,6 +6607,7 @@
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"dev": true,
"license": "MIT",
+ "peer": true,
"peerDependencies": {
"@types/react": "^19.2.0"
}
@@ -6637,6 +6648,7 @@
"integrity": "sha512-94EQTWZ40mzBc42ATNIBimBEDltSJ9RQHCC8vc/PDbxi4k8dVwUAv4o98dk50M1zB+JGFxp43FP7f8+FP8R6Sw==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@eslint-community/regexpp": "^4.10.0",
"@typescript-eslint/scope-manager": "7.18.0",
@@ -6694,6 +6706,7 @@
"integrity": "sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==",
"dev": true,
"license": "BSD-2-Clause",
+ "peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "7.18.0",
"@typescript-eslint/types": "7.18.0",
@@ -7079,6 +7092,7 @@
"integrity": "sha512-lt3kovsyHwYe00wq4D1ti0Z974fWj4NLp6siqiyEufUpyFwK9Yhi7rBhac9JL5aA0zoMrJqc4vYPZRUnI7l7nw==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@bcoe/v8-coverage": "^1.0.2",
"@vitest/utils": "4.1.8",
@@ -7274,6 +7288,7 @@
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"dev": true,
"license": "MIT",
+ "peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -7827,6 +7842,7 @@
}
],
"license": "MIT",
+ "peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.9.0",
"caniuse-lite": "^1.0.30001759",
@@ -8540,7 +8556,8 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
- "license": "MIT"
+ "license": "MIT",
+ "peer": true
},
"node_modules/damerau-levenshtein": {
"version": "1.0.8",
@@ -9246,6 +9263,7 @@
"deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.6.1",
@@ -9369,6 +9387,7 @@
"integrity": "sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==",
"dev": true,
"license": "MIT",
+ "peer": true,
"bin": {
"eslint-config-prettier": "bin/cli.js"
},
@@ -9448,6 +9467,7 @@
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@rtsao/scc": "^1.1.0",
"array-includes": "^3.1.9",
@@ -9538,6 +9558,7 @@
"integrity": "sha512-scB3nz4WmG75pV8+3eRUQOHZlNSUhFNq37xnpgRkCCELU3XMvXAxLk1eqWWyE22Ki4Q01Fnsw9BA3cJHDPgn2Q==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"aria-query": "^5.3.2",
"array-includes": "^3.1.8",
@@ -9632,6 +9653,7 @@
"integrity": "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"array-includes": "^3.1.8",
"array.prototype.findlast": "^1.2.5",
@@ -9665,6 +9687,7 @@
"integrity": "sha512-QzliNJq4GinDBcD8gPB5v0wh6g8q3SUi6EFF0x8N/BL9PoVs0atuGc47ozMRyOWAKdwaZ5OnbOEa3WR+dSGKuQ==",
"dev": true,
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=10"
},
@@ -9932,6 +9955,7 @@
"resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz",
"integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
@@ -10259,6 +10283,7 @@
"resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.38.0.tgz",
"integrity": "sha512-rFYkY/pigbcswl1XQSb7q424kSTQ8q6eAC+YUsSKooHQYuLdzdHjrt6uxUC+PRAO++q5IS7+TamgIw1AphxR+g==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"motion-dom": "^12.38.0",
"motion-utils": "^12.36.0",
@@ -10929,6 +10954,7 @@
}
],
"license": "MIT",
+ "peer": true,
"dependencies": {
"@babel/runtime": "^7.29.2"
},
@@ -11696,6 +11722,7 @@
"integrity": "sha512-mjzqwWRD9Y1J1KUi7W97Gja1bwOOM5Ug0EZ6UDK3xS7j7mndrkwozHtSblfomlzyB4NepioNt+B2sOSzczVgtQ==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@acemir/cssom": "^0.9.28",
"@asamuzakjp/dom-selector": "^6.7.6",
@@ -13406,6 +13433,7 @@
"resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz",
"integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"dompurify": "3.2.7",
"marked": "14.0.0"
@@ -13500,6 +13528,7 @@
"dev": true,
"hasInstallScript": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@inquirer/confirm": "^5.0.0",
"@mswjs/interceptors": "^0.40.0",
@@ -14296,6 +14325,7 @@
"integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==",
"dev": true,
"license": "MIT",
+ "peer": true,
"bin": {
"prettier": "bin/prettier.cjs"
},
@@ -14528,6 +14558,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.4.tgz",
"integrity": "sha512-9nfp2hYpCwOjAN+8TZFGhtWEwgvWHXqESH8qT89AT/lWklpLON22Lc8pEtnpsZz7VmawabSU0gCjnj8aC0euHQ==",
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -14652,6 +14683,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.4.tgz",
"integrity": "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@@ -14766,6 +14798,7 @@
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.17.0.tgz",
"integrity": "sha512-FDELK7rTMlCHO5+reyXsPlmfr7N1F91lPHsWYfMEGQm/KQ+F4JFM8jGoeQDmDvdTs93Fw9aSilH+uKRb4/jXvQ==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"cookie": "^1.0.1",
"set-cookie-parser": "^2.6.0"
@@ -15177,6 +15210,7 @@
"version": "4.59.0",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz",
"integrity": "sha512-2oMpl67a3zCH9H79LeMcbDhXW/UmWG/y2zuqnF2jQq5uq9TbM9TVyXvA4+t+ne2IIkBdrLpAaRQAvo7YI/Yyeg==",
+ "peer": true,
"dependencies": {
"@types/estree": "1.0.8"
},
@@ -16148,6 +16182,7 @@
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.4.0.tgz",
"integrity": "sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g==",
"license": "MIT",
+ "peer": true,
"funding": {
"type": "github",
"url": "https://github.com/sponsors/dcastil"
@@ -16276,6 +16311,7 @@
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
+ "peer": true,
"engines": {
"node": ">=12"
},
@@ -16579,6 +16615,7 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"devOptional": true,
"license": "Apache-2.0",
+ "peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -16885,6 +16922,7 @@
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz",
"integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==",
+ "peer": true,
"dependencies": {
"esbuild": "^0.27.0",
"fdir": "^6.5.0",
@@ -17049,6 +17087,7 @@
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
+ "peer": true,
"engines": {
"node": ">=12"
},
@@ -17062,6 +17101,7 @@
"integrity": "sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@vitest/expect": "4.1.8",
"@vitest/mocker": "4.1.8",
diff --git a/frontend/src/api/organization-service/organization-service.api.ts b/frontend/src/api/organization-service/organization-service.api.ts
index 7c95b9703b..15d90dfbdc 100644
--- a/frontend/src/api/organization-service/organization-service.api.ts
+++ b/frontend/src/api/organization-service/organization-service.api.ts
@@ -250,4 +250,193 @@ export const organizationService = {
}) => {
await openHands.delete(`/api/organizations/${orgId}/git-claims/${claimId}`);
},
+
+ // Organization Conversation APIs
+ getConversationStats: async ({ orgId }: { orgId: string }) => {
+ const { data } = await openHands.get<OrgConversationStats>(
+ `/api/organizations/${orgId}/conversations/stats`,
+ );
+ return data;
+ },
+
+ getUsageStats: async ({
+ orgId,
+ days = 7,
+ }: {
+ orgId: string;
+ days?: number;
+ }) => {
+ const { data } = await openHands.get<OrgUsageStats>(
+ `/api/organizations/${orgId}/conversations/usage-stats`,
+ { params: { days } },
+ );
+ return data;
+ },
+
+ getConversations: async ({
+ orgId,
+ page = 1,
+ perPage = 20,
+ search,
+ sortBy = "updated_at",
+ sortOrder = "desc",
+ executionStatus,
+ sandboxStatus,
+ timeWindow,
+ includeSubConversations = false,
+ }: {
+ orgId: string;
+ page?: number;
+ perPage?: number;
+ search?: string;
+ sortBy?: string;
+ sortOrder?: string;
+ executionStatus?: string;
+ sandboxStatus?: string;
+ timeWindow?: string;
+ includeSubConversations?: boolean;
+ }) => {
+ const params = new URLSearchParams();
+ params.set("page", String(page));
+ params.set("per_page", String(perPage));
+ params.set("sort_by", sortBy);
+ params.set("sort_order", sortOrder);
+ if (search) params.set("search", search);
+ if (executionStatus) params.set("execution_status", executionStatus);
+ if (sandboxStatus) params.set("sandbox_status", sandboxStatus);
+ if (timeWindow) params.set("time_window", timeWindow);
+ if (includeSubConversations)
+ params.set("include_sub_conversations", "true");
+
+ const { data } = await openHands.get<OrgConversationPage>(
+ `/api/organizations/${orgId}/conversations?${params.toString()}`,
+ );
+ return data;
+ },
+
+ getConversation: async ({
+ orgId,
+ conversationId,
+ }: {
+ orgId: string;
+ conversationId: string;
+ }) => {
+ const { data } = await openHands.get<OrgConversationResponse>(
+ `/api/organizations/${orgId}/conversations/${conversationId}`,
+ );
+ return data;
+ },
+
+ stopConversation: async ({
+ orgId,
+ conversationId,
+ }: {
+ orgId: string;
+ conversationId: string;
+ }) => {
+ const { data } = await openHands.post<{
+ success: boolean;
+ message: string;
+ conversation_id: string;
+ sandbox_id?: string;
+ }>(`/api/organizations/${orgId}/conversations/${conversationId}/stop`);
+ return data;
+ },
+
+ exportConversationsUrl: ({
+ orgId,
+ search,
+ sortBy = "updated_at",
+ sortOrder = "desc",
+ executionStatus,
+ sandboxStatus,
+ timeWindow,
+ }: {
+ orgId: string;
+ search?: string;
+ sortBy?: string;
+ sortOrder?: string;
+ executionStatus?: string;
+ sandboxStatus?: string;
+ timeWindow?: string;
+ }) => {
+ const params = new URLSearchParams();
+ params.set("sort_by", sortBy);
+ params.set("sort_order", sortOrder);
+ if (search) params.set("search", search);
+ if (executionStatus) params.set("execution_status", executionStatus);
+ if (sandboxStatus) params.set("sandbox_status", sandboxStatus);
+ if (timeWindow) params.set("time_window", timeWindow);
+ return `/api/organizations/${orgId}/conversations/export?${params.toString()}`;
+ },
};
+
+// Types for org conversation APIs
+interface OrgConversationStats {
+ active_conversations: number;
+ running_runtimes: number;
+ completed_24h: number;
+ completed_7d: number;
+ completed_30d: number;
+ total_cost: number;
+ total_prompt_tokens: number;
+ total_completion_tokens: number;
+ total_tokens: number;
+}
+
+interface DailyUsageData {
+ date: string;
+ tokens: number;
+ conversations: number;
+}
+
+interface TeamUsageData {
+ user_id: string;
+ user_email: string | null;
+ user_name: string | null;
+ conversation_count: number;
+ total_tokens: number;
+ percentage: number;
+}
+
+interface OrgUsageStats {
+ active_users: number;
+ agent_runs: number;
+ total_tokens: number;
+ estimated_spend: number;
+ daily_usage: DailyUsageData[];
+ team_usage: TeamUsageData[];
+}
+
+interface OrgConversationResponse {
+ id: string;
+ title: string;
+ llm_model: string | null;
+ agent_kind: string;
+ user_id: string;
+ user_email: string | null;
+ created_at: string;
+ updated_at: string;
+ sandbox_id: string | null;
+ sandbox_status: string | null;
+ runtime_url: string | null;
+ execution_status: string | null;
+ selected_repository: string | null;
+ selected_branch: string | null;
+ trigger: string | null;
+ tags: Record<string, string>;
+ accumulated_cost: number;
+ prompt_tokens: number;
+ completion_tokens: number;
+ total_tokens: number;
+ cache_read_tokens: number;
+ cache_write_tokens: number;
+}
+
+interface OrgConversationPage {
+ items: OrgConversationResponse[];
+ total_items: number;
+ page: number;
+ per_page: number;
+ total_pages: number;
+}
diff --git a/frontend/src/components/features/admin-dashboard/admin-dashboard.tsx b/frontend/src/components/features/admin-dashboard/admin-dashboard.tsx
new file mode 100644
index 0000000000..3d8c64f686
--- /dev/null
+++ b/frontend/src/components/features/admin-dashboard/admin-dashboard.tsx
@@ -0,0 +1,1155 @@
+/* eslint-disable i18next/no-literal-string */
+import React, { useMemo, useState } from "react";
+import { useSearchParams } from "react-router";
+import toast from "react-hot-toast";
+import { useSelectedOrganizationId } from "#/context/use-selected-organization";
+import { useOrganizations } from "#/hooks/query/use-organizations";
+import { useOrgConversationStats } from "#/hooks/query/use-org-conversation-stats";
+import { useOrgConversations } from "#/hooks/query/use-org-conversations";
+import { useOrgUsageStats } from "#/hooks/query/use-org-usage-stats";
+import { useStopConversation } from "#/hooks/mutation/use-stop-conversation";
+import { ConfirmationModal } from "#/components/shared/modals/confirmation-modal";
+import { organizationService } from "#/api/organization-service/organization-service.api";
+
+// Conversation statuses from which the user can no longer stop a running
+// agent. Mirrors the terminal-status set used by OrgConversationService.
+const TERMINAL_EXECUTION_STATUSES = new Set([
+ "finished",
+ "error",
+ "stuck",
+ "deleting",
+]);
+
+const isStoppable = (status: string | null | undefined) =>
+ !TERMINAL_EXECUTION_STATUSES.has((status ?? "").toLowerCase());
+
+// Icons as inline SVGs for simplicity
+function SearchIcon() {
+ return (
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <circle cx="11" cy="11" r="8" />
+ <path d="m21 21-4.35-4.35" />
+ </svg>
+ );
+}
+
+function ExportIcon() {
+ return (
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
+ <polyline points="7,10 12,15 17,10" />
+ <line x1="12" y1="15" x2="12" y2="3" />
+ </svg>
+ );
+}
+
+function CopyIcon() {
+ return (
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
+ </svg>
+ );
+}
+
+function ExternalLinkIcon() {
+ return (
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
+ <polyline points="15,3 21,3 21,9" />
+ <line x1="10" y1="14" x2="21" y2="3" />
+ </svg>
+ );
+}
+
+function StopIcon() {
+ return (
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <circle cx="12" cy="12" r="10" />
+ <rect x="9" y="9" width="6" height="6" />
+ </svg>
+ );
+}
+
+function ChevronLeftIcon() {
+ return (
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <polyline points="15,18 9,12 15,6" />
+ </svg>
+ );
+}
+
+function ChevronRightIcon() {
+ return (
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <polyline points="9,18 15,12 9,6" />
+ </svg>
+ );
+}
+
+function ActivityIcon() {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <polyline points="22,12 18,12 15,21 9,3 6,12 2,12" />
+ </svg>
+ );
+}
+
+function ServerIcon() {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <rect x="2" y="2" width="20" height="8" rx="2" ry="2" />
+ <rect x="2" y="14" width="20" height="8" rx="2" ry="2" />
+ <line x1="6" y1="6" x2="6.01" y2="6" />
+ <line x1="6" y1="18" x2="6.01" y2="18" />
+ </svg>
+ );
+}
+
+function CheckCircleIcon() {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
+ <polyline points="22,4 12,14.01 9,11.01" />
+ </svg>
+ );
+}
+
+function DollarIcon() {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <line x1="12" y1="1" x2="12" y2="23" />
+ <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
+ </svg>
+ );
+}
+
+// Status badge component
+function StatusBadge({ status }: { status: string | null }) {
+ const getStatusStyle = () => {
+ switch (status) {
+ case "running":
+ return "bg-blue-500/10 text-blue-400 border-blue-500/30";
+ case "idle":
+ case "paused":
+ return "bg-yellow-500/10 text-yellow-400 border-yellow-500/30";
+ case "finished":
+ return "bg-green-500/10 text-green-400 border-green-500/30";
+ case "error":
+ case "stuck":
+ return "bg-red-500/10 text-red-400 border-red-500/30";
+ default:
+ return "bg-gray-500/10 text-gray-400 border-gray-500/30";
+ }
+ };
+
+ return (
+ <span
+ className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${getStatusStyle()}`}
+ >
+ {status || "unknown"}
+ </span>
+ );
+}
+
+// Runtime status badge
+function RuntimeBadge({ status }: { status: string | null }) {
+ const getStatusStyle = () => {
+ switch (status) {
+ case "RUNNING":
+ return "bg-blue-500/10 text-blue-400 border-blue-500/30";
+ case "STARTING":
+ return "bg-yellow-500/10 text-yellow-400 border-yellow-500/30";
+ case "ERROR":
+ case "MISSING":
+ return "bg-red-500/10 text-red-400 border-red-500/30";
+ case "PAUSED":
+ return "bg-gray-500/10 text-gray-400 border-gray-500/30";
+ default:
+ return "bg-gray-500/10 text-gray-400 border-gray-500/30";
+ }
+ };
+
+ return (
+ <span
+ className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${getStatusStyle()}`}
+ >
+ {status || "N/A"}
+ </span>
+ );
+}
+
+// KPI Card component
+function KPICard({
+ label,
+ value,
+ subtext,
+ icon,
+}: {
+ label: string;
+ value: string | number;
+ subtext?: string;
+ icon: React.ReactNode;
+}) {
+ return (
+ <div className="bg-[#1E1E1E] border border-[#262626] rounded-lg p-4">
+ <div className="flex items-center justify-between mb-3">
+ <span className="text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">
+ {label}
+ </span>
+ <span className="text-[#8C8C8C]">{icon}</span>
+ </div>
+ <div className="text-white text-2xl font-bold mb-1">{value}</div>
+ {subtext && <div className="text-[#8C8C8C] text-xs">{subtext}</div>}
+ </div>
+ );
+}
+
+// Format tokens
+const formatTokens = (tokens: number) => {
+ if (tokens >= 1000000) return `${(tokens / 1000000).toFixed(1)}M`;
+ if (tokens >= 1000) return `${(tokens / 1000).toFixed(1)}k`;
+ return tokens.toString();
+};
+
+// Format cost
+const formatCost = (cost: number) => {
+ if (cost >= 1000) return `$${(cost / 1000).toFixed(1)}k`;
+ return `$${cost.toFixed(2)}`;
+};
+
+// Format date
+const formatDate = (dateStr: string) => {
+ const date = new Date(dateStr);
+ return date.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ });
+};
+
+// Copy to clipboard
+const copyToClipboard = (text: string) => {
+ navigator.clipboard.writeText(text);
+};
+
+// Get number of days from time window string
+const getDaysFromTimeWindow = (timeWindow: string): number => {
+ if (timeWindow === "90d") return 90;
+ if (timeWindow === "30d") return 30;
+ return 7;
+};
+
+export function AdminDashboard() {
+ const { organizationId } = useSelectedOrganizationId();
+ const { data: orgData } = useOrganizations();
+ const [activeTab, setActiveTab] = useState<"conversations" | "usage">(
+ "conversations",
+ );
+ const [searchParams, setSearchParams] = useSearchParams();
+
+ // Use the currently selected org (from the org switcher) rather than
+ // deriving from the org list — avoids mismatches when the user belongs
+ // to multiple orgs and has different roles in each.
+ const orgId = organizationId ?? undefined;
+ const currentOrg = orgData?.organizations?.find(
+ (org) => org.id === organizationId,
+ );
+
+ // Filter state from URL params
+ const page = parseInt(searchParams.get("page") || "1", 10);
+ const perPage = parseInt(searchParams.get("per_page") || "20", 10);
+ const search = searchParams.get("search") || "";
+ const sortBy = searchParams.get("sort_by") || "updated_at";
+ const sortOrder = searchParams.get("sort_order") || "desc";
+ const executionStatus = searchParams.get("execution_status") || "";
+ const sandboxStatus = searchParams.get("sandbox_status") || "";
+ const timeWindow = searchParams.get("time_window") || "";
+
+ // Fetch stats
+ const { data: stats } = useOrgConversationStats();
+
+ // Fetch usage stats for Usage tab
+ const { data: usageStats } = useOrgUsageStats({
+ days: getDaysFromTimeWindow(timeWindow),
+ });
+
+ // Fetch conversations
+ const { data: conversationsData, isLoading: conversationsLoading } =
+ useOrgConversations({
+ page,
+ perPage,
+ search,
+ sortBy,
+ sortOrder,
+ executionStatus,
+ sandboxStatus,
+ timeWindow,
+ });
+
+ const [stoppingIds, setStoppingIds] = useState<Set<string>>(new Set());
+ const [pendingStop, setPendingStop] = useState<{
+ id: string;
+ title: string | null;
+ } | null>(null);
+ const stopConversation = useStopConversation();
+
+ const handleStop = (conversation: { id: string; title: string | null }) => {
+ setPendingStop(conversation);
+ };
+
+ const confirmStop = () => {
+ if (!pendingStop) return;
+ const conversation = pendingStop;
+ setPendingStop(null);
+ setStoppingIds((prev) => {
+ const next = new Set(prev);
+ next.add(conversation.id);
+ return next;
+ });
+ const toastId = toast.loading("Stopping conversation…");
+ stopConversation.mutate(
+ { conversationId: conversation.id },
+ {
+ onSettled: () => {
+ setStoppingIds((prev) => {
+ if (!prev.has(conversation.id)) return prev;
+ const next = new Set(prev);
+ next.delete(conversation.id);
+ return next;
+ });
+ toast.dismiss(toastId);
+ },
+ },
+ );
+ };
+
+ const cancelStop = () => {
+ setPendingStop(null);
+ };
+
+ const updateFilter = (key: string, value: string | string[] | null) => {
+ const newParams = new URLSearchParams(searchParams);
+ if (value === null || value === "") {
+ newParams.delete(key);
+ } else if (Array.isArray(value)) {
+ newParams.delete(key);
+ value.forEach((v) => newParams.append(key, v));
+ } else {
+ newParams.set(key, value);
+ }
+ newParams.set("page", "1"); // Reset to first page on filter change
+ setSearchParams(newParams);
+ };
+
+ const handlePageChange = (newPage: number) => {
+ const newParams = new URLSearchParams(searchParams);
+ newParams.set("page", String(newPage));
+ setSearchParams(newParams);
+ };
+
+ const totalPages = conversationsData?.total_pages || 1;
+ const totalItems = conversationsData?.total_items || 0;
+ const pendingStopLabel = pendingStop?.title?.trim();
+ const stopConfirmationText = pendingStopLabel
+ ? `Stop "${pendingStopLabel}"? This will cancel any in-progress agent run.`
+ : "Stop this conversation? This will cancel any in-progress agent run.";
+
+ const exportUrl = useMemo(() => {
+ if (!orgId) return "#";
+ return organizationService.exportConversationsUrl({
+ orgId,
+ search: search || undefined,
+ sortBy,
+ sortOrder,
+ executionStatus: executionStatus.length ? executionStatus : undefined,
+ sandboxStatus: sandboxStatus.length ? sandboxStatus : undefined,
+ timeWindow: timeWindow || undefined,
+ });
+ }, [
+ orgId,
+ search,
+ sortBy,
+ sortOrder,
+ executionStatus,
+ sandboxStatus,
+ timeWindow,
+ ]);
+
+ if (!orgId) {
+ return (
+ <div className="p-8 text-center text-[#8C8C8C]">
+ Please select an organization to view the admin dashboard.
+ </div>
+ );
+ }
+
+ return (
+ <div className="min-h-screen bg-[#0B0B0B] text-white flex flex-col">
+ {/* Top Header with Tabs */}
+ <header className="border-b border-white/10 px-6 py-4">
+ <div className="flex items-center justify-between mb-4">
+ <div>
+ <h1 className="text-white font-bold text-lg">Admin dashboard</h1>
+ <p className="text-[#888888] text-sm mt-1">
+ {currentOrg?.name || "your organization"}
+ </p>
+ </div>
+ </div>
+
+ {/* Tabs */}
+ <div className="flex gap-1 border-b border-white/10 -mb-4">
+ <button
+ type="button"
+ onClick={() => setActiveTab("usage")}
+ className={`px-4 py-2 text-sm font-medium transition-colors border-b-2 ${
+ activeTab === "usage"
+ ? "border-white text-white"
+ : "border-transparent text-[#888888] hover:text-white"
+ }`}
+ >
+ Usage
+ </button>
+ <button
+ type="button"
+ onClick={() => setActiveTab("conversations")}
+ className={`px-4 py-2 text-sm font-medium transition-colors border-b-2 ${
+ activeTab === "conversations"
+ ? "border-white text-white"
+ : "border-transparent text-[#888888] hover:text-white"
+ }`}
+ >
+ Conversations
+ </button>
+ </div>
+ </header>
+
+ {/* Main Content */}
+ <main className="flex-1 overflow-auto">
+ {activeTab === "usage" ? (
+ <>
+ {/* Usage Page Header */}
+ <div className="p-8 border-b border-white/10">
+ <div className="flex items-start justify-between mb-2">
+ <div>
+ <p className="text-[#888888] text-sm">
+ At-a-glance OpenHands usage for{" "}
+ {currentOrg?.name || "your organization"}.
+ </p>
+ </div>
+ <button
+ type="button"
+ className="flex items-center gap-2 px-4 py-2 rounded-full border border-white/20 text-sm text-[#888888] hover:text-white hover:border-white/40 transition-colors"
+ >
+ Last 7 days
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <path d="M6 9l6 6 6-6" />
+ </svg>
+ </button>
+ </div>
+ </div>
+
+ {/* Usage Content */}
+ <div className="p-8">
+ {/* Top Metrics Row - 3 cards */}
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
+ {/* Active Users */}
+ <div className="bg-[#1A1A1A] p-6 rounded-xl border border-white/5">
+ <div className="flex items-center justify-between mb-4">
+ <span className="text-[#888888] text-xs font-medium uppercase tracking-wide">
+ Active Users
+ </span>
+ <div className="w-8 h-8 rounded-lg bg-white/10 flex items-center justify-center">
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
+ <circle cx="9" cy="7" r="4" />
+ <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
+ <path d="M16 3.13a4 4 0 0 1 0 7.75" />
+ </svg>
+ </div>
+ </div>
+ <div className="text-white text-3xl font-bold tracking-tight mb-2">
+ {usageStats?.active_users ?? 0}
+ </div>
+ <div className="text-[#888888] text-sm">
+ users in last 7 days
+ </div>
+ </div>
+
+ {/* Agent Runs */}
+ <div className="bg-[#1A1A1A] p-6 rounded-xl border border-white/5">
+ <div className="flex items-center justify-between mb-4">
+ <span className="text-[#888888] text-xs font-medium uppercase tracking-wide">
+ Agent Runs
+ </span>
+ <div className="w-8 h-8 rounded-lg bg-white/10 flex items-center justify-center">
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <polyline points="22,12 18,12 15,21 9,3 6,12 2,12" />
+ </svg>
+ </div>
+ </div>
+ <div className="text-white text-3xl font-bold tracking-tight mb-2">
+ {usageStats?.agent_runs ?? 0}
+ </div>
+ <div className="text-[#888888] text-sm">
+ {(() => {
+ const days = getDaysFromTimeWindow(timeWindow);
+ if (usageStats?.agent_runs && usageStats.agent_runs > 0) {
+ return `${Math.round(usageStats.agent_runs / days)} daily average`;
+ }
+ return `No runs in ${days} days`;
+ })()}
+ </div>
+ </div>
+
+ {/* Token Usage */}
+ <div className="bg-[#1A1A1A] p-6 rounded-xl border border-white/5">
+ <div className="flex items-center justify-between mb-4">
+ <span className="text-[#888888] text-xs font-medium uppercase tracking-wide">
+ Token Usage
+ </span>
+ <div className="w-8 h-8 rounded-lg bg-white/10 flex items-center justify-center">
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <circle cx="12" cy="12" r="10" />
+ <path d="M12 6v6l4 2" />
+ </svg>
+ </div>
+ </div>
+ <div className="text-white text-3xl font-bold tracking-tight mb-2">
+ {formatTokens(usageStats?.total_tokens ?? 0)}
+ </div>
+ <div className="text-[#888888] text-sm">
+ ${(usageStats?.estimated_spend ?? 0).toFixed(2)} estimated
+ spend
+ </div>
+ </div>
+ </div>
+
+ {/* Bottom Row - Chart and Team Usage */}
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
+ {/* Daily Usage Chart */}
+ <div className="lg:col-span-2 bg-[#1A1A1A] p-6 rounded-xl border border-white/5">
+ <div className="mb-6">
+ <h2 className="text-white font-medium text-lg">
+ Daily usage
+ </h2>
+ <p className="text-[#888888] text-sm">
+ Tokens and conversations by day
+ </p>
+ </div>
+
+ {/* Simple Bar Chart */}
+ <div className="h-48 flex items-end justify-between gap-4 px-2">
+ {(usageStats?.daily_usage ?? []).map((day) => {
+ // Find max tokens for scaling
+ const maxTokens = Math.max(
+ ...(usageStats?.daily_usage?.map((d) => d.tokens) ?? [
+ 1,
+ ]),
+ 1,
+ );
+ const tokenHeight =
+ day.tokens > 0 ? (day.tokens / maxTokens) * 100 : 5;
+ const convoHeight =
+ day.conversations > 0
+ ? Math.min(
+ (day.conversations /
+ Math.max(
+ ...(usageStats?.daily_usage?.map(
+ (d) => d.conversations,
+ ) ?? [1]),
+ 1,
+ )) *
+ 100,
+ 80,
+ )
+ : 5;
+
+ // Get day name from date
+ const date = new Date(day.date);
+ const dayName = date.toLocaleDateString("en-US", {
+ weekday: "short",
+ });
+
+ return (
+ <div
+ key={day.date}
+ className="flex-1 flex flex-col items-center gap-2"
+ >
+ <div className="w-full flex items-end justify-center gap-1 h-36">
+ <div
+ className="w-4 bg-white rounded-sm transition-all"
+ style={{ height: `${tokenHeight}%` }}
+ title={`${day.tokens.toLocaleString()} tokens`}
+ />
+ <div
+ className="w-4 bg-zinc-600 rounded-sm transition-all"
+ style={{ height: `${convoHeight}%` }}
+ title={`${day.conversations} conversations`}
+ />
+ </div>
+ <span className="text-[#888888] text-xs">
+ {dayName}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+
+ {/* Legend */}
+ <div className="flex items-center gap-6 mt-6 pt-4 border-t border-white/10">
+ <div className="flex items-center gap-2">
+ <div className="w-3 h-3 rounded-sm bg-white" />
+ <span className="text-[#888888] text-sm">Tokens</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-3 h-3 rounded-sm bg-zinc-600" />
+ <span className="text-[#888888] text-sm">
+ Conversations
+ </span>
+ </div>
+ </div>
+ </div>
+
+ {/* Usage by Team (User) */}
+ <div className="bg-[#1A1A1A] p-6 rounded-xl border border-white/5">
+ <div className="mb-6">
+ <h2 className="text-white font-medium text-lg">
+ Usage by user
+ </h2>
+ <p className="text-[#888888] text-sm">
+ Share of total runs
+ </p>
+ </div>
+
+ <div className="space-y-5">
+ {(usageStats?.team_usage ?? []).slice(0, 6).map((user) => (
+ <div key={user.user_id}>
+ <div className="flex items-center justify-between mb-2">
+ <span
+ className="text-white text-sm truncate max-w-[120px]"
+ title={
+ user.user_email || user.user_name || user.user_id
+ }
+ >
+ {user.user_name || user.user_email || "Unknown"}
+ </span>
+ <span className="text-[#888888] text-sm">
+ {user.percentage}%
+ </span>
+ </div>
+ <div className="w-full h-1.5 bg-zinc-800 rounded-full overflow-hidden">
+ <div
+ className="h-full bg-white rounded-full transition-all"
+ style={{ width: `${user.percentage}%` }}
+ />
+ </div>
+ </div>
+ ))}
+ {(!usageStats?.team_usage ||
+ usageStats.team_usage.length === 0) && (
+ <div className="text-[#888888] text-sm text-center py-4">
+ No usage data available
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ </>
+ ) : (
+ <>
+ {/* KPI Cards */}
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6 px-8 pt-6">
+ <KPICard
+ label="Active Conversations"
+ value={stats?.active_conversations ?? "-"}
+ subtext="In-flight agent work"
+ icon={<ActivityIcon />}
+ />
+ <KPICard
+ label="Running Runtimes"
+ value={stats?.running_runtimes ?? "-"}
+ subtext="Connected execution cells"
+ icon={<ServerIcon />}
+ />
+ <KPICard
+ label="Completed (24H)"
+ value={stats?.completed_24h ?? "-"}
+ subtext="Finished in last day"
+ icon={<CheckCircleIcon />}
+ />
+ <KPICard
+ label="Estimated Spend"
+ value={formatCost(stats?.total_cost ?? 0)}
+ subtext={`~${formatTokens(stats?.total_tokens ?? 0)} tokens in dataset`}
+ icon={<DollarIcon />}
+ />
+ </div>
+
+ {/* Filter Bar */}
+
+ <div className="bg-[#161616] border border-[#262626] rounded-lg p-4 mb-4">
+ <div className="flex items-center justify-between mb-4">
+ <span className="text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">
+ Filters
+ </span>
+ <a
+ href={exportUrl}
+ className="flex items-center gap-2 px-3 py-1.5 bg-[#1E1E1E] border border-[#262626] rounded text-sm text-[#8C8C8C] hover:text-white hover:border-[#404040] transition-colors"
+ >
+ <ExportIcon />
+ Export CSV
+ </a>
+ </div>
+
+ <div className="flex flex-wrap gap-3">
+ {/* Search */}
+ <div className="relative flex-1 min-w-[200px]">
+ <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-[#8C8C8C]">
+ <SearchIcon />
+ </div>
+ <input
+ type="text"
+ placeholder="Name, creator, email..."
+ value={search}
+ onChange={(e) => updateFilter("search", e.target.value)}
+ className="w-full pl-10 pr-4 py-2 bg-[#0D0D0D] border border-[#262626] rounded text-white text-sm placeholder-[#6B6B6B] focus:outline-none focus:border-[#404040]"
+ />
+ </div>
+
+ {/* Sort By */}
+ <select
+ value={sortBy}
+ onChange={(e) => updateFilter("sort_by", e.target.value)}
+ className="px-3 py-2 bg-[#0D0D0D] border border-[#262626] rounded text-sm text-white focus:outline-none focus:border-[#404040] appearance-none cursor-pointer"
+ >
+ <option value="updated_at">Last updated</option>
+ <option value="created_at">Created</option>
+ <option value="title">Title</option>
+ <option value="llm_model">Model</option>
+ <option value="accumulated_cost">Cost</option>
+ </select>
+
+ {/* Order */}
+ <select
+ value={sortOrder}
+ onChange={(e) => updateFilter("sort_order", e.target.value)}
+ className="px-3 py-2 bg-[#0D0D0D] border border-[#262626] rounded text-sm text-white focus:outline-none focus:border-[#404040] appearance-none cursor-pointer"
+ >
+ <option value="desc">Descending</option>
+ <option value="asc">Ascending</option>
+ </select>
+
+ {/* Conversation Status */}
+ <select
+ value={executionStatus}
+ onChange={(e) =>
+ updateFilter("execution_status", e.target.value || null)
+ }
+ className="px-3 py-2 bg-[#0D0D0D] border border-[#262626] rounded text-sm text-white focus:outline-none focus:border-[#404040] appearance-none cursor-pointer"
+ >
+ <option value="">Conversation status: All</option>
+ <option value="running">Running</option>
+ <option value="idle">Idle</option>
+ <option value="paused">Paused</option>
+ <option value="finished">Finished</option>
+ <option value="error">Error</option>
+ <option value="stuck">Stuck</option>
+ </select>
+
+ {/* Runtime Status */}
+ <select
+ value={sandboxStatus}
+ onChange={(e) =>
+ updateFilter("sandbox_status", e.target.value || null)
+ }
+ className="px-3 py-2 bg-[#0D0D0D] border border-[#262626] rounded text-sm text-white focus:outline-none focus:border-[#404040] appearance-none cursor-pointer"
+ >
+ <option value="">Runtime status: All</option>
+ <option value="RUNNING">Running</option>
+ <option value="STARTING">Starting</option>
+ <option value="PAUSED">Paused</option>
+ <option value="ERROR">Error</option>
+ <option value="MISSING">Missing</option>
+ </select>
+
+ {/* Time Window */}
+ <select
+ value={timeWindow}
+ onChange={(e) =>
+ updateFilter("time_window", e.target.value || null)
+ }
+ className="px-3 py-2 bg-[#0D0D0D] border border-[#262626] rounded text-sm text-white focus:outline-none focus:border-[#404040] appearance-none cursor-pointer"
+ >
+ <option value="">All time</option>
+ <option value="7d">Last 7 days</option>
+ <option value="30d">Last 30 days</option>
+ <option value="90d">Last 90 days</option>
+ </select>
+ </div>
+ </div>
+
+ {/* Table */}
+ <div className="bg-[#161616] border border-[#262626] rounded-lg overflow-hidden">
+ <div className="overflow-x-auto">
+ <table className="w-full">
+ <thead>
+ <tr className="border-b border-[#262626]">
+ <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">
+ Conversation
+ </th>
+ <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">
+ Model
+ </th>
+ <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">
+ Created by
+ </th>
+ <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">
+ Status
+ </th>
+ <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">
+ Runtime
+ </th>
+ <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">
+ Runtime URL / GUID
+ </th>
+ <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">
+ Created / Updated
+ </th>
+ <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">
+ Tokens / Cost
+ </th>
+ <th className="px-4 py-3 text-left text-[#8C8C8C] text-xs font-medium uppercase tracking-wide">
+ Actions
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {conversationsLoading && (
+ <tr>
+ <td
+ colSpan={9}
+ className="px-4 py-8 text-center text-[#8C8C8C]"
+ >
+ Loading...
+ </td>
+ </tr>
+ )}
+ {!conversationsLoading &&
+ conversationsData?.items.length === 0 && (
+ <tr>
+ <td
+ colSpan={9}
+ className="px-4 py-8 text-center text-[#8C8C8C]"
+ >
+ No conversations found
+ </td>
+ </tr>
+ )}
+ {!conversationsLoading &&
+ conversationsData?.items.map((conversation, index) => (
+ <tr
+ key={conversation.id}
+ className={`border-b border-[#262626] hover:bg-[#1E1E1E]/50 transition-colors ${
+ index % 2 === 0 ? "" : "bg-[#0D0D0D]/30"
+ }`}
+ >
+ <td className="px-4 py-3">
+ <div className="font-medium text-white text-sm">
+ {conversation.title || "Untitled"}
+ </div>
+ </td>
+ <td className="px-4 py-3">
+ <span className="font-mono text-xs text-[#8C8C8C]">
+ {conversation.llm_model || "N/A"}
+ </span>
+ </td>
+ <td className="px-4 py-3">
+ <div className="text-sm">
+ <div className="text-white">
+ {conversation.user_email?.split("@")[0] ||
+ "Unknown"}
+ </div>
+ <div className="text-[#8C8C8C] text-xs">
+ {conversation.user_email || ""}
+ </div>
+ </div>
+ </td>
+ <td className="px-4 py-3">
+ <StatusBadge
+ status={conversation.execution_status}
+ />
+ </td>
+ <td className="px-4 py-3">
+ <RuntimeBadge
+ status={conversation.sandbox_status}
+ />
+ </td>
+ <td className="px-4 py-3">
+ {conversation.sandbox_id ? (
+ <div className="flex items-center gap-2">
+ <span className="font-mono text-xs text-[#8C8C8C] truncate max-w-[120px]">
+ {conversation.sandbox_id.slice(0, 12)}...
+ </span>
+ <button
+ type="button"
+ onClick={() =>
+ copyToClipboard(conversation.sandbox_id!)
+ }
+ className="text-[#6B6B6B] hover:text-white transition-colors"
+ title="Copy GUID"
+ >
+ <CopyIcon />
+ </button>
+ {conversation.runtime_url && (
+ <a
+ href={conversation.runtime_url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-[#6B6B6B] hover:text-white transition-colors"
+ title="Open in new tab"
+ >
+ <ExternalLinkIcon />
+ </a>
+ )}
+ </div>
+ ) : (
+ <span className="text-[#6B6B6B] text-xs">
+ N/A
+ </span>
+ )}
+ </td>
+ <td className="px-4 py-3">
+ <div className="text-xs">
+ <div className="text-[#8C8C8C] uppercase mb-0.5">
+ Created
+ </div>
+ <div className="text-white mb-1">
+ {formatDate(conversation.created_at)}
+ </div>
+ <div className="text-[#8C8C8C] uppercase mb-0.5">
+ Updated
+ </div>
+ <div className="text-white">
+ {formatDate(conversation.updated_at)}
+ </div>
+ </div>
+ </td>
+ <td className="px-4 py-3">
+ <div className="text-xs text-right">
+ <div className="text-white font-mono">
+ {formatTokens(conversation.total_tokens)}
+ </div>
+ <div className="text-white font-medium">
+ ${conversation.accumulated_cost.toFixed(2)}
+ </div>
+ </div>
+ </td>
+ <td className="px-4 py-3">
+ <div className="flex flex-col gap-1">
+ <button
+ type="button"
+ onClick={() => handleStop(conversation)}
+ disabled={
+ !isStoppable(conversation.execution_status) ||
+ stoppingIds.has(conversation.id)
+ }
+ className="flex items-center gap-1.5 px-2 py-1 text-xs text-[#8C8C8C] hover:text-white hover:bg-[#262626] rounded transition-colors disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-[#8C8C8C] disabled:cursor-not-allowed"
+ title={
+ isStoppable(conversation.execution_status)
+ ? "Stop conversation"
+ : "Conversation is not running"
+ }
+ aria-label="Stop conversation"
+ >
+ <StopIcon />
+ {stoppingIds.has(conversation.id)
+ ? "Stopping…"
+ : "Stop"}
+ </button>
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+
+ {/* Pagination Footer */}
+ <div className="flex items-center justify-between px-4 py-3 border-t border-[#262626]">
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => handlePageChange(page - 1)}
+ disabled={page <= 1}
+ className={`flex items-center gap-1 px-2 py-1 text-sm rounded transition-colors ${
+ page <= 1
+ ? "text-[#6B6B6B] cursor-not-allowed"
+ : "text-[#8C8C8C] hover:text-white hover:bg-[#262626]"
+ }`}
+ >
+ <ChevronLeftIcon />
+ Previous
+ </button>
+ <button
+ type="button"
+ onClick={() => handlePageChange(page + 1)}
+ disabled={page >= totalPages}
+ className={`flex items-center gap-1 px-2 py-1 text-sm rounded transition-colors ${
+ page >= totalPages
+ ? "text-[#6B6B6B] cursor-not-allowed"
+ : "text-[#8C8C8C] hover:text-white hover:bg-[#262626]"
+ }`}
+ >
+ Next
+ <ChevronRightIcon />
+ </button>
+ </div>
+
+ <div className="flex items-center gap-4">
+ <div className="flex items-center gap-2">
+ <span className="text-[#8C8C8C] text-sm">Per page</span>
+ <select
+ value={perPage}
+ onChange={(e) => {
+ const newParams = new URLSearchParams(searchParams);
+ newParams.set("per_page", e.target.value);
+ newParams.set("page", "1");
+ setSearchParams(newParams);
+ }}
+ className="px-2 py-1 bg-[#0D0D0D] border border-[#262626] rounded text-sm text-white focus:outline-none"
+ >
+ <option value="5">5</option>
+ <option value="10">10</option>
+ <option value="20">20</option>
+ <option value="50">50</option>
+ </select>
+ </div>
+ <span className="text-[#8C8C8C] text-sm">
+ Page {page} of {totalPages} · {totalItems} conversations
+ </span>
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+ </main>
+
+ {pendingStop && (
+ <ConfirmationModal
+ text={stopConfirmationText}
+ onConfirm={confirmStop}
+ onCancel={cancelStop}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/components/shared/buttons/admin-dashboard-button.tsx b/frontend/src/components/shared/buttons/admin-dashboard-button.tsx
new file mode 100644
index 0000000000..b8b9ca010d
--- /dev/null
+++ b/frontend/src/components/shared/buttons/admin-dashboard-button.tsx
@@ -0,0 +1,59 @@
+import React from "react";
+import { Link, useLocation } from "react-router";
+import { useConfig } from "#/hooks/query/use-config";
+import { useMe } from "#/hooks/query/use-me";
+import { useSelectedOrganizationId } from "#/context/use-selected-organization";
+import { cn } from "#/utils/utils";
+
+export function AdminDashboardButton() {
+ const location = useLocation();
+ const { data: config } = useConfig();
+ const { organizationId } = useSelectedOrganizationId();
+
+ const isSaas = config?.app_mode === "saas";
+
+ const { data: meData, isLoading } = useMe();
+
+ const isAdmin = meData?.role === "owner" || meData?.role === "admin";
+
+ // Don't render anything while loading (prevents flash of wrong state)
+ if (!isSaas || isLoading || !organizationId) {
+ return null;
+ }
+
+ if (!isAdmin) {
+ return null;
+ }
+
+ const isActive = location.pathname.startsWith("/settings/admin-dashboard");
+
+ return (
+ <Link
+ to="/settings/admin-dashboard"
+ className={cn(
+ "flex items-center justify-center w-[34px] h-[34px] rounded-lg transition-colors",
+ isActive
+ ? "bg-[#262626] text-white"
+ : "text-[#8C8C8C] hover:text-white hover:bg-[#1E1E1E]",
+ )}
+ title="Admin Dashboard"
+ aria-label="Admin Dashboard"
+ >
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <rect x="3" y="3" width="7" height="7" />
+ <rect x="14" y="3" width="7" height="7" />
+ <rect x="14" y="14" width="7" height="7" />
+ <rect x="3" y="14" width="7" height="7" />
+ </svg>
+ </Link>
+ );
+}
diff --git a/frontend/src/constants/settings-nav.tsx b/frontend/src/constants/settings-nav.tsx
index 938defa682..44ad6bc872 100644
--- a/frontend/src/constants/settings-nav.tsx
+++ b/frontend/src/constants/settings-nav.tsx
@@ -1,4 +1,4 @@
-import { FiUsers, FiBriefcase } from "react-icons/fi";
+import { FiUsers, FiBriefcase, FiBarChart2 } from "react-icons/fi";
import CreditCardIcon from "#/icons/credit-card.svg?react";
import KeyIcon from "#/icons/key.svg?react";
import LightbulbIcon from "#/icons/lightbulb.svg?react";
@@ -47,6 +47,12 @@ export const SAAS_NAV_ITEMS: SettingsNavItem[] = [
text: "SETTINGS$NAV_ORG_MEMBERS",
section: "org",
},
+ {
+ icon: <FiBarChart2 size={22} />,
+ to: "/settings/admin-dashboard",
+ text: "SETTINGS$NAV_ADMIN_DASHBOARD",
+ section: "org",
+ },
{
icon: <CircuitIcon width={22} height={22} />,
to: "/settings/org-defaults",
diff --git a/frontend/src/hooks/mutation/use-stop-conversation.ts b/frontend/src/hooks/mutation/use-stop-conversation.ts
new file mode 100644
index 0000000000..e7d9f4b9b4
--- /dev/null
+++ b/frontend/src/hooks/mutation/use-stop-conversation.ts
@@ -0,0 +1,29 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import toast from "react-hot-toast";
+import { organizationService } from "#/api/organization-service/organization-service.api";
+import { useSelectedOrganizationId } from "#/context/use-selected-organization";
+
+export const useStopConversation = () => {
+ const { organizationId } = useSelectedOrganizationId();
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({ conversationId }: { conversationId: string }) =>
+ organizationService.stopConversation({
+ orgId: organizationId!,
+ conversationId,
+ }),
+ onError: () => {
+ toast.error("Failed to stop conversation");
+ },
+ onSuccess: () => {
+ toast.success("Conversation stopped");
+ queryClient.invalidateQueries({
+ queryKey: ["organizations", "conversations", organizationId],
+ });
+ queryClient.invalidateQueries({
+ queryKey: ["organizations", "conversation-stats", organizationId],
+ });
+ },
+ });
+};
diff --git a/frontend/src/hooks/query/use-org-conversation-stats.ts b/frontend/src/hooks/query/use-org-conversation-stats.ts
new file mode 100644
index 0000000000..e9c0a6a796
--- /dev/null
+++ b/frontend/src/hooks/query/use-org-conversation-stats.ts
@@ -0,0 +1,14 @@
+import { useQuery } from "@tanstack/react-query";
+import { organizationService } from "#/api/organization-service/organization-service.api";
+import { useSelectedOrganizationId } from "#/context/use-selected-organization";
+
+export const useOrgConversationStats = () => {
+ const { organizationId } = useSelectedOrganizationId();
+
+ return useQuery({
+ queryKey: ["organizations", "conversation-stats", organizationId],
+ queryFn: () =>
+ organizationService.getConversationStats({ orgId: organizationId! }),
+ enabled: !!organizationId,
+ });
+};
diff --git a/frontend/src/hooks/query/use-org-conversations.ts b/frontend/src/hooks/query/use-org-conversations.ts
new file mode 100644
index 0000000000..4e9c65de18
--- /dev/null
+++ b/frontend/src/hooks/query/use-org-conversations.ts
@@ -0,0 +1,61 @@
+import { keepPreviousData, useQuery } from "@tanstack/react-query";
+import { organizationService } from "#/api/organization-service/organization-service.api";
+import { useSelectedOrganizationId } from "#/context/use-selected-organization";
+
+interface UseOrgConversationsParams {
+ page?: number;
+ perPage?: number;
+ search?: string;
+ sortBy?: string;
+ sortOrder?: string;
+ executionStatus?: string;
+ sandboxStatus?: string;
+ timeWindow?: string;
+ includeSubConversations?: boolean;
+}
+
+export const useOrgConversations = ({
+ page = 1,
+ perPage = 20,
+ search = "",
+ sortBy = "updated_at",
+ sortOrder = "desc",
+ executionStatus = "",
+ sandboxStatus = "",
+ timeWindow = "",
+ includeSubConversations = false,
+}: UseOrgConversationsParams = {}) => {
+ const { organizationId } = useSelectedOrganizationId();
+
+ return useQuery({
+ queryKey: [
+ "organizations",
+ "conversations",
+ organizationId,
+ page,
+ perPage,
+ search,
+ sortBy,
+ sortOrder,
+ executionStatus,
+ sandboxStatus,
+ timeWindow,
+ includeSubConversations,
+ ],
+ queryFn: () =>
+ organizationService.getConversations({
+ orgId: organizationId!,
+ page,
+ perPage,
+ search: search || undefined,
+ sortBy,
+ sortOrder,
+ executionStatus: executionStatus || undefined,
+ sandboxStatus: sandboxStatus || undefined,
+ timeWindow: timeWindow || undefined,
+ includeSubConversations,
+ }),
+ enabled: !!organizationId,
+ placeholderData: keepPreviousData,
+ });
+};
diff --git a/frontend/src/hooks/query/use-org-usage-stats.ts b/frontend/src/hooks/query/use-org-usage-stats.ts
new file mode 100644
index 0000000000..95be794812
--- /dev/null
+++ b/frontend/src/hooks/query/use-org-usage-stats.ts
@@ -0,0 +1,18 @@
+import { useQuery } from "@tanstack/react-query";
+import { organizationService } from "#/api/organization-service/organization-service.api";
+import { useSelectedOrganizationId } from "#/context/use-selected-organization";
+
+interface UseOrgUsageStatsParams {
+ days?: number;
+}
+
+export const useOrgUsageStats = ({ days = 7 }: UseOrgUsageStatsParams = {}) => {
+ const { organizationId } = useSelectedOrganizationId();
+
+ return useQuery({
+ queryKey: ["organizations", "usage-stats", organizationId, days],
+ queryFn: () =>
+ organizationService.getUsageStats({ orgId: organizationId!, days }),
+ enabled: !!organizationId,
+ });
+};
diff --git a/frontend/src/hooks/use-settings-nav-items.ts b/frontend/src/hooks/use-settings-nav-items.ts
index 19a5c96ca8..7bb7f96024 100644
--- a/frontend/src/hooks/use-settings-nav-items.ts
+++ b/frontend/src/hooks/use-settings-nav-items.ts
@@ -90,6 +90,11 @@ export function useSettingsNavItems(): SettingsNavRenderedItem[] {
);
}
+ // Hide admin dashboard for non-admins/owners or personal orgs
+ if (!isAdminOrOwner || !organizationId || isPersonalOrg) {
+ items = items.filter((item) => item.to !== "/settings/admin-dashboard");
+ }
+
const PERSONAL_LLM_PATHS = new Set([
"/settings",
"/settings/condenser",
diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.ts
index 503027dc69..ca228d17df 100644
--- a/frontend/src/i18n/declaration.ts
+++ b/frontend/src/i18n/declaration.ts
@@ -290,6 +290,7 @@ export enum I18nKey {
SETTINGS$NAV_SECRETS = "SETTINGS$NAV_SECRETS",
SETTINGS$NAV_API_KEYS = "SETTINGS$NAV_API_KEYS",
SETTINGS$NAV_ORGANIZATION = "SETTINGS$NAV_ORGANIZATION",
+ SETTINGS$NAV_ADMIN_DASHBOARD = "SETTINGS$NAV_ADMIN_DASHBOARD",
SETTINGS$NAV_ORG_MEMBERS = "SETTINGS$NAV_ORG_MEMBERS",
SETTINGS$ORG_SETTINGS_HEADER = "SETTINGS$ORG_SETTINGS_HEADER",
SETTINGS$PERSONAL_SETTINGS_HEADER = "SETTINGS$PERSONAL_SETTINGS_HEADER",
diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.json
index 76533942e3..1339e88d15 100644
--- a/frontend/src/i18n/translation.json
+++ b/frontend/src/i18n/translation.json
@@ -4929,6 +4929,23 @@
"uk": "Організація",
"ca": "Organització"
},
+ "SETTINGS$NAV_ADMIN_DASHBOARD": {
+ "en": "Admin Dashboard",
+ "ja": "管理ダッシュボード",
+ "zh-CN": "管理仪表板",
+ "zh-TW": "管理儀表板",
+ "ko-KR": "관리자 대시보드",
+ "no": "Admin Dashboard",
+ "it": "Dashboard Admin",
+ "pt": "Painel Admin",
+ "es": "Panel de Admin",
+ "ar": "لوحة الإدارة",
+ "fr": "Tableau de Bord Admin",
+ "tr": "Yönetici Panosu",
+ "de": "Admin-Dashboard",
+ "uk": "Панель адміністратора",
+ "ca": "Tauler d'Admin"
+ },
"SETTINGS$NAV_ORG_MEMBERS": {
"en": "Org Members",
"ja": "組織メンバー",
diff --git a/frontend/src/routes.ts b/frontend/src/routes.ts
index 723135b80c..1fc9616622 100644
--- a/frontend/src/routes.ts
+++ b/frontend/src/routes.ts
@@ -37,6 +37,7 @@ export default [
route("api-keys", "routes/api-keys.tsx"),
route("org-members", "routes/manage-organization-members.tsx"),
route("org", "routes/manage-org.tsx"),
+ route("admin-dashboard", "routes/admin-dashboard.tsx"),
]),
route("conversations/:conversationId", "routes/conversation.tsx"),
route("oauth/device/verify", "routes/device-verify.tsx"),
diff --git a/frontend/src/routes/admin-dashboard.tsx b/frontend/src/routes/admin-dashboard.tsx
new file mode 100644
index 0000000000..ba79cd2373
--- /dev/null
+++ b/frontend/src/routes/admin-dashboard.tsx
@@ -0,0 +1,6 @@
+import React from "react";
+import { AdminDashboard } from "#/components/features/admin-dashboard/admin-dashboard";
+
+export default function AdminDashboardPage() {
+ return <AdminDashboard />;
+}
diff --git a/frontend/src/routes/settings.tsx b/frontend/src/routes/settings.tsx
index 11fcfeb952..5d944ce86f 100644
--- a/frontend/src/routes/settings.tsx
+++ b/frontend/src/routes/settings.tsx
@@ -39,6 +39,7 @@ const SAAS_ONLY_PATHS = [
"/settings/org-defaults",
"/settings/org-defaults/condenser",
"/settings/org-defaults/verification",
+ "/settings/admin-dashboard",
];
const ORG_WIDE_BADGE_PATHS = new Set<string>([
@@ -116,7 +117,8 @@ export const clientLoader = async ({ request }: Route.ClientLoaderArgs) => {
if (
pathname === "/settings/billing" ||
pathname === "/settings/org" ||
- pathname === "/settings/org-members"
+ pathname === "/settings/org-members" ||
+ pathname === "/settings/admin-dashboard"
) {
const user = await getActiveOrganizationUser();
@@ -150,21 +152,35 @@ export const clientLoader = async ({ request }: Route.ClientLoaderArgs) => {
}
// Org route protection: redirect if user lacks required permissions or personal org
- if (pathname === "/settings/org" || pathname === "/settings/org-members") {
+ if (pathname === "/settings/org") {
const role = user?.role ?? "member";
- const requiredPermission =
- pathname === "/settings/org"
- ? "view_billing"
- : "invite_user_to_organization";
+ if (
+ !user ||
+ !rolePermissions[role].includes("view_billing") ||
+ isPersonalOrg
+ ) {
+ return redirect("/settings");
+ }
+ }
+ if (pathname === "/settings/org-members") {
+ const role = user?.role ?? "member";
if (
!user ||
- !rolePermissions[role].includes(requiredPermission) ||
+ !rolePermissions[role].includes("invite_user_to_organization") ||
isPersonalOrg
) {
return redirect("/settings");
}
}
+
+ // Admin Dashboard route protection: only admins and owners can access
+ if (pathname === "/settings/admin-dashboard") {
+ const role = user?.role ?? "member";
+ if (!user || (role !== "admin" && role !== "owner") || isPersonalOrg) {
+ return redirect("/settings");
+ }
+ }
}
return null;
diff --git a/openhands/app_server/app_conversation/app_conversation_info_service.py b/openhands/app_server/app_conversation/app_conversation_info_service.py
index e14f1dbf6e..cf7cd05b88 100644
--- a/openhands/app_server/app_conversation/app_conversation_info_service.py
+++ b/openhands/app_server/app_conversation/app_conversation_info_service.py
@@ -116,6 +116,19 @@ class AppConversationInfoService(ABC):
conversation_id: The ID of the conversation to update
"""
+ @abstractmethod
+ async def update_execution_status(
+ self,
+ conversation_id: UUID,
+ execution_status: str,
+ ) -> None:
+ """Update the execution status for a conversation.
+
+ Args:
+ conversation_id: The ID of the conversation to update
+ execution_status: The new execution status value
+ """
+
class AppConversationInfoServiceInjector(
DiscriminatedUnionMixin, Injector[AppConversationInfoService], ABC
diff --git a/openhands/app_server/app_conversation/sql_app_conversation_info_service.py b/openhands/app_server/app_conversation/sql_app_conversation_info_service.py
index 3a730b1e76..0425d27e38 100644
--- a/openhands/app_server/app_conversation/sql_app_conversation_info_service.py
+++ b/openhands/app_server/app_conversation/sql_app_conversation_info_service.py
@@ -111,6 +111,11 @@ class StoredConversationMetadata(Base):
)
public: Mapped[bool | None] = mapped_column(nullable=True, index=True)
+ # Execution status: idle, running, paused, finished, error, stuck, deleting
+ execution_status: Mapped[str | None] = mapped_column(
+ String, nullable=True, index=True
+ )
+
# Tags for conversation metadata (e.g., automation context, skills used)
tags: Mapped[dict[str, str] | None] = mapped_column(
create_json_type_decorator(dict[str, str]), nullable=True
@@ -511,6 +516,35 @@ class SQLAppConversationInfoService(AppConversationInfoService):
stack_info=True,
)
+ async def update_execution_status(
+ self,
+ conversation_id: UUID,
+ execution_status: str,
+ ) -> None:
+ """Update the execution status for a conversation.
+
+ Args:
+ conversation_id: The ID of the conversation to update
+ execution_status: The new execution status value
+ """
+ query = await self._secure_select()
+ query = query.where(
+ StoredConversationMetadata.conversation_id == str(conversation_id)
+ )
+ result = await self.db_session.execute(query)
+ stored = result.scalar_one_or_none()
+
+ if not stored:
+ logger.debug(
+ 'Conversation %s not found or not accessible, skipping execution status update',
+ conversation_id,
+ )
+ return
+
+ stored.execution_status = execution_status
+ stored.last_updated_at = utc_now()
+ await self.db_session.commit()
+
async def _secure_select(self):
query = select(StoredConversationMetadata).where(
StoredConversationMetadata.conversation_version == 'V1'
diff --git a/openhands/app_server/app_lifespan/alembic/versions/013.py b/openhands/app_server/app_lifespan/alembic/versions/013.py
new file mode 100644
index 0000000000..f0ff52f66e
--- /dev/null
+++ b/openhands/app_server/app_lifespan/alembic/versions/013.py
@@ -0,0 +1,45 @@
+"""Add execution_status column to conversation_metadata
+
+Revision ID: 013
+Revises: 012
+Create Date: 2026-06-16 00:00:00.000000
+"""
+
+from typing import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = '013'
+down_revision: str | None = '012'
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ """Add execution_status column to conversation_metadata table.
+
+ This column stores the current execution status of conversations
+ (idle, running, paused, finished, error, stuck, deleting) for
+ org-wide dashboard queries without requiring agent server calls.
+ """
+ with op.batch_alter_table('conversation_metadata') as batch_op:
+ batch_op.add_column(
+ sa.Column(
+ 'execution_status',
+ sa.String(),
+ nullable=True,
+ )
+ )
+ # Create index for efficient dashboard queries
+ batch_op.create_index(
+ 'ix_conversation_metadata_execution_status',
+ 'execution_status',
+ unique=False,
+ )
+
+
+def downgrade() -> None:
+ with op.batch_alter_table('conversation_metadata') as batch_op:
+ batch_op.drop_index('ix_conversation_metadata_execution_status')
+ batch_op.drop_column('execution_status')
diff --git a/openhands/app_server/app_lifespan/alembic/versions/014.py b/openhands/app_server/app_lifespan/alembic/versions/014.py
new file mode 100644
index 0000000000..c6e3c96a8c
--- /dev/null
+++ b/openhands/app_server/app_lifespan/alembic/versions/014.py
@@ -0,0 +1,39 @@
+"""Create recaptcha_logs table
+
+Revision ID: 014
+Revises: 013
+Create Date: 2026-06-16 00:00:00.000000
+"""
+
+from typing import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = '014'
+down_revision: str | None = '013'
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ """Create recaptcha_logs table for storing reCAPTCHA verification logs."""
+ op.create_table(
+ 'recaptcha_logs',
+ sa.Column('id', sa.String(), primary_key=True),
+ sa.Column('user_id', sa.String(), nullable=True),
+ sa.Column('score', sa.Float(), nullable=True),
+ sa.Column('token', sa.String(), nullable=True),
+ sa.Column('action', sa.String(), nullable=True),
+ sa.Column('hostname', sa.String(), nullable=True),
+ sa.Column('apk_package_name', sa.String(), nullable=True),
+ sa.Column(
+ 'created_at',
+ sa.DateTime(timezone=True),
+ nullable=True,
+ ),
+ )
+
+
+def downgrade() -> None:
+ op.drop_table('recaptcha_logs')
diff --git a/openhands/app_server/event_callback/webhook_router.py b/openhands/app_server/event_callback/webhook_router.py
index 05b0114b6e..15b6d94c5e 100644
--- a/openhands/app_server/event_callback/webhook_router.py
+++ b/openhands/app_server/event_callback/webhook_router.py
@@ -496,6 +496,7 @@ async def on_event(
await app_conversation_info_service.save_app_conversation_info(info)
# Analytics: conversation terminal state detection
+ # Also persist execution status to database for dashboard queries
for event in events:
if not isinstance(event, ConversationStateUpdateEvent):
continue
@@ -503,6 +504,10 @@ async def on_event(
continue
try:
exec_status = ConversationExecutionStatus(event.value)
+ # Persist execution status for org-wide dashboard
+ await app_conversation_info_service.update_execution_status(
+ conversation_id, exec_status.value
+ )
if exec_status.is_terminal():
await _track_conversation_terminal(
conversation_id, app_conversation_info, events, exec_status
diff --git a/openhands/app_server/recaptcha/recaptcha_models.py b/openhands/app_server/recaptcha/recaptcha_models.py
new file mode 100644
index 0000000000..a29c244dd1
--- /dev/null
+++ b/openhands/app_server/recaptcha/recaptcha_models.py
@@ -0,0 +1,29 @@
+from datetime import datetime
+from uuid import uuid4
+
+from pydantic import BaseModel, Field
+
+from openhands.agent_server.utils import OpenHandsUUID, utc_now
+
+
+class RecaptchaLog(BaseModel):
+ """Model for logging reCAPTCHA verification results."""
+
+ id: OpenHandsUUID = Field(default_factory=uuid4)
+ user_id: str | None = None
+ score: float | None = None
+ token: str | None = None
+ action: str | None = None
+ hostname: str | None = None
+ apk_package_name: str | None = None
+ created_at: datetime = Field(default_factory=utc_now)
+
+
+class RecaptchaLogRequest(BaseModel):
+ """Request model for logging reCAPTCHA verification results."""
+
+ score: float | None = None
+ token: str | None = None
+ action: str | None = None
+ hostname: str | None = None
+ apk_package_name: str | None = None
diff --git a/openhands/app_server/recaptcha/recaptcha_router.py b/openhands/app_server/recaptcha/recaptcha_router.py
new file mode 100644
index 0000000000..c63b47e18a
--- /dev/null
+++ b/openhands/app_server/recaptcha/recaptcha_router.py
@@ -0,0 +1,31 @@
+from fastapi import APIRouter, Depends, status
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from openhands.app_server.config import get_db_session, get_user_context
+from openhands.app_server.recaptcha.recaptcha_models import (
+ RecaptchaLog,
+ RecaptchaLogRequest,
+)
+from openhands.app_server.recaptcha.sql_recaptcha_service import RecaptchaService
+from openhands.app_server.user.user_context import UserContext
+
+router = APIRouter(prefix='/recaptcha', tags=['recaptcha'])
+
+
[email protected]('/log', status_code=status.HTTP_201_CREATED)
+async def log_recaptcha(
+ request: RecaptchaLogRequest,
+ user_context: UserContext = Depends(get_user_context),
+ db_session: AsyncSession = Depends(get_db_session),
+):
+ """Log reCAPTCHA verification result."""
+ service = RecaptchaService(db_session=db_session, user_context=user_context)
+ log = RecaptchaLog(
+ score=request.score,
+ token=request.token,
+ action=request.action,
+ hostname=request.hostname,
+ apk_package_name=request.apk_package_name,
+ )
+ await service.save_log(log)
+ return {'status': 'success'}
diff --git a/openhands/app_server/recaptcha/sql_recaptcha_service.py b/openhands/app_server/recaptcha/sql_recaptcha_service.py
new file mode 100644
index 0000000000..9b8893c3b1
--- /dev/null
+++ b/openhands/app_server/recaptcha/sql_recaptcha_service.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+import logging
+import uuid
+from dataclasses import dataclass
+
+from sqlalchemy import (
+ Column,
+ DateTime,
+ Float,
+ String,
+)
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from openhands.agent_server.utils import utc_now
+from openhands.app_server.recaptcha.recaptcha_models import RecaptchaLog
+from openhands.app_server.user.user_context import UserContext
+from openhands.app_server.utils.sql_utils import Base
+
+logger = logging.getLogger(__name__)
+
+
+class RecaptchaStore(Base): # type: ignore
+ __tablename__ = 'recaptcha_logs'
+
+ id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
+ user_id = Column(String, nullable=True)
+ score = Column(Float, nullable=True)
+ token = Column(String, nullable=True)
+ action = Column(String, nullable=True)
+ hostname = Column(String, nullable=True)
+ apk_package_name = Column(String, nullable=True)
+ created_at = Column(DateTime(timezone=True), default=utc_now)
+
+
+@dataclass
+class RecaptchaService:
+ """Service for logging reCAPTCHA verification results."""
+
+ db_session: AsyncSession
+ user_context: UserContext
+
+ async def save_log(self, log: RecaptchaLog) -> RecaptchaLog:
+ """Save a reCAPTCHA log entry to the database."""
+
+ user_id = await self.user_context.get_user_id()
+
+ stored = RecaptchaStore(
+ id=str(log.id),
+ user_id=user_id,
+ score=log.score,
+ token=log.token,
+ action=log.action,
+ hostname=log.hostname,
+ apk_package_name=log.apk_package_name,
+ created_at=log.created_at,
+ )
+
+ self.db_session.add(stored)
+ await self.db_session.commit()
+ return log
diff --git a/tests/unit/app_server/test_recaptcha_service.py b/tests/unit/app_server/test_recaptcha_service.py
new file mode 100644
index 0000000000..10f7d3b91e
--- /dev/null
+++ b/tests/unit/app_server/test_recaptcha_service.py
@@ -0,0 +1,52 @@
+from unittest.mock import AsyncMock
+from uuid import uuid4
+
+import pytest
+
+from openhands.app_server.recaptcha.recaptcha_models import RecaptchaLog
+from openhands.app_server.recaptcha.sql_recaptcha_service import RecaptchaService
+
+
+def mock_db_session():
+ return AsyncMock()
+
+
+def mock_user_context():
+ context = AsyncMock()
+ context.get_user_id = AsyncMock(return_value='user-123')
+ return context
+
+
+async def test_save_log(mock_db_session, mock_user_context):
+ service = RecaptchaService(
+ db_session=mock_db_session, user_context=mock_user_context
+ )
+
+ log_id = uuid4()
+ log = RecaptchaLog(
+ id=log_id,
+ score=0.9,
+ token='some-token',
+ action='login',
+ hostname='example.com',
+ apk_package_name=None,
+ )
+
+ result = await service.save_log(log)
+
+ assert result == log
+ mock_db_session.add.assert_called_once()
+ mock_db_session.commit.assert_called_once()
+
+ # Verify the stored object
+ stored = mock_db_session.add.call_args[0][0]
+ assert stored.id == str(log_id)
+ assert stored.user_id == 'user-123'
+ assert stored.score == 0.9
+ assert stored.token == 'some-token'
+ assert stored.action == 'login'
+ assert stored.hostname == 'example.com'
+ assert stored.apk_package_name is None
diff --git a/tests/unit/enterprise/test_org_conversation_service_injector.py b/tests/unit/enterprise/test_org_conversation_service_injector.py
new file mode 100644
index 0000000000..4b6894b35b
--- /dev/null
+++ b/tests/unit/enterprise/test_org_conversation_service_injector.py
@@ -0,0 +1,56 @@
+import sys
+import types
+from contextlib import asynccontextmanager
+from pathlib import Path
+
+import pytest
+from starlette.datastructures import State
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[3] / 'enterprise'))
+
+from enterprise.server.services.org_conversation_service import (
+ OrgConversationServiceInjector,
+)
+
+
+async def test_org_conversation_service_injector_sets_sandbox_service():
+ dummy_db_session = object()
+
+ class DummySandboxService:
+ closed = False
+
+ dummy_sandbox_service = DummySandboxService()
+
+ @asynccontextmanager
+ async def fake_db_session(state, request=None):
+ yield dummy_db_session
+
+ @asynccontextmanager
+ async def fake_sandbox_service(state, request=None):
+ try:
+ yield dummy_sandbox_service
+ finally:
+ dummy_sandbox_service.closed = True
+
+ sentinel = types.ModuleType('openhands.app_server.config')
+ sentinel.get_db_session = fake_db_session
+ sentinel.get_sandbox_service = fake_sandbox_service
+
+ original = sys.modules.get('openhands.app_server.config')
+ sys.modules['openhands.app_server.config'] = sentinel
+ try:
+ injector = OrgConversationServiceInjector()
+ state = State()
+ generator = injector.inject(state)
+ service = await generator.__anext__()
+ assert service.db_session is dummy_db_session
+ assert service.sandbox_service is dummy_sandbox_service
+ assert dummy_sandbox_service.closed is False
+ await generator.aclose()
+ assert dummy_sandbox_service.closed is True
+ finally:
+ if original is None:
+ sys.modules.pop('openhands.app_server.config', None)
+ else:
+ sys.modules['openhands.app_server.config'] = original