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.
The DepthSight PWA (pwa/) is a React 19 mobile-optimized Progressive Web Application built with Vite 8, TypeScript 6, and Tailwind CSS 4. It provides full trading platform functionality on mobile devices — portfolio monitoring, strategy editing, backtesting, AI assistant, and push notifications — all installable as a standalone app.
Source:
pwa/— 123 source files, ~37,400 lines total.
Architecture Overview
Unlike the web dashboard which uses react-router, the PWA employs a state-machine navigation pattern — the activeScreen state determines which component is rendered:
Provider Hierarchy
ErrorBoundary
-> QueryClientProvider (TanStack React Query)
-> GoogleOAuthProvider
-> AuthProvider (JWT auth)
-> App (I18nextProvider)
-> NotificationProvider (push notifications)
-> AIChatProvider
-> SymbolSelectionSettingsProvider
-> MainAppLayout (authed) / AuthScreen (guest)
Navigation State Machine
Defined in types.ts as a Screen enum with 13 screens:
Bottom navigation is only shown for the 4 primary screens: Dashboard, Strategies, Research, Notifications.
State Management
Zustand Stores
| Store | File | Lines | Purpose |
|---|---|---|---|
strategyEditorStore | stores/strategyEditorStore.ts | 1,635 | Full editor state — filters, entry conditions, initialization, position management, foundation weights, symbol selection. Uses immer for immutable updates. 30+ action functions. |
accountStore | stores/accountStore.ts | 26 | Persisted selected API key ID (localStorage) |
realtimeStore | stores/realtimeStore.ts | 192 | Realtime engine push snapshots (positions/strategies) merged per-controller with seq guards — no React Query involved |
React Contexts
| Context | File | Purpose |
|---|---|---|
AuthContext | contexts/AuthContext.tsx (219 lines) | User/token state, login/logout, token refresh |
AIChatContext | contexts/AIChatContext.tsx (280 lines) | Chat messages, session management, typing indicator |
NotificationContext | contexts/NotificationContext.tsx (233 lines) | In-app notifications + push subscription state |
SymbolSelectionSettingsContext | contexts/SymbolSelectionSettingsContext.tsx (74 lines) | Symbol selection mode configuration |
API Layer
The API client (services/api.ts, 878 lines) uses a custom apiFetch<T>() function with automatic JWT refresh:
API Endpoints by Domain:
| Domain | Key Endpoints |
|---|---|
| Auth | login, register, getMe, refresh |
| Dashboard | getPortfolio, getPositions, getPortfolioEquity, closePosition |
| AI Chat | aiChat, getChatHistory, initChatSession, deleteChatSession |
| Strategies | getSavedStrategies, getRunningStrategies, startStrategy, stopStrategy, saveStrategy |
| Backtests | getBacktests, getBacktestDetails, runBacktest, getBacktestKlines |
| Account | getAccountStatus, getPlans, createPayment, resetPaperAccount |
| API Keys | addApiKey, deleteApiKey, testApiKey |
| Gamification | getAchievements, getUserAchievements, getMyGenes |
| Config | getConfig, updateConfig |
Screens (Pages)
| Screen | Component | Lines | Description |
|---|---|---|---|
| Dashboard | DashboardScreen.tsx | 723 | Portfolio overview, PnL chart (Recharts), active positions list |
| Strategies | StrategiesScreen.tsx | 718 | Saved + running strategies with status badges, FAB to create new |
| Research | ResearchScreen.tsx | 210 | Backtest history with tabs for analytics |
| Notifications | NotificationsScreen.tsx | 234 | In-app notification list with read/unread state |
| AI Chat | AIChatScreen.tsx | 448 | Full chat interface with message history, strategy JSON responses |
| Editor | EditorHybridScreen.tsx → EditorScreen.tsx | 262 + 579 | Visual strategy builder optimized for mobile touch |
| BacktestResult | (inline in App.tsx) | ~250 | KPI cards (PnL, win rate, drawdown, Sharpe), equity chart, trade table |
| Profile | ProfileScreen.tsx | 709 | Account details, plans, billing history, achievements, referrals |
| Settings | SettingsScreen.tsx | 429 | Risk management configuration |
| Auth | AuthScreen.tsx | 589 | Login/Register with Google OAuth |
| ForgotPassword | ForgotPasswordScreen.tsx | 132 | Password reset request |
| ResetPassword | ResetPasswordScreen.tsx | 162 | New password form |
| Analytics | AnalyticsScreen.tsx | 442 | Trade analytics with charts and filters |
| Mining | MiningScreen.tsx | 817 | Trade-mining status, quests, and node wallet |
| ConfirmEmail | ConfirmEmailScreen.tsx | 129 | Rendered when a confirm-email/{token} URL is detected (not part of the Screen enum) |
Strategy Editor (Mobile)
The mobile strategy editor is a touch-optimized version of the web editor with the same block system:
Editor Components
| Component | Lines | Purpose |
|---|---|---|
BlockInspectorModal | 2,052 | The largest file — comprehensive block parameter editor with dynamic inputs for every block type |
BlockItem | 197 | Single block card with drag handle (via @dnd-kit) |
ComponentPaletteModal | 247 | Block type picker organized by category |
InitializationBlock | 235 | Position sizing, SL/TP, direction configuration |
DynamicInputPicker | 220 | Context-aware input type picker for block parameters |
FoundationWeightsModal | 193 | Foundation weight configuration |
BlockLinkPopover | 110 | Dynamic value linking between blocks |
DynamicValueInput | 118 | Renders linked or literal parameter values |
CollapsibleSection | 46 | Collapsible UI sections |
Block Types
Defined in constants/blockConfig.ts (337 lines) — ~40+ block types organized into:
| Category | Examples |
|---|---|
| Foundations | Orderbook, Pattern, Trend, Level, RoundNumber, TapeAcceleration, MarketActivity, VolumeConfirmation, ReturnToLevel |
| Filters | TradingSession, TimeFilter, TrendFilter, VolatilityFilter, NATRFilter, ADXFilter, BTCStateFilter, Correlation |
| Indicators | RSI, MACD, Bollinger Bands, Stochastic, EMA, SMA, ATR, ADX |
| Entry Conditions | MA Cross, Price vs Level, Volume Confirmation, Classic Pattern, Level Touch, Volatility Squeeze |
| Management | Trailing Stop, Breakeven, Partial Exit, Scale In, DCA, Grid |
Strategy Serialization
The editor serializes blocks to a JSON structure matching the backend schema via the store's toJson():
AI Chat Integration
The AI chat (contexts/AIChatContext.tsx, 280 lines + AIChatScreen.tsx, 448 lines) allows mobile users to:
- Generate strategies from text descriptions — sends prompt to backend, receives strategy JSON, loads into editor.
- Modify strategies — provides natural language instructions to adjust existing strategy parameters.
- Analyze backtests — requests performance explanations and improvement suggestions.
The geminiService.ts (60 lines) is a thin wrapper — the actual AI logic runs on the backend via /api/v1/ai/chat.
Service Worker & Offline Support
The PWA service worker (public/sw.js, 177 lines) implements a hybrid caching strategy:
Cache Strategy
| Request Type | Strategy | Behavior |
|---|---|---|
| Navigation (HTML) | Network First | Try network, fallback to cached index.html |
| Static assets (JS/CSS) | Cache First | Serve from cache, update from network in background |
API calls (/api/v1) | Network Only | Never cached — always fresh data |
Lifecycle
Sources:The app-shell cache version is depthsight-cache-v9 (CACHE_NAME); older caches are dropped on activate.
Update Flow
1. New SW detected → "Update available" toast
2. User taps "Reload" → postMessage({ type: "SKIP_WAITING" })
3. SW activates → clients.claim()
4. Page reloads automatically
Push Notifications
Defined in services/notificationService.ts (209 lines):
- Fetches VAPID public key from
/api/v1/notifications/vapid_public_key. - Subscribes via
PushManager.subscribe({ userVisibleOnly: true, applicationServerKey }). - Sends subscription to
/api/v1/users/subscribe_push. - On push event — shows browser notification with icon + vibration pattern.
Google OAuth Flow
Sources:The Google credential (JWT) is sent to the backend, which validates it (with optional 2FA challenge) and returns an application JWT. The PWA stores this token in localStorage under authToken (the refresh token is stored under refreshToken and rotated by refreshAuthToken).
Internationalization
| Setting | Value |
|---|---|
| Library | i18next 26 + react-i18next 17 |
| Languages | en, ru |
| Namespace | Single pwa-common |
| Translation lines | EN: 1,474, RU: 1,488 |
| Scope | Auth, Dashboard, Analytics, Strategies, Editor, AI Chat, Profile, Settings, Notifications, Achievements (33 named) |
Build & Deployment
| Script | Command |
|---|---|
dev | vite (port 5174) |
build | tsc --noEmit && vite build |
typecheck | tsc --noEmit |
lint | eslint . |
preview | vite preview |
Production base path: base: "/pwa/" — deployed behind nginx at /pwa/ subpath.
Vite dev proxy:
Sources:Web App Manifest:
Sources: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.
Database Schema and Models
Comprehensive reference of all PostgreSQL tables, SQLAlchemy ORM models, relationships, indexes, and constraints managed by Alembic migrations.