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 18 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/ — 449 source files in src/, ~3,571 lines in the API layer alone.


Architecture Overview

Rendering diagram...

Provider Hierarchy

The root App.tsx (308 lines) wraps the application in a layered provider hierarchy, outermost first:

ThemeProvider (custom light/dark/system provider)
  -> SidebarProvider (shadcn sidebar)
    -> QueryClientProvider (TanStack React Query 5)
      -> BrowserRouter (react-router-dom 7)
        -> AuthProvider (JWT auth context)
          -> WebSocketProvider (real-time events)
            -> NotificationProvider (in-app notifications)
              -> TooltipProvider
                -> ReferralTracker (URL param capture)
                  -> SymbolSelectionSettingsProvider
                    -> PortfolioModeProvider (live/paper toggle)
                      -> <Routes />
                      -> OnboardingTutorial
                      -> GeneDiscoveryNotification
                      -> Toaster

State Management

The project uses a three-tier state architecture:

1. Zustand Stores (Client State)

StoreFileLinesPurpose
useStrategyEditorStorestores/strategyEditorStore.ts1,497Full 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.ts45Tutorial step tracking

2. React Contexts (Cross-Cutting State)

ContextFilePurpose
AuthContextcontext/AuthContext.tsx (228 lines)JWT token management, login/logout, admin impersonation
WebSocketProvidercontext/WebSocketProvider.tsx (671 lines)Real-time event stream; merges pushed position/strategy/portfolio snapshots into the React Query cache (with targeted invalidation fallbacks)
ThemeProvidercontext/ThemeProvider.tsxCustom dark/light/system theme provider (localStorage-persisted, class strategy)
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 (3,571 lines). Every backend endpoint is wrapped as a React Query hook.

Pattern:

Sources:

Key hooks (160+ total):

DomainHooks
PortfoliousePortfolioStatus, usePositions, usePortfolioEquity
StrategiesuseStrategies, useStrategyConfigsList, useStartStrategy, useStopStrategy
BacktestsuseBacktestRuns, useRunBacktest, useBacktestRun, useRunPortfolioBacktest
GeneticuseGeneticRuns, useRunGeneticSearch, useFoundStrategies
AIuseGetChatHistory, usePostChatMessage
ConfiguseConfig, useUpdateConfig
AdminuseAdminGetUsers, useAdminDashboardStats
MiscuseKlines, useAchievements, usePhantomStats, useBlockRestrictions

Query key strategy: authScopedQueryKey() (in lib/queryKeys.ts) 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, 135 lines) handles all HTTP communication against the /api/v1 base URL:

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
/r/:refCodeReferralRedirect (inline in App.tsx)Referral link capture, then redirect to registration
/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
/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
/miningMiningHub.tsxTrade-mining hub and node status

Admin-Only Routes (nested AdminRoute inside the protected layout)

RouteComponentDescription
/model-labMLCorePage.tsxML dataset creation and model training
/diagnostics/foundation-visualizerFoundationVisualizerPage.tsxFoundation weights diagnostics
/hftHftDashboardPage.tsxHFT engine control dashboard

Admin Routes (AdminRoute → AdminLayout)

RouteComponentDescription
/adminAdminDashboardPage.tsxPlatform-wide metrics
/admin/plansAdminPlansPage.tsxPlan configuration editor
/admin/ai-settingsAdminAISettingsPage.tsxAI assistant settings
/admin/usersAdminUsersPage.tsxUser management table
/admin/users/:idAdminUserDetailPage.tsxSingle user detail
/admin/affiliatesAdminAffiliatesPage.tsxAffiliate management
/admin/affiliates/:idAdminAffiliateDetailPage.tsxSingle affiliate detail
/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
/admin/miningAdminMiningPage.tsxMining node administration
/admin/mining-analyticsAdminMiningAnalytics.tsxMining analytics
/admin/promoAdminPromoPage.tsxPromo campaign administration

Component Architecture

The UI layer is organized into groups totaling 200+ components:

shadcn/ui Primitives (51 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 (20 components + 1,497-line store)

The most complex part of the application. Includes:

ComponentPurpose
StrategyCanvasDrag-and-drop block workspace via @xyflow/react
ComponentPaletteSidebar with available block types (filters, indicators, conditions)
ConditionBlock / ManagementBlockIndividual strategy blocks with parameter display
BlockLinkPopoverVisual AND/OR logic connections between blocks
AI Copilot WidgetFloating chat widget for AI-generated strategies
FoundationWeightsModalWeight configuration for the foundation system
BacktestModalQuick backtest launch from editor (components/strategies)

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, 671 lines) maintains a persistent connection:

Sources:

Knowledge Base (KB)

Integrated within the dashboard, the KB provides in-app help without leaving the platform:

ComponentDescription
articles.tsMetadata index — 23 English / 20 Russian articles 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)
buildtsc --noEmit && vite build
typechecktsc --noEmit
linteslint .
previewvite preview

Docker: Two Dockerfiles exist — Dockerfile.prod (multi-stage, nginx) and Dockerfile.dev. In Docker Compose the frontend is a static nginx container served behind Caddy (no host port published); local development runs the Vite dev server on port 5173.

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: Toast-Driven Mutation Feedback

Backtest submissions report success/failure via toasts and refresh the research task list:

Sources:

Pattern 3: WebSocket-Driven Cache Updates

Instead of polling, the WebSocket provider merges pushed snapshots into the cache and invalidates only what it cannot merge:

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 (typed by BaseBlock / ConditionBlock / ManagementBlock):

Sources: