# LetUsMsg Flutter App - AI Coding Agent Instructions **Project**: LetUsMsg (Flutter cross-platform messaging app) **Focus**: gRPC relay-based secure messaging with local Hive persistence ## Architecture Overview ### Core Components 1. **Relay Communication** (`flutter_src/lib/relay/`) - `grpc_service.dart`: gRPC client managing streaming messages from relay servers and sending messages - Handles message sequences, acknowledgments, and connection state - Uses `fixnum.Int64` for protobuf compatibility (common error: forgetting `import 'package:fixnum/fixnum.dart'`) - **Key workflow**: `registerClient()` → `streamMessages()` → `_procMessage()` → `ackMessages()` 2. **Data Layer** (`flutter_src/lib/data/`) - Hive CE (encrypted local DB) for persistent storage - Models: `MyselfData`, `ChannelData`, `MessageData`, `RelayPoolData`, `RelayStateData`, `CCCData` and more look at the path `flutter_src/lib/data/` - All models use `@HiveType()` annotations; code generation required (`build_runner`) - **Message storage**: Size-based approach (active box + archived boxes per channel) 3. **Processing Layer** (`flutter_src/lib/proc/`) - `proc_main.dart`: Central orchestrator - Abstract base classes: `ProcConnAbstract`, `ProcMsgAbstract`, `NetworkSendAbstract` - Handles cryptography, message sending, incoming stream processing - Runs message background work via `worker_manager` isolates 4. **State Management** (`flutter_src/lib/bloc/`) - BLoC pattern (custom, not `flutter_bloc` package) - `AppState`: Global singleton for `appNotify`, `conn`, `fcm`, `msgNotify`, `proc` - `ConnectionStateUI`: Connection state per relay (connecting/registered/disconnected) - Changes broadcast via callbacks: `StreamMsgCallback`, `StreamCloseCallback`, `StreamCountCallback` 5. **UI Layer** (`flutter_src/lib/`) - `main.dart`: Multi-platform entry (macOS, iOS, Android, Linux, Windows) - Platform detection: `Platform.isMacOS`, `Platform.isIOS`, etc. - Custom widgets in `widgetz/`; theme via `flex_color_scheme` ∏ ## Key Workflows & Patterns ### Message Relay Flow ``` User sends → UI callback → NetworkSendAbstract.sendMessage() → gRPC stub.sendMessage(Message) → Relay server → other clients receive via streamMessages() → _procMessage() processes with sequence tracking → _lastMsgSeq == serverSeq → ackMessages(AckRequest) → Clear cached messages, reset _firstMsgSeq/_lastMsgSeq ``` ### gRPC Type Handling (Critical) - **Protobuf definitions**: `proto/letusmsg.proto` defines service `MessagingService` - **Generated stubs**: `flutter_src/lib/gen/proto/letusmsg.pbgrpc.dart` (auto-generated) - **Integer types**: Always use `Int64` (from `fixnum`) for protobuf `int64` fields - Common error: `Int16(_lastMsgSeq)` → use `Int64(_lastMsgSeq)` instead - Nullable fields: `Int64?` requires conditional: `_lastMsgSeq == -1 ? null : Int64(_lastMsgSeq)` - **Method calls**: Use named parameters, e.g., `_stub.ackMessages(request: ackRequest, options: ...)` ### Hive Data Generation - All Hive models require code generation - **Build command**: `flutter pub run build_runner build --delete-conflicting-outputs` - Files: `*_data.g.dart` (auto-generated adapters) - Models must have: `@HiveType()`, `@HiveField(0)` annotations - **Storage locations**: `dataDir` (from args or default app docs dir) ### Multi-Platform Desktop Window Management - macOS/Windows/Linux: Use `window_manager` (see `main.dart`) - Mobile (iOS/Android): Firebase initialization required - Window options: Title, size (600x800 default), titlebar style, min/max dimensions ## Common Pitfalls & Solutions ### Notification Tap Handling (Critical for Mobile) The app handles notifications from **three sources**: 1. **FCM (Firebase Cloud Messaging)** - Remote push notifications (`relay/fcm.dart`) 2. **flutter_local_notifications** - Local notifications (`notifications/local_notification.dart`) 3. **URI Deep Links** - Custom scheme `com.letusmsg://` via `app_links` package **Three App States for Notification Taps:** | State | FCM Handler | Local Notification Handler | URI Deep Link | |-------|-------------|---------------------------|---------------| | **Terminated (cold start)** | `getInitialMessage()` | `getNotificationAppLaunchDetails()` | `getInitialLink()` | | **Background (warm start)** | `onMessageOpenedApp` stream | `onDidReceiveNotificationResponse` callback | `uriLinkStream` | | **Foreground (hot)** | `onMessage` stream | `onDidReceiveNotificationResponse` callback | `uriLinkStream` | **Key Pattern**: Always check for "initial message/link" on app startup because callbacks aren't registered when app is terminated. Store in `MyApp.pendingDeepLink` and process after splash screen via `MyApp.processPendingDeepLink()`. **Deep Link Handler**: All notification taps route through `utilz/deep_link_handler.dart`: - `DeepLinkArgs.fromUri()` - Parse URI deep links - `DeepLinkArgs.fromFcmData()` - Parse FCM notification data payload - `DeepLinkArgs.fromPayload()` - Parse local notification payload string **FCM Data Payload Structure** (server sends this): ```json { "data": { "channel": "abc123-channel-uuid" } } ``` **URI Deep Link Format**: - Open channel: `com.letusmsg://chat?channel=abc123` - Accept invite: `com.letusmsg://chat?invite-code=89ae57b9-4435-4956-b735-37bd5af00a5e` **Flow for Cold Start from Notification**: 1. User taps notification → App launches 2. `FCM.init()` calls `getInitialMessage()` → stores in `initialMessageData` if callback not ready 3. `_setupNotificationHandlers()` checks `initialMessageData` → sets `MyApp.pendingDeepLink` 4. Splash finishes → `MyApp.processPendingDeepLink()` → `DeepLinkHandler.handle()` → navigate to channel ## Build & Test Commands **Manual Flutter commands**: ```bash flutter pub get # Install deps flutter pub run build_runner build --delete-conflicting-outputs # Hive codegen flutter run -v # Run with logs flutter test # Run unit tests (test/) ``` ## Project-Specific Dependencies - **gRPC/Protobuf**: `grpc: ^4.1.0`, `fixnum: ^1.1.1` (strict version to avoid dependency issues) - **State Management**: `provider: ^6.1.2` (lightweight, not flutter_bloc) - **Local Storage**: `hive_ce: ^2.10.1` (encrypted), `path_provider: ^2.0.15` - **Async**: `worker_manager: ^7.2.6` (for background isolates) - **Firebase**: `firebase_core`, `firebase_messaging` (mobile only, see `main.dart`) - **Notifications**: `flutter_local_notifications` (local notifications with cold start support) - **Deep Linking**: `app_links: ^6.4.0` (URI scheme and universal links) - **UI**: `flex_color_scheme` (dynamic theming), `flutter_svg` (SVG support) - **Custom packages** (git-based): - `lum_loading_animations` (internal) - `linkify_text` (forked, improved regex) ## File Organization ``` flutter_src/ ├── lib/ │ ├── main.dart # Entry point, platform detection │ ├── app.dart # App widget │ ├── bloc/ # State management │ │ ├── app_state.dart # Global singleton │ │ ├── conn_state_UI.dart # Connection per relay │ │ └── ... │ ├── data/ # Hive models & persistence │ │ ├── myself_data.dart │ │ ├── my_hive.dart # Hive box manager │ │ └── ... │ ├── notifications/ # Push & local notifications │ │ ├── local_notification.dart # flutter_local_notifications wrapper │ │ └── permissions.dart # Notification permission handling │ ├── proc/ # Business logic & processing │ │ ├── proc_main.dart │ │ └── *_abstract.dart # Abstract interfaces │ ├── relay/ # gRPC communication │ │ ├── grpc_service.dart # Main gRPC client │ │ └── fcm.dart # Firebase Cloud Messaging │ ├── utilz/ # Utilities │ │ ├── deep_link_handler.dart # Deep link & notification routing │ │ └── Llog.dart # Logging configuration │ ├── widgetz/ # UI widgets │ └── ... ├── pubspec.yaml # Dependencies └── ... proto/ ├── letusmsg.proto # Protobuf definitions ``` ## Next Steps for Contributors - **First-time setup**: Run `flutter pub get` and `flutter pub run build_runner build --delete-conflicting-outputs` - **Understand gRPC service**: Read `relay/grpc_service.dart` (callbacks, state machine) - **Understand meessage flow**: `proc/proc_bg_msg.dart` is the message processing engine - **Hive persistence**: Review `data/my_hive.dart` and size-based message storage in `new_message_storage_architecture.md` - **Adding features**: Use abstract base classes in `proc/` and follow BLoC pattern in `bloc/` - **Testing**: Add tests to `test/` and run `flutter test` ## Notes - **Logging**: Uses `logger` package; configure in `utilz/Llog.dart` - **Crypto**: Phase 1 implemented via `cryptography: ^2.7.0`; see `proc/crypt_abstract.dart` - **CCC** (Copius Cipher Chain): Internal message protocol; see `data/ccc_data.dart` ## Instructions for AI Coding Agent - Follow the established architecture and coding patterns. - his project is using dart lang and flutter framework. you are an elite coder who knows the dart lang design patterns and the flutter design patterns that are the most recent and popular, and you apply those with pricision, focusing on an amazing user experience, focusing on responsive design (because this app will run on mobile phones and desktop) - make sure to follow the code and design patterns for this project, that includes file names, notifications, and popups and confirmation popups; there is an app constants and app theme constants that should be used and provided more details of the app design; do your research; - this is the worlds most secure messaging app. the app is design so that the main isolate is dedicated to the UI and there is a background isolate that handles a lot of IO for the app, for example local storage with hive db, networking with grpc, and encryption. - prioritize efficiency and clean code: avoid duplicate logic/UI; extract reusable widgets/helpers for repeated behavior so there is one place to maintain changes. - DO NOT remove any existing features! you can ask me questions for more clarity on your solutions and fixes. - please ask me any questions and share you design before changing code - if you create documents use .rst format and name the files in lowercase - if you create code files, follow the existing naming patterns and file organization - if you create new features, make sure to add tests for them in the test/ directory and follow the existing testing patterns - if you create new classes and methods(more than 5 lines of code) , make sure to add doc comments and follow the existing code style and patterns