* Add UserProvider to App component and enhance user data fetching logic - Integrated UserProvider into the App component to manage user state. - Updated UserProvider to fetch current user data on token availability and handle token expiration by clearing the token on fetch failure. - Improved user data fetching logic for better error handling and user experience. * Enhance Telegram connection handling and error management - Added logic to handle Telegram account mismatch, providing user feedback and resetting connection state. - Improved user verification during authentication to ensure the logged-in account matches the Telegram account. - Refactored connection status checks and error handling for better user experience. - Introduced a method to clear session and disconnect when account mismatch occurs. - Updated polling mechanism for authentication status to ensure timely updates. This update improves the robustness of the Telegram connection process and enhances user feedback during authentication failures. * ran prettier * Refactor socket and auth state management for user-specific handling - Updated socket state management to support multiple users by introducing user-specific selectors and actions. - Refactored connection status handling in the socket service to dispatch user-specific status updates. - Enhanced onboarding state management to track completion per user, allowing for more granular control. - Introduced new selectors for socket and auth states to improve readability and maintainability. - Updated relevant components to utilize the new user-specific state management. This update improves the application's ability to handle multiple users and enhances the overall user experience during onboarding and socket connections. * Enhance MTProto client session management and introduce user-specific session handling - Updated the MTProtoService to manage sessions per user by storing session data under a user-specific key. - Modified the initialize method to accept a userId parameter, allowing for user-specific session initialization and management. - Improved session loading and saving logic to ensure proper handling of user sessions. - Added a utility function to generate session keys based on userId for better maintainability. This update enhances the application's ability to handle multiple user sessions effectively. * Refactor Telegram state management for user-specific handling - Introduced user-specific state management in the Telegram store, allowing for better handling of multiple users. - Updated selectors to retrieve state based on the current user, improving data encapsulation and reducing global state dependencies. - Enhanced reducers and thunks to ensure actions are dispatched with user context, maintaining user-specific data integrity. - Modified persistence configuration to store Telegram state scoped by user, ensuring isolated state management. This update significantly improves the application's ability to manage multiple user sessions effectively and enhances overall user experience. * Enhance MTProtoService connection handling with user-specific initialization - Updated the checkConnection method to accept an optional userId parameter, allowing for user-specific connection initialization. - Modified the connection logic to ensure proper initialization only occurs when a userId is provided, improving session management. - Refactored related thunks to use a consistent naming convention for userId parameters, enhancing code clarity. This update improves the handling of user sessions in the MTProtoService, aligning with recent enhancements in user-specific state management. * Refactor Telegram connection handling for user-specific management - Updated the TelegramConnectionModal to utilize user-specific identifiers for connection status and authentication processes, enhancing session management. - Refactored related components and selectors to ensure userId is consistently passed and utilized, improving clarity and maintainability. - Enhanced the ConnectionsPanel and ConnectStep to check for saved sessions based on userId, allowing for better handling of multiple user connections. This update significantly improves the application's ability to manage user-specific Telegram connections and enhances the overall user experience. * Refactor Telegram connection logic to simplify session management - Removed unnecessary userId checks and localStorage interactions from ConnectionsPanel and ConnectStep components, streamlining the connection status determination. - Updated MTProtoService to manage session data through Redux instead of localStorage, enhancing consistency and maintainability. - Improved session loading and saving logic to focus solely on Redux state, ensuring better integration with user-specific session handling. This update enhances the clarity and efficiency of the Telegram connection management process, aligning with recent improvements in user-specific state management. * Update CLAUDE.md to clarify localStorage usage and emphasize Redux for state management - Revised documentation to discourage the use of localStorage and sessionStorage for app state, advocating for Redux and Redux Persist instead. - Added guidelines for removing existing localStorage usage and migrating relevant data to Redux. - Updated service layer documentation to reflect changes in session management, specifying that session data is now stored in Redux rather than localStorage. - Enhanced clarity on deep link handling and the prevention of infinite reload loops. This update aligns with recent improvements in user-specific state management and reinforces best practices for state handling. * Enhance onboarding process with error handling and API integration - Updated the Onboarding component to include an API call for marking onboarding as complete, with error handling to provide user feedback. - Refactored the GetStartedStep component to support asynchronous completion handling, including loading state and error messages. - Introduced a new onboardingComplete method in the userApi service to facilitate the onboarding completion process. This update improves the user experience during onboarding by ensuring proper error management and feedback. * Enhance TelegramConnectionModal with socket connection management and improved initialization flow - Integrated socket connection handling in the TelegramConnectionModal to ensure the socket is connected when the modal opens, enhancing real-time features. - Refactored the initialization logic to streamline the connection process, including user verification and error handling. - Introduced a reference to track the QR code flow state, preventing multiple initiations and improving user experience during authentication. This update improves the reliability of the Telegram connection process and enhances user feedback during the onboarding experience. * Refactor Telegram connection checks for improved logic consistency - Updated the ConnectionsPanel and ConnectStep components to refine the logic for determining if a Telegram connection is established, ensuring that both session string and authentication status are required for a valid connection. - Simplified className definitions in the UI components for better readability and maintainability. This update enhances the clarity of connection status checks and improves the overall user experience during the onboarding process. * Refactor Telegram authentication flow and improve error handling - Simplified the TelegramLoginButton component by removing complex authentication logic and replacing it with a direct link to the Telegram bot for login. - Enhanced the Login page to consume a login token from the URL, providing better error handling and user feedback during the authentication process. - Introduced a new API service for consuming login tokens, ensuring secure retrieval of JWT tokens from the backend. This update streamlines the authentication experience and improves error management, enhancing overall user experience during login.
11 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Summary
Cross-platform crypto community communication platform built with Tauri v2 (React 19 + Rust). Targets desktop (Windows, macOS) and mobile (Android, iOS). Features deep Telegram integration via MTProto, real-time Socket.io communication, and an MCP (Model Context Protocol) tool system for AI-driven Telegram interactions.
App Theme & Design System
Design Philosophy: Premium, sophisticated crypto platform with calm, trustworthy aesthetic.
Color Palette
- Primary: Ocean blue (
#4A83DD) optimized for dark backgrounds - Sage: Success green (
#4DC46F) for growth indicators - Amber: Warning (
#E8A838) for attention states - Coral: Error (
#F56565) soft professional red - Canvas: Background layers (
#FAFAF9to#D4D4D1) with subtle warmth - Market Colors: Bullish green, bearish red, Bitcoin orange, Ethereum purple
Typography
- Primary: Inter (premium font stack)
- Display: Cabinet Grotesk for headings
- Mono: JetBrains Mono for code
- Scale: Sophisticated sizing with negative letter spacing for elegance
Component System
- Shadows: Glow effects, subtle to float depth levels
- Animations: Fade-in, slide-in, scale-in with cubic-bezier easing
- Border Radius: Smooth system from
xs(0.25rem) to5xl(2rem) - Spacing: Extended scale including custom values (4.5, 13, 15, etc.)
Current UI State
- Uses HashRouter (not BrowserRouter) as seen in
App.tsx:1 - 153 TypeScript files total in src/
- Sophisticated Tailwind config with custom color system and animations
Commands
# Frontend dev server only (port 1420)
npm run dev
# Desktop dev with hot-reload (starts Vite + Tauri)
npm run tauri dev
# Production build (TypeScript compile + Vite build + Tauri bundle)
npm run tauri build
# Debug build with .app bundle (required for deep link testing on macOS)
npm run tauri build -- --debug --bundles app
# Android
npm run tauri android dev
npm run tauri android build
# iOS
npm run tauri ios dev
npm run tauri ios build
# Rust checks
cargo check --manifest-path src-tauri/Cargo.toml
cargo clippy --manifest-path src-tauri/Cargo.toml
No test framework is currently configured. No ESLint or Prettier configuration exists in the repo.
Architecture
Provider Chain (App.tsx)
The app wraps in this order: Redux Provider → PersistGate → SocketProvider → TelegramProvider → HashRouter → AppRoutes. Note: Now uses HashRouter instead of BrowserRouter. This ordering matters because Socket.io and Telegram providers depend on Redux auth state.
State Management (Redux Toolkit + Persist)
State lives in src/store/ using Redux Toolkit slices:
- authSlice — JWT token, onboarding completion flag (persisted)
- userSlice — user profile
- socketSlice — connection status, socket ID
- telegramSlice — connection/auth status, chats, messages, threads (selectively persisted; loading/error states excluded)
Redux Persist stores auth and telegram state (storage backend is configurable; default uses localStorage). The telegram slice has a complex nested structure in src/store/telegram/ with separate files for types, reducers, extraReducers, and thunks.
LocalStorage
- Do not use
localStorage(orsessionStorage) for app state or feature logic. Use Redux (and Redux Persist where needed) instead. - Remove any existing
localStorageusage when touching related code. User-scoped data (auth, onboarding, Telegram session, socket state) lives in Redux, keyed by user id where applicable. Telegram session is intelegram.byUser[userId].sessionString, not localStorage. - Exceptions: Redux-persist may use a localStorage-backed storage adapter by default; that is the persistence layer, not app logic. Any other remaining usage (e.g. deep-link
deepLinkHandledflag) should be migrated to Redux or similar when that code is modified. - General rule: Avoid adding new
localStorageorsessionStorageusage; prefer Redux and remove existing usage when you work on affected areas.
Service Layer (Singletons)
- mtprotoService (
src/services/mtprotoService.ts) — Telegram MTProto client viatelegramnpm package. Session stored in Redux (telegram.byUser[userId].sessionString), not localStorage. Auto-retries FLOOD_WAIT up to 60s. - socketService (
src/services/socketService.ts) — Socket.io client. Auth token passed in socketauthobject (not query string). Transports: polling first, then WebSocket. - apiClient (
src/services/apiClient.ts) — HTTP client for REST backend.
MCP System (src/lib/mcp/)
Model Context Protocol implementation for AI tool execution over Socket.io:
transport.ts— Socket.io JSON-RPC 2.0 transport with 30s timeouttelegram/server.ts— TelegramMCPServer manages 99 tool definitionstelegram/tools/— Individual tool files (one per Telegram API operation)- Tools use
big-integerlibrary for Telegram's large integer IDs
Routing (src/AppRoutes.tsx)
/ → Welcome (public)
/login → Login (public)
/onboarding → Onboarding (protected, requires auth, not yet onboarded)
/home → Home (protected, requires auth + onboarded)
* → DefaultRedirect (routes based on auth state)
PublicRoute redirects authenticated users away. ProtectedRoute enforces auth and optionally onboarding status.
Deep Link Auth Flow
Web-to-desktop handoff using outsourced:// URL scheme:
- User authenticates in browser
- Browser redirects to
outsourced://auth?token=<loginToken> - Tauri catches the deep link, Rust
exchange_tokencommand calls backend viareqwest(bypasses CORS) - Backend returns
sessionToken+ user object - App stores session in Redux, navigates to onboarding/home
Key file: src/utils/desktopDeepLinkListener.ts (lazy-loaded in main.tsx). Uses a deepLinkHandled flag to prevent infinite reload loops. Deep links do NOT work in tauri dev on macOS — must use built .app bundle.
Rust Backend (src-tauri/src/lib.rs)
Minimal — two Tauri commands:
greet— demo commandexchange_token— CORS-free HTTP POST to backend for token exchange
Deep link plugin registered at setup. register_all() called only on Windows/Linux (panics on macOS).
Environment Variables
Set in .env (Vite exposes VITE_* prefixed vars):
| Variable | Purpose |
|---|---|
VITE_BACKEND_URL |
Backend API URL (default: http://localhost:5005) |
VITE_TELEGRAM_API_ID |
Telegram MTProto API ID |
VITE_TELEGRAM_API_HASH |
Telegram MTProto API hash |
VITE_TELEGRAM_BOT_USERNAME |
Telegram bot username |
VITE_TELEGRAM_BOT_ID |
Telegram bot numeric ID |
VITE_DEBUG |
Debug mode flag |
Production defaults are in src/utils/config.ts.
Recent Changes (Last 24 Hours)
Key updates from recent commits:
Major Additions
- Settings Modal System (
60054d8): Complete URL-based settings modal with clean white design- Modal infrastructure with backdrop blur and center positioning
- User profile integration with Redux state management
- Connection management panel reusing onboarding components
- URL routing for
/settingsand/settings/connectionspaths - Mobile responsive design with accessibility features
- Type Casting Helpers: Added for Telegram MTProto API (
5a0425c) - Onboarding Refactor: Updated connection logic and steps (
bd1d240) - MCP Tools Enhancement: Improved type safety and consistency across Telegram tools (
d0e1191,86cc53a) - App Structure: Refactored MCPProvider integration (
d7d848d) - Big Integer Support: Consistent handling across all Telegram MCP tools (
0abed4d)
Design System Updates
- Settings Modal UI: Clean 520px white modal contrasting with glass morphism theme
- Animations: 200ms entry animations, 250ms panel transitions, chevron hover effects
- Lottie Animations: Integrated into onboarding flow (
334673e) - Connection Components: Added Telegram and Gmail connection indicators
- Routing: Switched to HashRouter for better desktop app compatibility
- Theme: Implemented sophisticated color system with premium crypto aesthetic
Component Structure
- 165+ TypeScript files across
src/directory (added settings modal system) - Settings Modal System: Complete modal infrastructure in
src/components/settings/- SettingsModal.tsx - Main container with URL routing
- SettingsLayout.tsx - Modal wrapper with createPortal
- SettingsHome.tsx - Main menu with profile and navigation
- ConnectionsPanel.tsx - Connection management with status indicators
- Hooks: useSettingsNavigation.ts, useSettingsAnimation.ts
- Onboarding Flow: Multi-step process with privacy, analytics, and connection steps
- Authentication: Web-to-desktop handoff using
outsourced://scheme - Connection Management: Telegram MTProto and Socket.io integration
Key Patterns
- No localStorage: Avoid
localStorageandsessionStorage; use Redux (and persist) for app state. Remove any direct usage when working on affected code. - Modal System: Settings modal uses
createPortalpattern with URL-based routing. Clean white design (not glass morphism) for system settings. Navigate with/settingsand/settings/connectionspaths. - Component Reuse: Connection management reuses
connectOptionsarray and components from onboarding flow. Maintains consistent UX patterns across features. - Redux Integration: Settings modal integrates with existing slices - auth for logout, user for profile display, telegram for connection status. No new state management needed.
- Node polyfills: Vite config (
vite.config.ts) polyfillsbuffer,process,util,os,crypto,streamfor thetelegramnpm package which requires Node APIs. - Telegram IDs: Use
big-integerlibrary, not native JS numbers (Telegram IDs exceedNumber.MAX_SAFE_INTEGER). - MCP tool files: Each tool in
src/lib/mcp/telegram/tools/exports a handler conforming toTelegramMCPToolHandlerinterface. Tool names are typed insrc/lib/mcp/telegram/types.ts. - Tauri IPC: Frontend calls Rust via
invoke()from@tauri-apps/api/core. Rust commands are registered ingenerate_handler![]macro. - CORS workaround: External HTTP requests from the WebView hit CORS. Use Rust
reqwestvia Tauri commands instead of browserfetch(). - Hash Routing: Uses HashRouter for desktop app compatibility and deep link handling.
Platform Gotchas
- macOS deep links: Require
.appbundle (nottauri dev). Clear WebKit caches when debugging stale content:rm -rf ~/Library/WebKit/com.megamind.tauri-app ~/Library/Caches/com.megamind.tauri-app - Cargo caching: May serve stale frontend assets on incremental builds. Run
cargo clean --manifest-path src-tauri/Cargo.tomlif the app shows outdated UI. window.__TAURI__: Not available at module load time. Use dynamicimport()and try/catch for Tauri plugin calls.