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/— ~66 source files, ~17,500 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
QueryClientProvider (TanStack React Query)
-> GoogleOAuthProvider
-> AuthProvider (JWT auth)
-> NotificationProvider (push notifications)
-> SymbolSelectionSettingsProvider
-> App
Navigation State Machine
Defined in types.ts as a Screen enum with 14 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,540 | 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 | 23 | Persisted selected API key ID (localStorage) |
React Contexts
| Context | File | Purpose |
|---|---|---|
AuthContext | contexts/AuthContext.tsx (94 lines) | User/token state, login/logout, token refresh |
AIChatContext | contexts/AIChatContext.tsx (259 lines) | Chat messages, session management, typing indicator |
NotificationContext | contexts/NotificationContext.tsx (182 lines) | In-app notifications + push subscription state |
SymbolSelectionSettingsContext | contexts/SymbolSelectionSettingsContext.tsx (65 lines) | Symbol selection mode configuration |
API Layer
The API client (services/api.ts, 401 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 | 377 | Portfolio overview, PnL chart (Recharts), active positions list |
| Strategies | StrategiesScreen.tsx | 367 | Saved + running strategies with status badges, FAB to create new |
| Research | ResearchScreen.tsx | 194 | Backtest history with tabs for analytics |
| Notifications | NotificationsScreen.tsx | 165 | In-app notification list with read/unread state |
| AI Chat | AIChatScreen.tsx | 385 | Full chat interface with message history, strategy JSON responses |
| Editor | EditorHybridScreen.tsx → EditorScreen.tsx | 244 + 535 | 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 | 665 | Account details, plans, billing history, achievements, referrals |
| Settings | SettingsScreen.tsx | 360 | Risk management configuration |
| Auth | AuthScreen.tsx | 383 | Login/Register with Google OAuth |
| ForgotPassword | ForgotPasswordScreen.tsx | 120 | Password reset request |
| ResetPassword | ResetPasswordScreen.tsx | 147 | New password form |
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,021 | The largest file — comprehensive block parameter editor with dynamic inputs for every block type |
BlockItem | 182 | Single block card with drag handle (via @dnd-kit) |
ComponentPaletteModal | 227 | Block type picker organized by category |
InitializationBlock | 224 | Position sizing, SL/TP, direction configuration |
BlockLinkPopover | 102 | Dynamic value linking between blocks |
FoundationWeightsModal | 177 | Foundation weight configuration |
CollapsibleSection | 41 | Collapsible UI sections |
Block Types
Defined in constants/blockConfig.ts (334 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:
Sources:AI Chat Integration
The AI chat (contexts/AIChatContext.tsx, 259 lines + AIChatScreen.tsx, 385 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 (51 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, 116 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: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 (130 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 and returns an application JWT. The PWA stores this token in localStorage under depthsight_pwa_token.
Internationalization
| Setting | Value |
|---|---|
| Library | i18next 26 + react-i18next 17 |
| Languages | en, ru |
| Namespace | Single pwa-common |
| Translation lines | EN: 1,089, RU: 1,102 |
| Scope | Auth, Dashboard, Analytics, Strategies, Editor, AI Chat, Profile, Settings, Notifications, Achievements (33 named) |
Build & Deployment
| Script | Command |
|---|---|
dev | vite (port 5174) |
build | vite build |
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.