React Web Dashboard
Comprehensive technical guide to the DepthSight web dashboard — architecture, component hierarchy, state management, API layer, routing, i18n, knowledge base, and key implementation patterns.
The DepthSight web dashboard (frontend/) is a React 19 single-page application built with Vite 5, TypeScript 6, Tailwind CSS 4, and shadcn/ui. It serves as the primary interface for users to build trading strategies visually, monitor portfolios, analyze backtests, manage API keys, and access community features.
Source:
frontend/— 389 source files insrc/, ~2,546 lines in the API layer alone.
Architecture Overview
Provider Hierarchy
The root App.tsx (275 lines) wraps the application in a layered provider hierarchy, outermost first:
ThemeProvider (dark mode via next-themes)
-> SidebarProvider (shadcn sidebar)
-> QueryClientProvider (TanStack React Query 5)
-> BrowserRouter (react-router-dom 7)
-> AuthProvider (JWT auth context)
-> WebSocketProvider (real-time events)
-> TooltipProvider
-> ReferralTracker (URL param capture)
-> SymbolSelectionSettingsProvider
-> PortfolioModeProvider (live/paper toggle)
-> <Routes />
-> OnboardingTutorial
-> GeneDiscoveryNotification
-> PaperModeBanner
-> Toaster + Sonner
State Management
The project uses a three-tier state architecture:
1. Zustand Stores (Client State)
| Store | File | Lines | Purpose |
|---|---|---|---|
useStrategyEditorStore | stores/strategyEditorStore.ts | 1,495 | Full visual editor state — filters, entry conditions, position management, foundation weights, oracle settings. Uses immer for immutable updates. |
useAiCopilotStore | stores/aiCopilotStore.ts | 235 | AI chat session management — message history, loading states, API sync |
useAccountStore | stores/accountStore.ts | 32 | Persisted selected API key ID and market type (localStorage) |
useOnboardingStore | stores/onboardingStore.ts | 40 | Tutorial step tracking |
2. React Contexts (Cross-Cutting State)
| Context | File | Purpose |
|---|---|---|
AuthContext | context/AuthContext.tsx (184 lines) | JWT token management, login/logout, admin impersonation |
WebSocketProvider | context/WebSocketProvider.tsx (273 lines) | Real-time event stream via react-use-websocket; auto-invalidates React Query caches on events |
ThemeProvider | context/ThemeProvider.tsx | Dark/light/system theme via next-themes |
PortfolioModeContext | context/PortfolioModeContext.tsx | Live vs paper trading mode toggle |
SymbolSelectionSettingsContext | context/SymbolSelectionSettingsContext.tsx | Dynamic/static/oracle symbol selection |
3. TanStack React Query (Server State)
Centralized in lib/api.ts (2,546 lines — the largest file in the project). Every backend endpoint is wrapped as a React Query hook.
Pattern:
Sources:Key hooks (~80+ total):
| Domain | Hooks |
|---|---|
| Portfolio | usePortfolioStatus, usePositions, usePortfolioEquity |
| Strategies | useStrategies, useStrategyConfig, useStartStrategy, useStopStrategy |
| Backtests | useBacktestRuns, useRunBacktest, useBacktestRun, useBacktestKlines |
| Genetic | useGeneticRuns, useRunGeneticSearch, useFoundStrategies |
| AI | useGetChatHistory, usePostChatMessage |
| Config | useConfig, useUpdateConfig |
| Admin | useAdminGetUsers, useAdminDashboardStats |
| Misc | useKlines, useAchievements, usePhantomStats, useBlockRestrictions |
Query key strategy: authScopedQueryKey() appends a hash of the user's JWT token to every query key, ensuring complete data isolation between users.
API Client Layer
The custom API client (lib/apiClient.ts, 118 lines) handles all HTTP communication:
JWT Auto-Refresh: On 401 responses, the client attempts a silent refresh using the refresh token. Concurrent requests during refresh are queued via a pub/sub pattern — when the new token arrives, all queued requests replay with the updated authorization header.
Vite Dev Proxy
Sources:Routing & Pages
The app uses react-router-dom 7 with a flat route structure:
Public Routes (PublicLayout)
| Route | Component | Description |
|---|---|---|
/login | Login.tsx | Email/password + Google OAuth authentication |
/register | Register.tsx | User registration with referral tracking |
/forgot-password | ForgotPassword.tsx | Password reset request |
/reset-password/:token | ResetPassword.tsx | New password form |
/confirm-email/:token | ConfirmEmail.tsx | Email verification |
/s/:publicSlug | SharedReportPage.tsx | Public shared backtest report |
Protected Routes (ProtectedLayout)
| Route | Component | Description |
|---|---|---|
/ | Index.tsx | Main dashboard — portfolio overview, PnL chart, active positions |
/strategies | Strategies.tsx | Saved and running strategies list |
/editor/:id? | StrategyEditor.tsx | Visual strategy builder with AI copilot |
/analytics | Analytics.tsx | Trade analytics, phantom tracking |
/positions | Positions.tsx | Open positions with edit SL/TP |
/research | Research.tsx | Backtest history and optimization runs |
/research/backtests/:runId | BacktestViewer.tsx | Single backtest KPI detail view |
/research/optimizations/:runId | OptimizationViewerPage.tsx | Genetic optimization results |
/research/portfolio-backtests/:runId | PortfolioBacktestViewer.tsx | Multi-asset backtest view |
/discovery | GeneticCommandCenter.tsx | Genetic strategy command center |
/model-lab | MLCorePage.tsx | ML dataset creation and model training |
/logs | EventLog.tsx | Live real-time event log |
/settings | Settings.tsx | API keys, blacklist, risk management |
/account | Account.tsx | Account details, plans, billing |
/support | Support.tsx | Support tickets |
/hub | CommunityHub.tsx | Community strategy sharing |
/leaderboard | LeaderboardPage.tsx | Gamification leaderboard |
/lab | LaboratoryPage.tsx | Advanced lab features |
/affiliate-dashboard | AffiliateDashboard.tsx | Affiliate program |
Admin Routes (AdminRoute → AdminLayout)
| Route | Component | Description |
|---|---|---|
/admin | AdminDashboardPage.tsx | Platform-wide metrics |
/admin/users | AdminUsersPage.tsx | User management table |
/admin/users/:id | AdminUserDetailPage.tsx | Single user detail |
/admin/affiliates | AdminAffiliatesPage.tsx | Affiliate management |
/admin/analytics | AnalyticsPage.tsx | Admin analytics |
/admin/health | PlatformHealthPage.tsx | System health monitoring |
/admin/error-logs | ErrorLogsPage.tsx | Server error logs |
/admin/support | AdminSupportPage.tsx | Support ticket administration |
/admin/data-pipeline | DataPipelinePage.tsx | ML data pipeline status |
Component Architecture
The UI layer is organized into groups totaling 200+ components:
shadcn/ui Primitives (54 components)
All base UI components live in components/ui/ — button, card, dialog, dropdown, input, select, table, tabs, tooltip, sidebar, toast, etc. Each is customized via CSS variables and Tailwind classes with dark class strategy support.
Strategy Editor (21 components + 1,495-line store)
The most complex part of the application. Includes:
| Component | Purpose |
|---|---|
Canvas | Drag-and-drop block workspace via @xyflow/react |
BlockPalette | Sidebar with available block types (filters, indicators, conditions) |
BlockNode | Individual strategy block with parameter display |
ConnectionLine | Visual AND/OR logic connections between blocks |
AI Copilot Widget | Floating chat widget for AI-generated strategies |
FoundationWeightPanel | Weight configuration for the foundation system |
BacktestModal | Quick backtest launch from editor |
StrategyValidation | Pre-flight compatibility checker |
Research Hub (26 components)
Backtest results, KPI charts (Sharpe, Sortino, drawdown), equity curves, trade tables, genetic evolution progress, optimization comparison views.
Analytics (12 components)
PnL history charts, trade distribution, phantom trade analysis, win rate by symbol/month, consistency scoring.
Dashboard (10 components)
Portfolio value chart, open positions table, strategy performance cards, system status indicators.
WebSocket Integration
The WebSocketProvider (context/WebSocketProvider.tsx, 273 lines) maintains a persistent connection:
Event handling: Incoming events trigger React Query cache invalidation:
positions:*→queryClient.invalidateQueries(["positions"])portfolio:*→queryClient.invalidateQueries(["portfolio"])backtest_completed→queryClient.invalidateQueries(["backtests"])achievement_unlocked→ toast notificationstrategy_update→queryClient.invalidateQueries(["strategies"])
Internationalization (i18n)
Configured in src/i18n.ts (127 lines):
| Setting | Value |
|---|---|
| Library | i18next 23 + react-i18next 15 |
| Detector | Browser language auto-detect |
| Languages | en, ru |
| Fallback | en |
| Namespaces | 26 per language (common, navigation, strategies, analytics, etc.) |
| Files | 26 JSON files × 2 languages = 52 files |
Usage:
Sources:Knowledge Base (KB)
Integrated within the dashboard, the KB provides in-app help without leaving the platform:
| Component | Description |
|---|---|
articles.ts | Metadata index — 24 articles per language with id, title, category, tags |
loader.ts | Vite import.meta.glob loader for raw .md files |
KBSearch.tsx | Full-text search across all articles |
KBArticleDialog.tsx | Modal rendering via react-markdown + remark-gfm |
Article categories: Getting Started, Features (Engine, Backtest, Strategy Editor, Blocks), Billing, Advanced (AI Copilot, Oracle, TradingView, Genetic Optimization, Grid/DCA, Risk Management).
Build & Deployment
| Script | Command |
|---|---|
dev | vite --host 0.0.0.0 --force (port 5173) |
build | vite build |
lint | eslint . |
preview | vite preview |
Docker: Two Dockerfiles exist — Dockerfile for production (multi-stage, nginx) and dev variant. The Docker Compose setup maps the frontend service to port 5173 with hot-reload via volume mounts.
Path alias: @/ → ./src/ (configured in both vite.config.ts and tsconfig.json).
Key Implementation Patterns
Pattern 1: Auth-Scoped Query Keys
Sources:Prevents cache leaks between users in admin impersonation scenarios.
Pattern 2: Optimistic Updates
Backtest mutations use optimistic updates for instant UI feedback:
Sources:Pattern 3: WebSocket-Driven Cache Invalidation
Instead of polling, the WebSocket provider pushes invalidation events:
Sources:Pattern 4: Strategy Editor Serialization
The visual block tree is serialized to a JSON structure that exactly matches the backend StrategyConfig.config_data schema:
Slack Trading Agent
Interactive Slack bot with rich HTML/CSS card rendering — backtest reports, market analysis, portfolio monitoring, live trade alerts, and AI-powered strategy generation via Playwright screenshots.
Mobile PWA Client
Comprehensive technical guide to the DepthSight mobile PWA — state-machine navigation, strategy editor, AI chat, offline support via service worker, push notifications, and Google OAuth flow.