Frontend Applications

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.

⏱️ 13 min read📊 Level: Intermediate

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 in src/, ~2,546 lines in the API layer alone.


Architecture Overview

Rendering diagram...

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)

StoreFileLinesPurpose
useStrategyEditorStorestores/strategyEditorStore.ts1,495Full visual editor state — filters, entry conditions, position management, foundation weights, oracle settings. Uses immer for immutable updates.
useAiCopilotStorestores/aiCopilotStore.ts235AI chat session management — message history, loading states, API sync
useAccountStorestores/accountStore.ts32Persisted selected API key ID and market type (localStorage)
useOnboardingStorestores/onboardingStore.ts40Tutorial step tracking

2. React Contexts (Cross-Cutting State)

ContextFilePurpose
AuthContextcontext/AuthContext.tsx (184 lines)JWT token management, login/logout, admin impersonation
WebSocketProvidercontext/WebSocketProvider.tsx (273 lines)Real-time event stream via react-use-websocket; auto-invalidates React Query caches on events
ThemeProvidercontext/ThemeProvider.tsxDark/light/system theme via next-themes
PortfolioModeContextcontext/PortfolioModeContext.tsxLive vs paper trading mode toggle
SymbolSelectionSettingsContextcontext/SymbolSelectionSettingsContext.tsxDynamic/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):

DomainHooks
PortfoliousePortfolioStatus, usePositions, usePortfolioEquity
StrategiesuseStrategies, useStrategyConfig, useStartStrategy, useStopStrategy
BacktestsuseBacktestRuns, useRunBacktest, useBacktestRun, useBacktestKlines
GeneticuseGeneticRuns, useRunGeneticSearch, useFoundStrategies
AIuseGetChatHistory, usePostChatMessage
ConfiguseConfig, useUpdateConfig
AdminuseAdminGetUsers, useAdminDashboardStats
MiscuseKlines, 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:

Sources:

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)

RouteComponentDescription
/loginLogin.tsxEmail/password + Google OAuth authentication
/registerRegister.tsxUser registration with referral tracking
/forgot-passwordForgotPassword.tsxPassword reset request
/reset-password/:tokenResetPassword.tsxNew password form
/confirm-email/:tokenConfirmEmail.tsxEmail verification
/s/:publicSlugSharedReportPage.tsxPublic shared backtest report

Protected Routes (ProtectedLayout)

RouteComponentDescription
/Index.tsxMain dashboard — portfolio overview, PnL chart, active positions
/strategiesStrategies.tsxSaved and running strategies list
/editor/:id?StrategyEditor.tsxVisual strategy builder with AI copilot
/analyticsAnalytics.tsxTrade analytics, phantom tracking
/positionsPositions.tsxOpen positions with edit SL/TP
/researchResearch.tsxBacktest history and optimization runs
/research/backtests/:runIdBacktestViewer.tsxSingle backtest KPI detail view
/research/optimizations/:runIdOptimizationViewerPage.tsxGenetic optimization results
/research/portfolio-backtests/:runIdPortfolioBacktestViewer.tsxMulti-asset backtest view
/discoveryGeneticCommandCenter.tsxGenetic strategy command center
/model-labMLCorePage.tsxML dataset creation and model training
/logsEventLog.tsxLive real-time event log
/settingsSettings.tsxAPI keys, blacklist, risk management
/accountAccount.tsxAccount details, plans, billing
/supportSupport.tsxSupport tickets
/hubCommunityHub.tsxCommunity strategy sharing
/leaderboardLeaderboardPage.tsxGamification leaderboard
/labLaboratoryPage.tsxAdvanced lab features
/affiliate-dashboardAffiliateDashboard.tsxAffiliate program

Admin Routes (AdminRoute → AdminLayout)

RouteComponentDescription
/adminAdminDashboardPage.tsxPlatform-wide metrics
/admin/usersAdminUsersPage.tsxUser management table
/admin/users/:idAdminUserDetailPage.tsxSingle user detail
/admin/affiliatesAdminAffiliatesPage.tsxAffiliate management
/admin/analyticsAnalyticsPage.tsxAdmin analytics
/admin/healthPlatformHealthPage.tsxSystem health monitoring
/admin/error-logsErrorLogsPage.tsxServer error logs
/admin/supportAdminSupportPage.tsxSupport ticket administration
/admin/data-pipelineDataPipelinePage.tsxML 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:

ComponentPurpose
CanvasDrag-and-drop block workspace via @xyflow/react
BlockPaletteSidebar with available block types (filters, indicators, conditions)
BlockNodeIndividual strategy block with parameter display
ConnectionLineVisual AND/OR logic connections between blocks
AI Copilot WidgetFloating chat widget for AI-generated strategies
FoundationWeightPanelWeight configuration for the foundation system
BacktestModalQuick backtest launch from editor
StrategyValidationPre-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:

Sources:

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 notification
  • strategy_update → queryClient.invalidateQueries(["strategies"])

Internationalization (i18n)

Configured in src/i18n.ts (127 lines):

SettingValue
Libraryi18next 23 + react-i18next 15
DetectorBrowser language auto-detect
Languagesen, ru
Fallbacken
Namespaces26 per language (common, navigation, strategies, analytics, etc.)
Files26 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:

ComponentDescription
articles.tsMetadata index — 24 articles per language with id, title, category, tags
loader.tsVite import.meta.glob loader for raw .md files
KBSearch.tsxFull-text search across all articles
KBArticleDialog.tsxModal 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

ScriptCommand
devvite --host 0.0.0.0 --force (port 5173)
buildvite build
linteslint .
previewvite 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:

Sources: