Spaces:
Runtime error
feat: add local mode auto-detection for no-gateway users (#83)
Browse filesWhen no OpenClaw gateway is detected, Mission Control now automatically
switches to Local Mode — showing a clear info banner, greying out
gateway-dependent panels, and surfacing Claude Code session stats,
GitHub profile data, and subscription-aware cost display.
Changes:
- Add capabilities endpoint to detect gateway, Claude home, subscription
- Add dashboardMode/gatewayAvailable/subscription state to Zustand store
- Add dismissible LocalModeBanner component
- Grey out Agents/Spawn/Config nav items when no gateway
- Show blue "Local Mode" indicator instead of red "Disconnected"
- Dashboard shows local metric cards (sessions, projects, tokens, cost)
- Claude Code Stats panel with session/token/cost breakdown
- GitHub panel with repo stats, languages, star/fork counts
- Subscription detection from ~/.claude/.credentials.json
- Show "Included (Max plan)" instead of dollar cost for subscribers
- Fix token cost estimation (cache reads at 10%, not 100%)
- Sessions API falls back to local Claude session scanner
- Live feed injects session items in local mode
- Memory browser auto-creates data dir with fallback path
Files changed (14)
- src/app/api/github/route.ts+87-1
- src/app/api/memory/route.ts+6
- src/app/api/sessions/route.ts+68-20
- src/app/api/status/route.ts+47-1
- src/app/page.tsx+57-18
- src/components/dashboard/dashboard.tsx+362-122
- src/components/layout/header-bar.tsx+20-3
- src/components/layout/live-feed.tsx+22-4
- src/components/layout/local-mode-banner.tsxAdded+34
- src/components/layout/nav-rail.tsx+35-21
- src/components/panels/memory-browser-panel.tsx+11-7
- src/lib/claude-sessions.ts+14-5
- src/lib/config.ts+2-1
- src/store/index.ts+20
6 unmodified lines78910111213 unmodified lines2627282930313233267 unmodified lines3013023033043053066 unmodified linesimport { validateBody, githubSyncSchema } from '@/lib/validation'import {getGitHubToken,fetchIssues,fetchIssue,createIssueComment,13 unmodified linesconst { searchParams } = new URL(request.url)const action = searchParams.get('action')if (action !== 'issues') {return NextResponse.json({ error: 'Unknown action. Use ?action=issues' }, { status: 400 })}const repo = searchParams.get('repo') || process.env.GITHUB_DEFAULT_REPO267 unmodified linesreturn NextResponse.json({ syncs })}// ── Priority mapping helper ─────────────────────────────────────function mapPriority(labels: string[]): 'critical' | 'high' | 'medium' | 'low' {6 unmodified lines7891011121313 unmodified lines272829303132333435363738267 unmodified lines3063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913926 unmodified linesimport { validateBody, githubSyncSchema } from '@/lib/validation'import {getGitHubToken,githubFetch,fetchIssues,fetchIssue,createIssueComment,13 unmodified linesconst { searchParams } = new URL(request.url)const action = searchParams.get('action')if (action === 'stats') {return await handleGitHubStats()}if (action !== 'issues') {return NextResponse.json({ error: 'Unknown action. Use ?action=issues or ?action=stats' }, { status: 400 })}const repo = searchParams.get('repo') || process.env.GITHUB_DEFAULT_REPO267 unmodified linesreturn NextResponse.json({ syncs })}// ── Stats: GitHub user profile + repo overview ──────────────────async function handleGitHubStats() {const token = getGitHubToken()if (!token) {return NextResponse.json({ error: 'GITHUB_TOKEN not configured' }, { status: 400 })}// Fetch user profileconst userRes = await githubFetch('/user')if (!userRes.ok) {return NextResponse.json({ error: 'Failed to fetch GitHub user' }, { status: 500 })}const user = await userRes.json() as Record<string, any>// Fetch repos (up to 100, sorted by recent push)const reposRes = await githubFetch('/user/repos?per_page=100&sort=pushed&affiliation=owner,collaborator')if (!reposRes.ok) {return NextResponse.json({ error: 'Failed to fetch repos' }, { status: 500 })}const allRepos = await reposRes.json() as Array<Record<string, any>>// Filter: exclude repos that are forks AND where user has never pushed// A fork the user actively commits to will have pushed_at > created_at (by more than a few seconds)const activeRepos = allRepos.filter(r => {if (!r.fork) return true// For forks, include only if pushed_at is meaningfully after created_at// (GitHub sets pushed_at = parent's pushed_at on fork creation)const created = new Date(r.created_at).getTime()const pushed = new Date(r.pushed_at).getTime()return (pushed - created) > 60_000 // pushed > 1min after fork creation})// Aggregate languagesconst langCounts: Record<string, number> = {}for (const r of activeRepos) {if (r.language) {langCounts[r.language] = (langCounts[r.language] || 0) + 1}}const topLanguages = Object.entries(langCounts).sort((a, b) => b[1] - a[1]).slice(0, 6).map(([name, count]) => ({ name, count }))// Recent repos (last 10 with actual pushes)const recentRepos = activeRepos.slice(0, 10).map(r => ({name: r.full_name,description: r.description,language: r.language,stars: r.stargazers_count,forks: r.forks_count,open_issues: r.open_issues_count,pushed_at: r.pushed_at,is_fork: r.fork,is_private: r.private,html_url: r.html_url,}))return NextResponse.json({user: {login: user.login,name: user.name,avatar_url: user.avatar_url,public_repos: user.public_repos,followers: user.followers,following: user.following,},repos: {total: activeRepos.length,public: activeRepos.filter(r => !r.private).length,private: activeRepos.filter(r => r.private).length,total_stars: activeRepos.reduce((sum: number, r) => sum + (r.stargazers_count || 0), 0),total_forks: activeRepos.reduce((sum: number, r) => sum + (r.forks_count || 0), 0),total_open_issues: activeRepos.reduce((sum: number, r) => sum + (r.open_issues_count || 0), 0),},topLanguages,recentRepos,})}// ── Priority mapping helper ─────────────────────────────────────function mapPriority(labels: string[]): 'critical' | 'high' | 'medium' | 'low' {
123453 unmodified lines91011121314import { NextRequest, NextResponse } from 'next/server'import { readdir, readFile, stat, lstat, realpath, writeFile, mkdir, unlink } from 'fs/promises'import { join, dirname, sep } from 'path'import { config } from '@/lib/config'import { resolveWithin } from '@/lib/paths'3 unmodified linesconst MEMORY_PATH = config.memoryDirinterface MemoryFile {path: stringname: string1234563 unmodified lines1011121314151617181920import { NextRequest, NextResponse } from 'next/server'import { readdir, readFile, stat, lstat, realpath, writeFile, mkdir, unlink } from 'fs/promises'import { existsSync, mkdirSync } from 'fs'import { join, dirname, sep } from 'path'import { config } from '@/lib/config'import { resolveWithin } from '@/lib/paths'3 unmodified linesconst MEMORY_PATH = config.memoryDir// Ensure memory directory exists on startupif (MEMORY_PATH && !existsSync(MEMORY_PATH)) {try { mkdirSync(MEMORY_PATH, { recursive: true }) } catch { /* ignore */ }}interface MemoryFile {path: stringname: string
123454 unmodified lines101112131415161718192021222324252627282930313233343536373839404142import { NextRequest, NextResponse } from 'next/server'import { getAllGatewaySessions } from '@/lib/sessions'import { requireRole } from '@/lib/auth'import { logger } from '@/lib/logger'4 unmodified linestry {const gatewaySessions = getAllGatewaySessions()const sessions = gatewaySessions.map((s) => {const total = s.totalTokens || 0const context = s.contextTokens || 35000const pct = context > 0 ? Math.round((total / context) * 100) : 0return {id: s.sessionId || s.key,key: s.key,agent: s.agent,kind: s.chatType || 'unknown',age: formatAge(s.updatedAt),model: s.model,tokens: `${formatTokens(total)}/${formatTokens(context)} (${pct}%)`,channel: s.channel,flags: [],active: s.active,startTime: s.updatedAt,lastActivity: s.updatedAt,}})return NextResponse.json({ sessions })} catch (error) {logger.error({ err: error }, 'Sessions API error')return NextResponse.json({ sessions: [] })}}function formatTokens(n: number): string {if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}m`if (n >= 1000) return `${Math.round(n / 1000)}k`12345674 unmodified lines12131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import { NextRequest, NextResponse } from 'next/server'import { getAllGatewaySessions } from '@/lib/sessions'import { syncClaudeSessions } from '@/lib/claude-sessions'import { getDatabase } from '@/lib/db'import { requireRole } from '@/lib/auth'import { logger } from '@/lib/logger'4 unmodified linestry {const gatewaySessions = getAllGatewaySessions()// If gateway sessions exist, return thoseif (gatewaySessions.length > 0) {const sessions = gatewaySessions.map((s) => {const total = s.totalTokens || 0const context = s.contextTokens || 35000const pct = context > 0 ? Math.round((total / context) * 100) : 0return {id: s.sessionId || s.key,key: s.key,agent: s.agent,kind: s.chatType || 'unknown',age: formatAge(s.updatedAt),model: s.model,tokens: `${formatTokens(total)}/${formatTokens(context)} (${pct}%)`,channel: s.channel,flags: [],active: s.active,startTime: s.updatedAt,lastActivity: s.updatedAt,source: 'gateway' as const,}})return NextResponse.json({ sessions })}// Fallback: sync and read local Claude sessions from SQLiteawait syncClaudeSessions()const claudeSessions = getLocalClaudeSessions()return NextResponse.json({ sessions: claudeSessions })} catch (error) {logger.error({ err: error }, 'Sessions API error')return NextResponse.json({ sessions: [] })}}/** Read Claude Code sessions from the local SQLite database */function getLocalClaudeSessions() {try {const db = getDatabase()const rows = db.prepare('SELECT * FROM claude_sessions ORDER BY last_message_at DESC LIMIT 50').all() as Array<Record<string, any>>return rows.map((s) => {const total = (s.input_tokens || 0) + (s.output_tokens || 0)const lastMsg = s.last_message_at ? new Date(s.last_message_at).getTime() : 0return {id: s.session_id,key: s.project_slug || s.session_id,agent: s.project_slug || 'local',kind: 'claude-code',age: formatAge(lastMsg),model: s.model || 'unknown',tokens: `${formatTokens(s.input_tokens || 0)}/${formatTokens(s.output_tokens || 0)}`,channel: 'local',flags: s.git_branch ? [s.git_branch] : [],active: s.is_active === 1,startTime: s.first_message_at ? new Date(s.first_message_at).getTime() : 0,lastActivity: lastMsg,source: 'local' as const,userMessages: s.user_messages || 0,assistantMessages: s.assistant_messages || 0,toolUses: s.tool_uses || 0,estimatedCost: s.estimated_cost || 0,lastUserPrompt: s.last_user_prompt || null,}})} catch (err) {logger.warn({ err }, 'Failed to read local Claude sessions')return []}}function formatTokens(n: number): string {if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}m`if (n >= 1000) return `${Math.round(n / 1000)}k`
12345635 unmodified lines424344454647412 unmodified lines460461462463464465import { NextRequest, NextResponse } from 'next/server'import net from 'node:net'import { statSync } from 'node:fs'import { runCommand, runOpenClaw, runClawdbot } from '@/lib/command'import { config } from '@/lib/config'import { getDatabase } from '@/lib/db'35 unmodified linesreturn NextResponse.json(health)}return NextResponse.json({ error: 'Invalid action' }, { status: 400 })} catch (error) {logger.error({ err: error }, 'Status API error')412 unmodified linesreturn health}function isPortOpen(host: string, port: number): Promise<boolean> {return new Promise((resolve) => {const socket = new net.Socket()123456735 unmodified lines4344454647484950515253412 unmodified lines466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511import { NextRequest, NextResponse } from 'next/server'import net from 'node:net'import { existsSync, readFileSync, statSync } from 'node:fs'import path from 'node:path'import { runCommand, runOpenClaw, runClawdbot } from '@/lib/command'import { config } from '@/lib/config'import { getDatabase } from '@/lib/db'35 unmodified linesreturn NextResponse.json(health)}if (action === 'capabilities') {const capabilities = await getCapabilities()return NextResponse.json(capabilities)}return NextResponse.json({ error: 'Invalid action' }, { status: 400 })} catch (error) {logger.error({ err: error }, 'Status API error')412 unmodified linesreturn health}async function getCapabilities() {const gateway = await isPortOpen(config.gatewayHost, config.gatewayPort)const openclawHome = !!(config.openclawHome && existsSync(config.openclawHome))const claudeProjectsPath = path.join(config.claudeHome, 'projects')const claudeHome = existsSync(claudeProjectsPath)let claudeSessions = 0try {const db = getDatabase()const row = db.prepare("SELECT COUNT(*) as c FROM claude_sessions WHERE is_active = 1").get() as { c: number } | undefinedclaudeSessions = row?.c ?? 0} catch {// claude_sessions table may not exist}// Detect Claude subscription type from credentialslet subscription: { type: string; rateLimitTier?: string } | null = nulltry {const credsPath = path.join(config.claudeHome, '.credentials.json')if (existsSync(credsPath)) {const creds = JSON.parse(readFileSync(credsPath, 'utf-8'))const oauth = creds.claudeAiOauthif (oauth?.subscriptionType) {subscription = {type: oauth.subscriptionType,rateLimitTier: oauth.rateLimitTier || undefined,}}}} catch {// credentials file may not exist or be unreadable}return { gateway, openclawHome, claudeHome, claudeSessions, subscription }}function isPortOpen(host: string, port: number): Promise<boolean> {return new Promise((resolve) => {const socket = new net.Socket()
31 unmodified lines323334353637383940414243448 unmodified lines535455565758596061626364656667686919 unmodified lines89909192939430 unmodified lines1251261271281291301311321331341351361371383 unmodified lines14214314414514614714814915031 unmodified linesimport { GitHubSyncPanel } from '@/components/panels/github-sync-panel'import { ChatPanel } from '@/components/chat/chat-panel'import { ErrorBoundary } from '@/components/ErrorBoundary'import { useWebSocket } from '@/lib/websocket'import { useServerEvents } from '@/lib/use-server-events'import { useMissionControl } from '@/store'export default function Home() {const { connect } = useWebSocket()const { activeTab, setCurrentUser, liveFeedOpen, toggleLiveFeed } = useMissionControl()// Connect to SSE for real-time local DB events (tasks, agents, chat, etc.)useServerEvents()8 unmodified lines.then(data => { if (data?.user) setCurrentUser(data.user) }).catch(() => {})// Auto-connect to gateway on mountconst wsToken = process.env.NEXT_PUBLIC_GATEWAY_TOKEN || process.env.NEXT_PUBLIC_WS_TOKEN || ''const explicitWsUrl = process.env.NEXT_PUBLIC_GATEWAY_URL || ''const gatewayPort = process.env.NEXT_PUBLIC_GATEWAY_PORT || '18789'const gatewayHost = process.env.NEXT_PUBLIC_GATEWAY_HOST || window.location.hostnameconst gatewayProto =process.env.NEXT_PUBLIC_GATEWAY_PROTOCOL ||(window.location.protocol === 'https:' ? 'wss' : 'ws')const wsUrl = explicitWsUrl || `${gatewayProto}://${gatewayHost}:${gatewayPort}`connect(wsUrl, wsToken)}, [connect, setCurrentUser])if (!isClient) {return (19 unmodified lines{/* Center: Header + Content */}<div className="flex-1 flex flex-col min-w-0"><HeaderBar /><main className="flex-1 overflow-auto pb-16 md:pb-0" role="main"><div aria-live="polite"><ErrorBoundary key={activeTab}>30 unmodified lines}function ContentRouter({ tab }: { tab: string }) {switch (tab) {case 'overview':return (<><Dashboard /><div className="mt-4 mx-4 mb-4 rounded-xl border border-border bg-card overflow-hidden"><AgentCommsPanel /></div></>)case 'tasks':3 unmodified lines<><OrchestrationBar /><AgentSquadPanelPhase3 /><div className="mt-4 mx-4 mb-4 rounded-xl border border-border bg-card overflow-hidden"><AgentCommsPanel /></div></>)case 'activity':31 unmodified lines32333435363738394041424344458 unmodified lines5455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910019 unmodified lines12012112212312412512630 unmodified lines1571581591601611621631641651661671681691701711721731741753 unmodified lines17918018118218318418518618718818931 unmodified linesimport { GitHubSyncPanel } from '@/components/panels/github-sync-panel'import { ChatPanel } from '@/components/chat/chat-panel'import { ErrorBoundary } from '@/components/ErrorBoundary'import { LocalModeBanner } from '@/components/layout/local-mode-banner'import { useWebSocket } from '@/lib/websocket'import { useServerEvents } from '@/lib/use-server-events'import { useMissionControl } from '@/store'export default function Home() {const { connect } = useWebSocket()const { activeTab, setCurrentUser, setDashboardMode, setGatewayAvailable, setSubscription, liveFeedOpen, toggleLiveFeed } = useMissionControl()// Connect to SSE for real-time local DB events (tasks, agents, chat, etc.)useServerEvents()8 unmodified lines.then(data => { if (data?.user) setCurrentUser(data.user) }).catch(() => {})// Check capabilities, then conditionally connect to gatewayfetch('/api/status?action=capabilities').then(res => res.ok ? res.json() : null).then(data => {if (data?.subscription) {setSubscription(data.subscription)}if (data && data.gateway === false) {setDashboardMode('local')setGatewayAvailable(false)// Skip WebSocket connect — no gateway to talk toreturn}if (data && data.gateway === true) {setDashboardMode('full')setGatewayAvailable(true)}// Connect to gateway WebSocketconst wsToken = process.env.NEXT_PUBLIC_GATEWAY_TOKEN || process.env.NEXT_PUBLIC_WS_TOKEN || ''const explicitWsUrl = process.env.NEXT_PUBLIC_GATEWAY_URL || ''const gatewayPort = process.env.NEXT_PUBLIC_GATEWAY_PORT || '18789'const gatewayHost = process.env.NEXT_PUBLIC_GATEWAY_HOST || window.location.hostnameconst gatewayProto =process.env.NEXT_PUBLIC_GATEWAY_PROTOCOL ||(window.location.protocol === 'https:' ? 'wss' : 'ws')const wsUrl = explicitWsUrl || `${gatewayProto}://${gatewayHost}:${gatewayPort}`connect(wsUrl, wsToken)}).catch(() => {// If capabilities check fails, still try to connectconst wsToken = process.env.NEXT_PUBLIC_GATEWAY_TOKEN || process.env.NEXT_PUBLIC_WS_TOKEN || ''const explicitWsUrl = process.env.NEXT_PUBLIC_GATEWAY_URL || ''const gatewayPort = process.env.NEXT_PUBLIC_GATEWAY_PORT || '18789'const gatewayHost = process.env.NEXT_PUBLIC_GATEWAY_HOST || window.location.hostnameconst gatewayProto =process.env.NEXT_PUBLIC_GATEWAY_PROTOCOL ||(window.location.protocol === 'https:' ? 'wss' : 'ws')const wsUrl = explicitWsUrl || `${gatewayProto}://${gatewayHost}:${gatewayPort}`connect(wsUrl, wsToken)})}, [connect, setCurrentUser, setDashboardMode, setGatewayAvailable, setSubscription])if (!isClient) {return (19 unmodified lines{/* Center: Header + Content */}<div className="flex-1 flex flex-col min-w-0"><HeaderBar /><LocalModeBanner /><main className="flex-1 overflow-auto pb-16 md:pb-0" role="main"><div aria-live="polite"><ErrorBoundary key={activeTab}>30 unmodified lines}function ContentRouter({ tab }: { tab: string }) {const { dashboardMode } = useMissionControl()const isLocal = dashboardMode === 'local'switch (tab) {case 'overview':return (<><Dashboard />{!isLocal && (<div className="mt-4 mx-4 mb-4 rounded-xl border border-border bg-card overflow-hidden"><AgentCommsPanel /></div>)}</>)case 'tasks':3 unmodified lines<><OrchestrationBar /><AgentSquadPanelPhase3 />{!isLocal && (<div className="mt-4 mx-4 mb-4 rounded-xl border border-border bg-card overflow-hidden"><AgentCommsPanel /></div>)}</>)case 'activity':
15 unmodified lines1617181920212223242526272829303132333435363738394041427 unmodified lines50515253545556575859606127 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281292 unmodified lines13213313413513613713813914014114214314414527 unmodified lines1731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662676 unmodified lines27427527627727827928053 unmodified lines3343353363373383393403413423433441 unmodified line34634734834935035135235335435516 unmodified lines37237337437537637779 unmodified lines4574584594604614622 unmodified lines46546646746846947079 unmodified lines55055155215 unmodified lineswebhookCount: number}export function Dashboard() {const {sessions,setSessions,connection,logs,agents,tasks,setActiveTab,} = useMissionControl()const [systemStats, setSystemStats] = useState<any>(null)const [dbStats, setDbStats] = useState<DbStats | null>(null)const [isLoading, setIsLoading] = useState(true)const loadDashboard = useCallback(async () => {try {const [dashRes, sessRes] = await Promise.all([fetch('/api/status?action=dashboard'),fetch('/api/sessions'),])if (dashRes.ok) {const data = await dashRes.json()7 unmodified linesconst data = await sessRes.json()if (data && !data.error) setSessions(data.sessions || data)}} catch {// silent} finally {setIsLoading(false)}}, [setSessions])useSmartPoll(loadDashboard, 60000, { pauseWhenConnected: true })27 unmodified lines<div className="p-5 space-y-5">{/* Top Metric Cards */}<div className="grid grid-cols-2 lg:grid-cols-4 gap-3"><div className="cursor-pointer" onClick={() => setActiveTab('history')}><MetricCardlabel="Active Sessions"value={activeSessions}total={sessions.length}icon={<SessionIcon />}color="blue"/></div><div className="cursor-pointer" onClick={() => setActiveTab('agents')}><MetricCardlabel="Agents Online"value={onlineAgents}total={dbStats?.agents.total ?? agents.length}icon={<AgentIcon />}color="green"/></div><div className="cursor-pointer" onClick={() => setActiveTab('tasks')}><MetricCardlabel="Tasks Running"value={runningTasks}total={dbStats?.tasks.total ?? tasks.length}icon={<TaskIcon />}color="purple"/></div><div className="cursor-pointer" onClick={() => setActiveTab('logs')}><MetricCardlabel="Errors (24h)"value={errorCount}icon={<ErrorIcon />}color={errorCount > 0 ? 'red' : 'green'}/></div></div>{/* Three-column layout */}2 unmodified lines<div className="panel"><div className="panel-header"><h3 className="text-sm font-semibold text-foreground">System Health</h3><StatusBadge connected={connection.isConnected} /></div><div className="panel-body space-y-3"><HealthRowlabel="Gateway"value={connection.isConnected ? 'Connected' : 'Disconnected'}status={connection.isConnected ? 'good' : 'bad'}/>{memPct != null && (<HealthRowlabel="Memory"27 unmodified lines</div></div>{/* Security & Audit */}<div className="panel cursor-pointer hover:border-primary/30 transition-smooth" onClick={() => setActiveTab('audit')}><div className="panel-header"><h3 className="text-sm font-semibold text-foreground">Security & Audit</h3>{dbStats && dbStats.audit.loginFailures > 0 && (<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-2xs font-medium bg-red-500/10 text-red-400 border border-red-500/20">{dbStats.audit.loginFailures} failed login{dbStats.audit.loginFailures > 1 ? 's' : ''}</span>)}</div><div className="panel-body space-y-3"><StatRow label="Audit events (24h)" value={dbStats?.audit.day ?? 0} /><StatRow label="Audit events (7d)" value={dbStats?.audit.week ?? 0} /><StatRowlabel="Login failures (24h)"value={dbStats?.audit.loginFailures ?? 0}alert={dbStats ? dbStats.audit.loginFailures > 0 : false}/><StatRow label="Activities (24h)" value={dbStats?.activities.day ?? 0} /><StatRow label="Webhooks configured" value={dbStats?.webhookCount ?? 0} /><div className="pt-1 border-t border-border/50"><div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Unread notifications</span><span className={`text-xs font-medium font-mono-tight ${(dbStats?.notifications.unread ?? 0) > 0 ? 'text-amber-400' : 'text-muted-foreground'}`}>{dbStats?.notifications.unread ?? 0}</span></div></div></div></div>{/* Backup & Data */}<div className="panel"><div className="panel-header"><h3 className="text-sm font-semibold text-foreground">Backup & Pipelines</h3></div><div className="panel-body space-y-3">{dbStats?.backup ? (<><div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Latest backup</span><span className={`text-xs font-medium font-mono-tight ${dbStats.backup.age_hours > 48 ? 'text-red-400' :dbStats.backup.age_hours > 24 ? 'text-amber-400' : 'text-green-400'}`}>{dbStats.backup.age_hours < 1 ? '<1h ago' : `${dbStats.backup.age_hours}h ago`}</span></div><div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Backup size</span><span className="text-xs font-mono-tight text-muted-foreground">{formatBytes(dbStats.backup.size)}</span></div></>) : (<div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Latest backup</span><span className="text-xs font-medium text-amber-400">None</span></div>)}<div className="pt-1 border-t border-border/50 space-y-2"><StatRow label="Active pipelines" value={dbStats?.pipelines.active ?? 0} /><StatRow label="Pipeline runs (24h)" value={dbStats?.pipelines.recentDay ?? 0} /></div><div className="pt-1 border-t border-border/50 space-y-2"><div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Tasks by status</span></div>{dbStats?.tasks.total ? (<div className="flex flex-wrap gap-1.5">{Object.entries(dbStats.tasks.byStatus).map(([status, count]) => (<spankey={status}className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-2xs font-mono-tight bg-secondary text-muted-foreground"><span className={`w-1.5 h-1.5 rounded-full ${taskStatusColor(status)}`} />{status}: {count}</span>))}</div>) : (<span className="text-2xs text-muted-foreground">No tasks</span>)}</div></div></div></div>{/* Bottom two-column: Sessions + Logs */}6 unmodified lines</div><div className="divide-y divide-border/50 max-h-56 overflow-y-auto">{sessions.length === 0 ? (<div className="px-4 py-8 text-center"><p className="text-xs text-muted-foreground">No active sessions</p><p className="text-2xs text-muted-foreground/60 mt-1">Sessions appear when agents connect via gateway</p></div>) : (sessions.slice(0, 8).map((session) => (<div key={session.id} className="px-4 py-2.5 flex items-center gap-3 hover:bg-secondary/30 transition-smooth">53 unmodified lines{/* Quick Actions */}<div className="grid grid-cols-2 lg:grid-cols-5 gap-2"><QuickAction label="Spawn Agent" desc="Launch sub-agent" tab="spawn" icon={<SpawnActionIcon />} setActiveTab={setActiveTab} /><QuickAction label="View Logs" desc="Real-time viewer" tab="logs" icon={<LogActionIcon />} setActiveTab={setActiveTab} /><QuickAction label="Task Board" desc="Kanban view" tab="tasks" icon={<TaskActionIcon />} setActiveTab={setActiveTab} /><QuickAction label="Memory" desc="Knowledge base" tab="memory" icon={<MemoryActionIcon />} setActiveTab={setActiveTab} /><QuickAction label="Orchestration" desc="Workflows & pipelines" tab="orchestration" icon={<PipelineActionIcon />} setActiveTab={setActiveTab} /></div></div>)1 unmodified line// --- Sub-components ---function MetricCard({ label, value, total, icon, color }: {label: stringvalue: numbertotal?: numbericon: React.ReactNodecolor: 'blue' | 'green' | 'purple' | 'red'}) {16 unmodified lines<span className="text-xs opacity-50 font-mono-tight">/ {total}</span>)}</div></div>)}79 unmodified linesreturn `${hours}h`}function formatBytes(bytes: number): string {if (bytes === 0) return '0 B'const k = 10242 unmodified linesreturn `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`}function taskStatusColor(status: string): string {switch (status) {case 'done': return 'bg-green-500'79 unmodified lines</svg>)}15 unmodified lines16171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364657 unmodified lines7374757677787980818283848586878889909192939427 unmodified lines1221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042 unmodified lines20720820921021121221321421521621721821922022122222322422522622722822923023127 unmodified lines2592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444456 unmodified lines45245345445545645745853 unmodified lines5125135145155165175185195205215225235245255265275281 unmodified line53053153253353453553653753853954016 unmodified lines55755855956056156256356456579 unmodified lines6456466476486496506516526536546556562 unmodified lines65966066166266366466566666766866967067167267367467567667767867968068168268368468568679 unmodified lines76676776876977077177277377477577677777877978078178278378478578678778878979079179215 unmodified lineswebhookCount: number}interface ClaudeStats {total_sessions: numberactive_sessions: numbertotal_input_tokens: numbertotal_output_tokens: numbertotal_estimated_cost: numberunique_projects: number}export function Dashboard() {const {sessions,setSessions,connection,dashboardMode,subscription,logs,agents,tasks,setActiveTab,} = useMissionControl()const isLocal = dashboardMode === 'local'const subscriptionLabel = subscription?.type? subscription.type.charAt(0).toUpperCase() + subscription.type.slice(1): nullconst [systemStats, setSystemStats] = useState<any>(null)const [dbStats, setDbStats] = useState<DbStats | null>(null)const [claudeStats, setClaudeStats] = useState<ClaudeStats | null>(null)const [githubStats, setGithubStats] = useState<any>(null)const [isLoading, setIsLoading] = useState(true)const loadDashboard = useCallback(async () => {try {const fetches: Promise<Response>[] = [fetch('/api/status?action=dashboard'),fetch('/api/sessions'),]if (isLocal) {fetches.push(fetch('/api/claude/sessions'))fetches.push(fetch('/api/github?action=stats'))}const [dashRes, sessRes, claudeRes, ghRes] = await Promise.all(fetches)if (dashRes.ok) {const data = await dashRes.json()7 unmodified linesconst data = await sessRes.json()if (data && !data.error) setSessions(data.sessions || data)}if (claudeRes?.ok) {const data = await claudeRes.json()if (data?.stats) setClaudeStats(data.stats)}if (ghRes?.ok) {const data = await ghRes.json()if (data && !data.error) setGithubStats(data)}} catch {// silent} finally {setIsLoading(false)}}, [setSessions, isLocal])useSmartPoll(loadDashboard, 60000, { pauseWhenConnected: true })27 unmodified lines<div className="p-5 space-y-5">{/* Top Metric Cards */}<div className="grid grid-cols-2 lg:grid-cols-4 gap-3">{isLocal ? (<><div className="cursor-pointer" onClick={() => setActiveTab('sessions')}><MetricCardlabel="Active Sessions"value={claudeStats?.active_sessions ?? activeSessions}total={claudeStats?.total_sessions ?? sessions.length}icon={<SessionIcon />}color="blue"/></div><div className="cursor-pointer" onClick={() => setActiveTab('sessions')}><MetricCardlabel="Projects"value={claudeStats?.unique_projects ?? 0}icon={<ProjectIcon />}color="green"/></div><div className="cursor-pointer" onClick={() => setActiveTab('tokens')}><MetricCardlabel="Tokens Used"value={formatTokensShort((claudeStats?.total_input_tokens ?? 0) + (claudeStats?.total_output_tokens ?? 0))}subtitle={claudeStats ? `${formatTokensShort(claudeStats.total_input_tokens)} in / ${formatTokensShort(claudeStats.total_output_tokens)} out` : undefined}icon={<TokenIcon />}color="purple"/></div><div className="cursor-pointer" onClick={() => setActiveTab('tokens')}><MetricCardlabel="Est. Cost"value={subscriptionLabel ? `Included` : `$${(claudeStats?.total_estimated_cost ?? 0).toFixed(2)}`}subtitle={subscriptionLabel ? `${subscriptionLabel} plan` : undefined}icon={<CostIcon />}color={subscriptionLabel ? 'green' : (claudeStats && claudeStats.total_estimated_cost > 10 ? 'red' : 'green')}/></div></>) : (<><div className="cursor-pointer" onClick={() => setActiveTab('history')}><MetricCardlabel="Active Sessions"value={activeSessions}total={sessions.length}icon={<SessionIcon />}color="blue"/></div><div className="cursor-pointer" onClick={() => setActiveTab('agents')}><MetricCardlabel="Agents Online"value={onlineAgents}total={dbStats?.agents.total ?? agents.length}icon={<AgentIcon />}color="green"/></div><div className="cursor-pointer" onClick={() => setActiveTab('tasks')}><MetricCardlabel="Tasks Running"value={runningTasks}total={dbStats?.tasks.total ?? tasks.length}icon={<TaskIcon />}color="purple"/></div><div className="cursor-pointer" onClick={() => setActiveTab('logs')}><MetricCardlabel="Errors (24h)"value={errorCount}icon={<ErrorIcon />}color={errorCount > 0 ? 'red' : 'green'}/></div></>)}</div>{/* Three-column layout */}2 unmodified lines<div className="panel"><div className="panel-header"><h3 className="text-sm font-semibold text-foreground">System Health</h3>{isLocal ? (<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-2xs font-medium bg-blue-500/10 text-blue-400 border border-blue-500/20"><span className="w-1.5 h-1.5 rounded-full bg-blue-400" />Local</span>) : (<StatusBadge connected={connection.isConnected} />)}</div><div className="panel-body space-y-3">{isLocal ? (<HealthRow label="Mode" value="Local" status="good" />) : (<HealthRowlabel="Gateway"value={connection.isConnected ? 'Connected' : 'Disconnected'}status={connection.isConnected ? 'good' : 'bad'}/>)}{memPct != null && (<HealthRowlabel="Memory"27 unmodified lines</div></div>{/* Middle panel: Claude Stats (local) or Security & Audit (full) */}{isLocal ? (<div className="panel cursor-pointer hover:border-primary/30 transition-smooth" onClick={() => setActiveTab('sessions')}><div className="panel-header"><h3 className="text-sm font-semibold text-foreground">Claude Code Stats</h3><span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-2xs font-medium bg-purple-500/10 text-purple-400 border border-purple-500/20">{claudeStats?.total_sessions ?? 0} sessions</span></div><div className="panel-body space-y-3"><StatRow label="Total sessions" value={claudeStats?.total_sessions ?? 0} /><StatRow label="Active now" value={claudeStats?.active_sessions ?? 0} /><StatRow label="Unique projects" value={claudeStats?.unique_projects ?? 0} /><div className="pt-1 border-t border-border/50 space-y-2"><div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Input tokens</span><span className="text-xs font-medium font-mono-tight text-muted-foreground">{formatTokensShort(claudeStats?.total_input_tokens ?? 0)}</span></div><div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Output tokens</span><span className="text-xs font-medium font-mono-tight text-muted-foreground">{formatTokensShort(claudeStats?.total_output_tokens ?? 0)}</span></div></div><div className="pt-1 border-t border-border/50"><div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Estimated cost</span>{subscriptionLabel ? (<span className="text-xs font-medium font-mono-tight text-green-400">Included ({subscriptionLabel})</span>) : (<span className={`text-xs font-medium font-mono-tight ${(claudeStats?.total_estimated_cost ?? 0) > 10 ? 'text-amber-400' : 'text-green-400'}`}>${(claudeStats?.total_estimated_cost ?? 0).toFixed(2)}</span>)}</div></div></div></div>) : (<div className="panel cursor-pointer hover:border-primary/30 transition-smooth" onClick={() => setActiveTab('audit')}><div className="panel-header"><h3 className="text-sm font-semibold text-foreground">Security & Audit</h3>{dbStats && dbStats.audit.loginFailures > 0 && (<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-2xs font-medium bg-red-500/10 text-red-400 border border-red-500/20">{dbStats.audit.loginFailures} failed login{dbStats.audit.loginFailures > 1 ? 's' : ''}</span>)}</div><div className="panel-body space-y-3"><StatRow label="Audit events (24h)" value={dbStats?.audit.day ?? 0} /><StatRow label="Audit events (7d)" value={dbStats?.audit.week ?? 0} /><StatRowlabel="Login failures (24h)"value={dbStats?.audit.loginFailures ?? 0}alert={dbStats ? dbStats.audit.loginFailures > 0 : false}/><StatRow label="Activities (24h)" value={dbStats?.activities.day ?? 0} /><StatRow label="Webhooks configured" value={dbStats?.webhookCount ?? 0} /><div className="pt-1 border-t border-border/50"><div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Unread notifications</span><span className={`text-xs font-medium font-mono-tight ${(dbStats?.notifications.unread ?? 0) > 0 ? 'text-amber-400' : 'text-muted-foreground'}`}>{dbStats?.notifications.unread ?? 0}</span></div></div></div></div>)}{/* Third column: GitHub (local) or Backup & Pipelines (full) */}{isLocal ? (<div className="panel"><div className="panel-header"><h3 className="text-sm font-semibold text-foreground">GitHub</h3>{githubStats?.user && (<span className="text-2xs text-muted-foreground font-mono-tight">@{githubStats.user.login}</span>)}</div><div className="panel-body space-y-3">{githubStats ? (<><StatRow label="Active repos" value={githubStats.repos.total} /><StatRow label="Public" value={githubStats.repos.public} /><StatRow label="Private" value={githubStats.repos.private} /><div className="pt-1 border-t border-border/50 space-y-2"><StatRow label="Total stars" value={githubStats.repos.total_stars} /><StatRow label="Total forks" value={githubStats.repos.total_forks} /><StatRow label="Open issues" value={githubStats.repos.total_open_issues} /></div>{githubStats.topLanguages.length > 0 && (<div className="pt-1 border-t border-border/50"><div className="text-xs text-muted-foreground mb-1.5">Top languages</div><div className="flex flex-wrap gap-1.5">{githubStats.topLanguages.map((lang: { name: string; count: number }) => (<spankey={lang.name}className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-2xs font-mono-tight bg-secondary text-muted-foreground"><span className={`w-1.5 h-1.5 rounded-full ${langColor(lang.name)}`} />{lang.name}</span>))}</div></div>)}</>) : (<div className="text-center py-4"><p className="text-xs text-muted-foreground">No GitHub token configured</p><p className="text-2xs text-muted-foreground/60 mt-1">Set GITHUB_TOKEN in .env.local</p></div>)}</div></div>) : (<div className="panel"><div className="panel-header"><h3 className="text-sm font-semibold text-foreground">Backup & Pipelines</h3></div><div className="panel-body space-y-3">{dbStats?.backup ? (<><div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Latest backup</span><span className={`text-xs font-medium font-mono-tight ${dbStats.backup.age_hours > 48 ? 'text-red-400' :dbStats.backup.age_hours > 24 ? 'text-amber-400' : 'text-green-400'}`}>{dbStats.backup.age_hours < 1 ? '<1h ago' : `${dbStats.backup.age_hours}h ago`}</span></div><div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Backup size</span><span className="text-xs font-mono-tight text-muted-foreground">{formatBytes(dbStats.backup.size)}</span></div></>) : (<div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Latest backup</span><span className="text-xs font-medium text-amber-400">None</span></div>)}<div className="pt-1 border-t border-border/50 space-y-2"><StatRow label="Active pipelines" value={dbStats?.pipelines.active ?? 0} /><StatRow label="Pipeline runs (24h)" value={dbStats?.pipelines.recentDay ?? 0} /></div><div className="pt-1 border-t border-border/50 space-y-2"><div className="flex items-center justify-between"><span className="text-xs text-muted-foreground">Tasks by status</span></div>{dbStats?.tasks.total ? (<div className="flex flex-wrap gap-1.5">{Object.entries(dbStats.tasks.byStatus).map(([status, count]) => (<spankey={status}className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-2xs font-mono-tight bg-secondary text-muted-foreground"><span className={`w-1.5 h-1.5 rounded-full ${taskStatusColor(status)}`} />{status}: {count}</span>))}</div>) : (<span className="text-2xs text-muted-foreground">No tasks</span>)}</div></div></div>)}</div>{/* Bottom two-column: Sessions + Logs */}6 unmodified lines</div><div className="divide-y divide-border/50 max-h-56 overflow-y-auto">{sessions.length === 0 ? (<div className="px-4 py-8 text-center"><p className="text-xs text-muted-foreground">No active sessions</p><p className="text-2xs text-muted-foreground/60 mt-1">{isLocal ? 'Sessions appear when Claude Code or Codex CLI are running' : 'Sessions appear when agents connect via gateway'}</p></div>) : (sessions.slice(0, 8).map((session) => (<div key={session.id} className="px-4 py-2.5 flex items-center gap-3 hover:bg-secondary/30 transition-smooth">53 unmodified lines{/* Quick Actions */}<div className="grid grid-cols-2 lg:grid-cols-5 gap-2">{!isLocal && (<QuickAction label="Spawn Agent" desc="Launch sub-agent" tab="spawn" icon={<SpawnActionIcon />} setActiveTab={setActiveTab} />)}<QuickAction label="View Logs" desc="Real-time viewer" tab="logs" icon={<LogActionIcon />} setActiveTab={setActiveTab} /><QuickAction label="Task Board" desc="Kanban view" tab="tasks" icon={<TaskActionIcon />} setActiveTab={setActiveTab} /><QuickAction label="Memory" desc="Knowledge base" tab="memory" icon={<MemoryActionIcon />} setActiveTab={setActiveTab} />{isLocal ? (<QuickAction label="Sessions" desc="Claude Code sessions" tab="sessions" icon={<SessionIcon />} setActiveTab={setActiveTab} />) : (<QuickAction label="Orchestration" desc="Workflows & pipelines" tab="orchestration" icon={<PipelineActionIcon />} setActiveTab={setActiveTab} />)}</div></div>)1 unmodified line// --- Sub-components ---function MetricCard({ label, value, total, subtitle, icon, color }: {label: stringvalue: number | stringtotal?: numbersubtitle?: stringicon: React.ReactNodecolor: 'blue' | 'green' | 'purple' | 'red'}) {16 unmodified lines<span className="text-xs opacity-50 font-mono-tight">/ {total}</span>)}</div>{subtitle && (<div className="text-2xs opacity-50 font-mono-tight mt-0.5">{subtitle}</div>)}</div>)}79 unmodified linesreturn `${hours}h`}function formatTokensShort(n: number): string {if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`if (n >= 1_000) return `${Math.round(n / 1_000)}K`return String(n)}function formatBytes(bytes: number): string {if (bytes === 0) return '0 B'const k = 10242 unmodified linesreturn `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`}function langColor(lang: string): string {const colors: Record<string, string> = {TypeScript: 'bg-blue-500',JavaScript: 'bg-yellow-500',Python: 'bg-green-500',Rust: 'bg-orange-500',Go: 'bg-cyan-500',Ruby: 'bg-red-500',Java: 'bg-red-400','C++': 'bg-pink-500',C: 'bg-gray-500',Shell: 'bg-emerald-500',Solidity: 'bg-purple-500',HTML: 'bg-orange-400',CSS: 'bg-indigo-500',Dart: 'bg-teal-500',Swift: 'bg-orange-600',Kotlin: 'bg-violet-500',}return colors[lang] || 'bg-muted-foreground/40'}function taskStatusColor(status: string): string {switch (status) {case 'done': return 'bg-green-500'79 unmodified lines</svg>)}function ProjectIcon() {return (<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="M2 4l6-2 6 2v8l-6 2-6-2V4z" /><path d="M8 6v8M2 4l6 2 6-2" /></svg>)}function TokenIcon() {return (<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><circle cx="8" cy="8" r="6" /><path d="M8 4v8M5 6h6M5 10h6" /></svg>)}function CostIcon() {return (<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><circle cx="8" cy="8" r="6" /><path d="M8 3.5V5M8 11v1.5M10.5 6.5C10.5 5.4 9.4 4.5 8 4.5S5.5 5.4 5.5 6.5c0 1.1 1.1 2 2.5 2s2.5.9 2.5 2c0 1.1-1.1 2-2.5 2s-2.5-.9-2.5-2" /></svg>)}
264 unmodified lines2652662672682692702712722732742752766 unmodified lines2832842852862872882892902919 unmodified lines301302303304305306307308264 unmodified linesconnection: { isConnected: boolean; reconnectAttempts: number }onReconnect: () => void}) {const isReconnecting = !connection.isConnected && connection.reconnectAttempts > 0let dotClass: stringlet title: stringif (connection.isConnected) {dotClass = 'bg-green-500'title = 'Gateway connected'} else if (isReconnecting) {6 unmodified linesreturn (<buttononClick={!connection.isConnected ? onReconnect : undefined}className={`md:hidden flex items-center justify-center h-8 w-8 rounded-md ${connection.isConnected ? 'cursor-default' : 'hover:bg-secondary cursor-pointer'} transition-smooth`}title={title}>9 unmodified linesconnection: { isConnected: boolean; reconnectAttempts: number; latency?: number }onReconnect: () => void}) {const isReconnecting = !connection.isConnected && connection.reconnectAttempts > 0let dotClass: stringlet label: string264 unmodified lines2652662672682692702712722732742752762772782792802816 unmodified lines2882892902912922932942952969 unmodified lines306307308309310311312313314315316317318319320321322323324325264 unmodified linesconnection: { isConnected: boolean; reconnectAttempts: number }onReconnect: () => void}) {const { dashboardMode } = useMissionControl()const isLocal = dashboardMode === 'local'const isReconnecting = !connection.isConnected && connection.reconnectAttempts > 0let dotClass: stringlet title: stringif (isLocal) {dotClass = 'bg-blue-500'title = 'Local Mode'} else if (connection.isConnected) {dotClass = 'bg-green-500'title = 'Gateway connected'} else if (isReconnecting) {6 unmodified linesreturn (<buttononClick={!isLocal && !connection.isConnected ? onReconnect : undefined}className={`md:hidden flex items-center justify-center h-8 w-8 rounded-md ${isLocal || connection.isConnected ? 'cursor-default' : 'hover:bg-secondary cursor-pointer'} transition-smooth`}title={title}>9 unmodified linesconnection: { isConnected: boolean; reconnectAttempts: number; latency?: number }onReconnect: () => void}) {const { dashboardMode } = useMissionControl()const isLocal = dashboardMode === 'local'const isReconnecting = !connection.isConnected && connection.reconnectAttempts > 0if (isLocal) {return (<div className="flex items-center gap-1.5 text-xs px-2 py-1 rounded-md cursor-default"><span className="text-muted-foreground">Gateway</span><span className="w-1.5 h-1.5 rounded-full bg-blue-500" /><span className="font-medium font-mono-tight text-blue-400">Local</span></div>)}let dotClass: stringlet label: string
3 unmodified lines4567891011121311 unmodified lines25262728293059 unmodified lines90919293949596973 unmodified linesimport { useEffect, useState } from 'react'export function LiveFeed() {const { logs, sessions, activities, connection, toggleLiveFeed } = useMissionControl()const [expanded, setExpanded] = useState(true)// Combine logs and activities into a unified feedconst feedItems = [...logs.slice(0, 30).map(log => ({id: `log-${log.id}`,11 unmodified linessource: act.actor,timestamp: act.created_at * 1000,})),].sort((a, b) => b.timestamp - a.timestamp).slice(0, 40)if (!expanded) {59 unmodified lines{/* Feed items */}<div className="flex-1 overflow-y-auto">{feedItems.length === 0 ? (<div className="px-3 py-8 text-center text-xs text-muted-foreground">No activity yet</div>) : (<div className="divide-y divide-border/50">3 unmodified lines4567891011121314151617181920212223242511 unmodified lines3738394041424359 unmodified lines1031041051061071081091101111121131141153 unmodified linesimport { useEffect, useState } from 'react'export function LiveFeed() {const { logs, sessions, activities, connection, dashboardMode, toggleLiveFeed } = useMissionControl()const isLocal = dashboardMode === 'local'const [expanded, setExpanded] = useState(true)// Combine logs, activities, and (in local mode) session events into a unified feedconst sessionItems = isLocal? sessions.slice(0, 10).map(s => ({id: `sess-${s.id}`,type: 'session' as const,level: 'info' as const,message: `${s.active ? 'Active' : 'Idle'} session: ${s.key || s.id}`,source: s.model?.split('/').pop()?.split('-').slice(0, 2).join('-') || 'claude',timestamp: s.lastActivity || s.startTime || Date.now(),})): []const feedItems = [...logs.slice(0, 30).map(log => ({id: `log-${log.id}`,11 unmodified linessource: act.actor,timestamp: act.created_at * 1000,})),...sessionItems,].sort((a, b) => b.timestamp - a.timestamp).slice(0, 40)if (!expanded) {59 unmodified lines{/* Feed items */}<div className="flex-1 overflow-y-auto">{feedItems.length === 0 ? (<div className="px-3 py-8 text-center"><p className="text-xs text-muted-foreground">No activity yet</p><p className="text-2xs text-muted-foreground/60 mt-1">{isLocal? 'Events appear when you create tasks or agents update': 'Events stream here from the gateway and local DB'}</p></div>) : (<div className="divide-y divide-border/50">
12345678910111213141516171819202122232425262728293031323334'use client'
import { useMissionControl } from '@/store'
export function LocalModeBanner() { const { dashboardMode, bannerDismissed, dismissBanner, setActiveTab } = useMissionControl()
if (dashboardMode === 'full' || bannerDismissed) return null
return ( <div className="mx-4 mt-3 mb-0 flex items-center gap-3 px-4 py-2.5 rounded-lg bg-blue-500/10 border border-blue-500/20 text-sm"> <span className="w-1.5 h-1.5 rounded-full bg-blue-500 shrink-0" /> <p className="flex-1 text-xs text-blue-300"> <span className="font-medium text-blue-200">No OpenClaw gateway detected</span> {' — running in Local Mode. Monitoring Claude Code sessions, tasks, and local data.'} </p> <button onClick={() => setActiveTab('gateways')} className="shrink-0 text-2xs font-medium text-blue-400 hover:text-blue-300 px-2 py-1 rounded border border-blue-500/20 hover:border-blue-500/40 transition-colors" > Configure Gateway </button> <button onClick={dismissBanner} className="shrink-0 text-blue-400/60 hover:text-blue-300 transition-colors" title="Dismiss" > <svg className="w-3.5 h-3.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"> <path d="M4 4l8 8M12 4l-8 8" /> </svg> </button> </div> )}7 unmodified lines89101112137 unmodified lines2122232425262714 unmodified lines424344454647487 unmodified lines565758596061625 unmodified lines6869707172737481 unmodified lines1561571581591601611621631641651661671681691704 unmodified lines1751761771781791801811821831841851861875 unmodified lines19319419519619719819920020120220320420520620720820921011 unmodified lines2222232242252262272282292302 unmodified lines2332342352362372382397 unmodified lineslabel: stringicon: React.ReactNodepriority: boolean // Show in mobile bottom bar}interface NavGroup {7 unmodified linesid: 'core',items: [{ id: 'overview', label: 'Overview', icon: <OverviewIcon />, priority: true },{ id: 'agents', label: 'Agents', icon: <AgentsIcon />, priority: true },{ id: 'tasks', label: 'Tasks', icon: <TasksIcon />, priority: true },{ id: 'sessions', label: 'Sessions', icon: <SessionsIcon />, priority: false },],14 unmodified lineslabel: 'AUTOMATE',items: [{ id: 'cron', label: 'Cron', icon: <CronIcon />, priority: false },{ id: 'spawn', label: 'Spawn', icon: <SpawnIcon />, priority: false },{ id: 'webhooks', label: 'Webhooks', icon: <WebhookIcon />, priority: false },{ id: 'alerts', label: 'Alerts', icon: <AlertIcon />, priority: false },{ id: 'github', label: 'GitHub', icon: <GitHubIcon />, priority: false },7 unmodified lines{ id: 'audit', label: 'Audit', icon: <AuditIcon />, priority: false },{ id: 'history', label: 'History', icon: <HistoryIcon />, priority: false },{ id: 'gateways', label: 'Gateways', icon: <GatewaysIcon />, priority: false },{ id: 'gateway-config', label: 'Config', icon: <GatewayConfigIcon />, priority: false },{ id: 'integrations', label: 'Integrations', icon: <IntegrationsIcon />, priority: false },{ id: 'super-admin', label: 'Super Admin', icon: <SuperAdminIcon />, priority: false },{ id: 'settings', label: 'Settings', icon: <SettingsIcon />, priority: false },5 unmodified linesconst allNavItems = navGroups.flatMap(g => g.items)export function NavRail() {const { activeTab, setActiveTab, connection, sidebarExpanded, collapsedGroups, toggleSidebar, toggleGroup } = useMissionControl()// Keyboard shortcut: [ to toggle sidebaruseEffect(() => {81 unmodified lines}`}><div className={`flex flex-col ${sidebarExpanded ? 'gap-0.5 px-2' : 'items-center gap-1'}`}>{group.items.map((item) => (<NavButtonkey={item.id}item={item}active={activeTab === item.id}expanded={sidebarExpanded}onClick={() => setActiveTab(item.id)}/>))}</div></div></div>4 unmodified lines<div className={`shrink-0 py-3 flex ${sidebarExpanded ? 'px-3 items-center gap-2' : 'flex-col items-center'}`}><divclassName={`w-2.5 h-2.5 rounded-full shrink-0 ${connection.isConnected ? 'bg-green-500 pulse-dot' : 'bg-red-500'}`}title={connection.isConnected ? 'Gateway connected' : 'Gateway disconnected'}/>{sidebarExpanded && (<span className="text-xs text-muted-foreground truncate">{connection.isConnected ? 'Connected' : 'Disconnected'}</span>)}</div>5 unmodified lines)}function NavButton({ item, active, expanded, onClick }: {item: NavItemactive: booleanexpanded: booleanonClick: () => void}) {if (expanded) {return (<buttononClick={onClick}aria-current={active ? 'page' : undefined}className={`w-full flex items-center gap-2 px-2 py-1.5 rounded-lg text-left transition-smooth relative ${active? 'bg-primary/15 text-primary': 'text-muted-foreground hover:text-foreground hover:bg-secondary'11 unmodified linesreturn (<buttononClick={onClick}title={item.label}aria-current={active ? 'page' : undefined}className={`w-10 h-10 rounded-lg flex items-center justify-center transition-smooth group relative ${active? 'bg-primary/15 text-primary': 'text-muted-foreground hover:text-foreground hover:bg-secondary'2 unmodified lines<div className="w-5 h-5">{item.icon}</div>{/* Tooltip */}<span className="absolute left-full ml-2 px-2 py-1 text-xs font-medium bg-popover text-popover-foreground border border-border rounded-md opacity-0 group-hover:opacity-100 pointer-events-none whitespace-nowrap z-50 transition-opacity">{item.label}</span>{/* Active indicator */}{active && (7 unmodified lines8910111213147 unmodified lines2223242526272814 unmodified lines434445464748497 unmodified lines575859606162635 unmodified lines697071727374757681 unmodified lines1581591601611621631641651661671681691701711721731741751764 unmodified lines1811821831841851861871881891901911921931941955 unmodified lines20120220320420520620720820921021121221321421521621721821922022122222311 unmodified lines2352362372382392402412422432442 unmodified lines2472482492502512522537 unmodified lineslabel: stringicon: React.ReactNodepriority: boolean // Show in mobile bottom barrequiresGateway?: boolean}interface NavGroup {7 unmodified linesid: 'core',items: [{ id: 'overview', label: 'Overview', icon: <OverviewIcon />, priority: true },{ id: 'agents', label: 'Agents', icon: <AgentsIcon />, priority: true, requiresGateway: true },{ id: 'tasks', label: 'Tasks', icon: <TasksIcon />, priority: true },{ id: 'sessions', label: 'Sessions', icon: <SessionsIcon />, priority: false },],14 unmodified lineslabel: 'AUTOMATE',items: [{ id: 'cron', label: 'Cron', icon: <CronIcon />, priority: false },{ id: 'spawn', label: 'Spawn', icon: <SpawnIcon />, priority: false, requiresGateway: true },{ id: 'webhooks', label: 'Webhooks', icon: <WebhookIcon />, priority: false },{ id: 'alerts', label: 'Alerts', icon: <AlertIcon />, priority: false },{ id: 'github', label: 'GitHub', icon: <GitHubIcon />, priority: false },7 unmodified lines{ id: 'audit', label: 'Audit', icon: <AuditIcon />, priority: false },{ id: 'history', label: 'History', icon: <HistoryIcon />, priority: false },{ id: 'gateways', label: 'Gateways', icon: <GatewaysIcon />, priority: false },{ id: 'gateway-config', label: 'Config', icon: <GatewayConfigIcon />, priority: false, requiresGateway: true },{ id: 'integrations', label: 'Integrations', icon: <IntegrationsIcon />, priority: false },{ id: 'super-admin', label: 'Super Admin', icon: <SuperAdminIcon />, priority: false },{ id: 'settings', label: 'Settings', icon: <SettingsIcon />, priority: false },5 unmodified linesconst allNavItems = navGroups.flatMap(g => g.items)export function NavRail() {const { activeTab, setActiveTab, connection, dashboardMode, sidebarExpanded, collapsedGroups, toggleSidebar, toggleGroup } = useMissionControl()const isLocal = dashboardMode === 'local'// Keyboard shortcut: [ to toggle sidebaruseEffect(() => {81 unmodified lines}`}><div className={`flex flex-col ${sidebarExpanded ? 'gap-0.5 px-2' : 'items-center gap-1'}`}>{group.items.map((item) => {const disabled = isLocal && item.requiresGatewayreturn (<NavButtonkey={item.id}item={item}active={activeTab === item.id}expanded={sidebarExpanded}disabled={disabled}onClick={() => { if (!disabled) setActiveTab(item.id) }}/>)})}</div></div></div>4 unmodified lines<div className={`shrink-0 py-3 flex ${sidebarExpanded ? 'px-3 items-center gap-2' : 'flex-col items-center'}`}><divclassName={`w-2.5 h-2.5 rounded-full shrink-0 ${isLocal? 'bg-blue-500': connection.isConnected ? 'bg-green-500 pulse-dot' : 'bg-red-500'}`}title={isLocal ? 'Local Mode' : connection.isConnected ? 'Gateway connected' : 'Gateway disconnected'}/>{sidebarExpanded && (<span className="text-xs text-muted-foreground truncate">{isLocal ? 'Local Mode' : connection.isConnected ? 'Connected' : 'Disconnected'}</span>)}</div>5 unmodified lines)}function NavButton({ item, active, expanded, disabled, onClick }: {item: NavItemactive: booleanexpanded: booleandisabled?: booleanonClick: () => void}) {const disabledClass = disabled ? 'opacity-40 pointer-events-none' : ''const tooltipLabel = disabled ? `${item.label} (Requires gateway)` : item.labelif (expanded) {return (<buttononClick={onClick}aria-current={active ? 'page' : undefined}aria-disabled={disabled || undefined}className={`w-full flex items-center gap-2 px-2 py-1.5 rounded-lg text-left transition-smooth relative ${disabledClass} ${active? 'bg-primary/15 text-primary': 'text-muted-foreground hover:text-foreground hover:bg-secondary'11 unmodified linesreturn (<buttononClick={onClick}title={tooltipLabel}aria-current={active ? 'page' : undefined}aria-disabled={disabled || undefined}className={`w-10 h-10 rounded-lg flex items-center justify-center transition-smooth group relative ${disabledClass} ${active? 'bg-primary/15 text-primary': 'text-muted-foreground hover:text-foreground hover:bg-secondary'2 unmodified lines<div className="w-5 h-5">{item.icon}</div>{/* Tooltip */}<span className="absolute left-full ml-2 px-2 py-1 text-xs font-medium bg-popover text-popover-foreground border border-border rounded-md opacity-0 group-hover:opacity-100 pointer-events-none whitespace-nowrap z-50 transition-opacity">{tooltipLabel}</span>{/* Active indicator */}{active && (
12 unmodified lines1314151617181920212223242526320 unmodified lines34734834935035135235312 unmodified lines}export function MemoryBrowserPanel() {const {memoryFiles,selectedMemoryFile,memoryContent,setMemoryFiles,setSelectedMemoryFile,setMemoryContent} = useMissionControl()const [isLoading, setIsLoading] = useState(false)const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set())320 unmodified lines<div className="border-b border-border pb-4"><h1 className="text-3xl font-bold text-foreground">Memory Browser</h1><p className="text-muted-foreground mt-2">Explore ClawdBot's knowledge files and memory structure</p>{/* Tab Navigation */}12 unmodified lines13141516171819202122232425262728320 unmodified lines34935035135235335435535635712 unmodified lines}export function MemoryBrowserPanel() {const {memoryFiles,selectedMemoryFile,memoryContent,dashboardMode,setMemoryFiles,setSelectedMemoryFile,setMemoryContent} = useMissionControl()const isLocal = dashboardMode === 'local'const [isLoading, setIsLoading] = useState(false)const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set())320 unmodified lines<div className="border-b border-border pb-4"><h1 className="text-3xl font-bold text-foreground">Memory Browser</h1><p className="text-muted-foreground mt-2">{isLocal? 'Browse and manage local knowledge files and memory': 'Explore knowledge files and memory structure'}</p>{/* Tab Navigation */}
84 unmodified lines85868788899051 unmodified lines1421431441451461471481498 unmodified lines1581591601611621631641651661671681691701711723 unmodified lines17617717817918018118284 unmodified lineslet toolUses = 0let inputTokens = 0let outputTokens = 0let firstMessageAt: string | null = nulllet lastMessageAt: string | null = nulllet lastUserPrompt: string | null = null51 unmodified linesconst usage = entry.message.usageif (usage) {inputTokens += (usage.input_tokens || 0)+ (usage.cache_read_input_tokens || 0)+ (usage.cache_creation_input_tokens || 0)outputTokens += (usage.output_tokens || 0)}8 unmodified linesif (!sessionId) return null// Estimate costconst pricing = (model && MODEL_PRICING[model]) || DEFAULT_PRICINGconst estimatedCost = inputTokens * pricing.input + outputTokens * pricing.output// Determine if activeconst isActive = lastMessageAt? (Date.now() - new Date(lastMessageAt).getTime()) < ACTIVE_THRESHOLD_MS: falsereturn {sessionId,projectSlug,3 unmodified linesuserMessages,assistantMessages,toolUses,inputTokens,outputTokens,estimatedCost: Math.round(estimatedCost * 10000) / 10000,firstMessageAt,84 unmodified lines858687888990919251 unmodified lines1441451461471481491501518 unmodified lines1601611621631641651661671681691701711721731741751761771781791801813 unmodified lines18518618718818919019184 unmodified lineslet toolUses = 0let inputTokens = 0let outputTokens = 0let cacheReadTokens = 0let cacheCreationTokens = 0let firstMessageAt: string | null = nulllet lastMessageAt: string | null = nulllet lastUserPrompt: string | null = null51 unmodified linesconst usage = entry.message.usageif (usage) {inputTokens += (usage.input_tokens || 0)cacheReadTokens += (usage.cache_read_input_tokens || 0)cacheCreationTokens += (usage.cache_creation_input_tokens || 0)outputTokens += (usage.output_tokens || 0)}8 unmodified linesif (!sessionId) return null// Estimate cost (cache reads = 10% of input, cache creation = 125% of input)const pricing = (model && MODEL_PRICING[model]) || DEFAULT_PRICINGconst estimatedCost =inputTokens * pricing.input +cacheReadTokens * pricing.input * 0.1 +cacheCreationTokens * pricing.input * 1.25 +outputTokens * pricing.output// Determine if activeconst isActive = lastMessageAt? (Date.now() - new Date(lastMessageAt).getTime()) < ACTIVE_THRESHOLD_MS: false// Store total input tokens (including cache) for displayconst totalInputTokens = inputTokens + cacheReadTokens + cacheCreationTokensreturn {sessionId,projectSlug,3 unmodified linesuserMessages,assistantMessages,toolUses,inputTokens: totalInputTokens,outputTokens,estimatedCost: Math.round(estimatedCost * 10000) / 10000,firstMessageAt,
30 unmodified lines3132333435363730 unmodified linestempLogsDir: process.env.CLAWDBOT_TMP_LOG_DIR || '',memoryDir:process.env.OPENCLAW_MEMORY_DIR ||(openclawHome ? path.join(openclawHome, 'memory') : ''),soulTemplatesDir:process.env.OPENCLAW_SOUL_TEMPLATES_DIR ||(openclawHome ? path.join(openclawHome, 'templates', 'souls') : ''),30 unmodified lines313233343536373830 unmodified linestempLogsDir: process.env.CLAWDBOT_TMP_LOG_DIR || '',memoryDir:process.env.OPENCLAW_MEMORY_DIR ||(openclawHome ? path.join(openclawHome, 'memory') : '') ||path.join(defaultDataDir, 'memory'),soulTemplatesDir:process.env.OPENCLAW_SOUL_TEMPLATES_DIR ||(openclawHome ? path.join(openclawHome, 'templates', 'souls') : ''),
250 unmodified lines251252253254255256131 unmodified lines388389390391392393250 unmodified lines}interface MissionControlStore {// WebSocket & Connectionconnection: ConnectionStatuslastMessage: any131 unmodified linesexport const useMissionControl = create<MissionControlStore>()(subscribeWithSelector((set, get) => ({// Connection stateconnection: {isConnected: false,250 unmodified lines251252253254255256257258259260261262263264265266131 unmodified lines398399400401402403404405406407408409410411412413250 unmodified lines}interface MissionControlStore {// Dashboard Mode (local vs full gateway)dashboardMode: 'full' | 'local'gatewayAvailable: booleanbannerDismissed: booleansubscription: { type: string; rateLimitTier?: string } | nullsetDashboardMode: (mode: 'full' | 'local') => voidsetGatewayAvailable: (available: boolean) => voiddismissBanner: () => voidsetSubscription: (sub: { type: string; rateLimitTier?: string } | null) => void// WebSocket & Connectionconnection: ConnectionStatuslastMessage: any131 unmodified linesexport const useMissionControl = create<MissionControlStore>()(subscribeWithSelector((set, get) => ({// Dashboard ModedashboardMode: 'full' as const,gatewayAvailable: true,bannerDismissed: false,subscription: null,setDashboardMode: (mode) => set({ dashboardMode: mode }),setGatewayAvailable: (available) => set({ gatewayAvailable: available }),dismissBanner: () => set({ bannerDismissed: true }),setSubscription: (sub) => set({ subscription: sub }),// Connection stateconnection: {isConnected: false,