# Chat System Architecture
This document provides a comprehensive overview of the chat system architecture in the Cynoia Mobile application, including navigation, screens, components, models, services, and their relationships.
## Architecture Overview
The chat system follows a layered architecture with clear separation of concerns:
```mermaid
graph TB
subgraph "Presentation Layer"
NAV[ChatsNavigator]
SCREENS[Chat Screens]
COMPONENTS[Chat Components]
end
subgraph "Business Logic Layer"
STORES[MobX Stores]
MODELS[Data Models]
PARSERS[Message Parsers]
end
subgraph "Service Layer"
API[Chat API]
SOCKET[Socket Service]
LIVEKIT[LiveKit Service]
end
subgraph "Data Layer"
CACHE[Local Cache]
STORAGE[AsyncStorage]
end
NAV --> SCREENS
SCREENS --> COMPONENTS
COMPONENTS --> STORES
STORES --> MODELS
STORES --> API
STORES --> SOCKET
API --> CACHE
SOCKET --> STORES
STORES --> STORAGE
classDef presentation fill:#e1f5fe
classDef business fill:#f3e5f5
classDef service fill:#e8f5e8
classDef data fill:#fff3e0
class NAV,SCREENS,COMPONENTS presentation
class STORES,MODELS,PARSERS business
class API,SOCKET,LIVEKIT service
class CACHE,STORAGE data
```
## Navigation Layer
### ChatsNavigator
The central navigation controller for all chat-related screens.
**File**: `app/navigators/ChatsNavigator.tsx`
**Key Responsibilities**:
- Route management for 14+ chat screens
- Parameter passing between screens
- Navigation state management
- Screen presentation modes (modal, card, slide)
**Screen Routes**:
- `ConversationsList` - Main chat list (default)
- `ConversationDetails` - Chat conversation view
- `CreateChannel` - Channel creation
- `CreateRoom` - Video room creation
- `Meeting` - Video meeting interface
- `AudioMeet` - Audio call interface
- `Info` - Chat/channel information
- `Search` - Message search
- `Pinned` - Pinned messages
- `ChatAttachments` - Media attachments
- `PreviewMedia/File` - Media preview
- `MembersChannel` - Channel members
- `ChannelsList` - Browse channels
## Screen Layer Architecture
```mermaid
graph TD
subgraph "Lists"
CLS[ConversationsListScreen]
CHLS[ChannelsListScreen]
end
subgraph "Conversation"
CDS[ConversationDetailsScreen]
SS[SearchScreen]
end
subgraph "Channels"
CCS[CreateChannelScreen]
MCS[MembersChannelScreen]
end
subgraph "Rooms"
CRS[CreateRoomScreen]
MS[MeetingScreen]
BS[BridgeScreen]
end
subgraph "Communication"
AMS[AudioMeetScreen]
end
subgraph "Details"
IS[InfoScreen]
PS[PinnedScreen]
CAS[ChatAttachmentsScreen]
PMS[PreviewMediaScreen]
PFS[PreviewFileScreen]
end
CLS --> CDS
CLS --> CCS
CLS --> CHLS
CDS --> SS
CDS --> IS
CDS --> PS
CDS --> CAS
CCS --> MCS
CRS --> MS
MS --> BS
IS --> AMS
classDef list fill:#e3f2fd
classDef conversation fill:#f1f8e9
classDef channel fill:#fce4ec
classDef room fill:#fff8e1
classDef communication fill:#e8eaf6
classDef detail fill:#f3e5f5
class CLS,CHLS list
class CDS,SS conversation
class CCS,MCS channel
class CRS,MS,BS room
class AMS communication
class IS,PS,CAS,PMS,PFS detail
```
### Screen Descriptions
#### **Lists Screens**
- **ConversationsListScreen**: Main hub displaying all conversations (channels, direct messages, groups)
- **ChannelsListScreen**: Browse and discover public channels
#### **Conversation Screens**
- **ConversationDetailsScreen**: Core chat interface with message rendering, input, and real-time updates
- **SearchScreen**: Search messages within a conversation with filters and highlighting
#### **Channel Management Screens**
- **CreateChannelScreen**: Create new channels with privacy settings, member selection, and permissions
- **MembersChannelScreen**: Manage channel members, roles, and permissions
#### **Room/Meeting Screens**
- **CreateRoomScreen**: Create video meeting rooms with scheduling options
- **MeetingScreen**: LiveKit-powered video conferencing interface
- **BridgeScreen**: Connection bridge for meeting transitions
#### **Communication Screens**
- **AudioMeetScreen**: Voice-only calling interface with controls
#### **Detail Screens**
- **InfoScreen**: Comprehensive chat/channel information and settings
- **PinnedScreen**: View all pinned messages in a conversation
- **ChatAttachmentsScreen**: Browse all media and files shared in a chat
- **PreviewMediaScreen/PreviewFileScreen**: Full-screen media and document preview
## Component Architecture
```mermaid
graph TD
subgraph "ListView Components"
CA[ChatAvatar]
CC[ChatCard]
CHMC[ChannelMembersCard]
end
subgraph "ConversationView Components"
subgraph "Message Rendering"
MF[MessageFactory]
DC[Dynamic Components]
MI[MessageItems]
end
subgraph "Message Lists"
GCA[GiftedChatAdapter]
ML[MediaList]
end
subgraph "Input Components"
MINPUT[MessageInput]
RINPUT[RichMessageInput]
end
subgraph "UI Components"
TBM[TobBarMessages]
MH[MessageHeader]
MQA[MessageQuickActions]
RT[RecordTimer]
end
end
subgraph "VideoMeet Components"
LKP[LiveKitProvider]
LKV[LiveKitVideoView]
LKC[LiveKitControls]
end
subgraph "Communication Components"
CAB[CallActionButtons]
CS[CallStatus]
CT[CallTimer]
end
CC --> CA
GCA --> MF
MF --> DC
MF --> MI
MINPUT --> RT
classDef listview fill:#e8f5e8
classDef conversation fill:#e1f5fe
classDef videomeet fill:#fff3e0
classDef communication fill:#f3e5f5
class CA,CC,CHMC listview
class MF,DC,MI,GCA,ML,MINPUT,RINPUT,TBM,MH,MQA,RT conversation
class LKP,LKV,LKC videomeet
class CAB,CS,CT communication
```
### Component Layer Details
#### **ListView Components**
- **ChatAvatar**: Displays user/channel avatars with online status
- **ChatCard**: Conversation list item with last message, timestamp, unread count
- **ChannelMembersCard**: Channel member display with role indicators
#### **ConversationView Components**
##### Message Rendering System
```mermaid
graph LR
API[API Message] --> MF[MessageFactory]
MF --> MP[MessageParser]
MP --> DC[Dynamic Component]
subgraph "Dynamic Components"
NM[NormalMessage]
HM[HighlightedMessage]
RM[RepliedMessage]
DM[DeletedMessage]
EM[EditedMessage]
WRM[WithReactionsMessage]
WAM[WithAttachmentsMessage]
WLM[WithLinksMessage]
FM[ForwardedMessage]
PM[PinnedMessage]
end
DC --> NM
DC --> HM
DC --> RM
DC --> DM
DC --> EM
DC --> WRM
DC --> WAM
DC --> WLM
DC --> FM
DC --> PM
```
- **MessageFactory**: Analyzes message content and selects appropriate rendering component
- **Dynamic Components**: Specialized message renderers for different message types
- **MessageItems**: Reusable UI elements (text, images, chips, links)
##### Message Lists
- **GiftedChatAdapter**: Optimized message list with virtual scrolling and performance optimizations
- **MediaList**: Grid display for media attachments
##### Input System
- **MessageInput**: Primary message composition with attachment support
- **RichMessageInput**: Enhanced editor with formatting and mentions
- **RecordTimer**: Voice message recording interface
##### UI Components
- **TobBarMessages**: Chat header with actions and selection controls
- **MessageHeader**: Message metadata display (sender, timestamp)
- **MessageQuickActions**: Context actions (reply, react, pin, delete)
#### **VideoMeet Components**
- **LiveKitProvider**: WebRTC connection management
- **LiveKitVideoView**: Video stream rendering
- **LiveKitControls**: Meeting controls (mute, camera, screen share)
#### **Communication Components**
- **CallActionButtons**: Voice call controls
- **CallStatus**: Call state indicator
- **CallTimer**: Call duration tracking
## Data Layer Architecture
```mermaid
graph TD
subgraph "MobX State Tree"
RS[RootStore]
CS[ChatStore]
SS[SocketStore]
AS[AuthenticationStore]
OS[OrganizationStore]
end
subgraph "Data Models"
CM[ChatModels]
CHM[ChannelModel]
CRM[ChatRoomModel]
RM[ReceivedMessage]
end
subgraph "Message Processing"
MP[MessageParser]
AT[AttachmentTransformer]
MF[MessageFactory]
end
RS --> CS
RS --> SS
RS --> AS
RS --> OS
CS --> CM
CM --> CHM
CM --> CRM
CM --> RM
CS --> MP
MP --> AT
MP --> MF
classDef store fill:#e3f2fd
classDef model fill:#f1f8e9
classDef processor fill:#fce4ec
class RS,CS,SS,AS,OS store
class CM,CHM,CRM,RM model
class MP,AT,MF processor
```
### Store Architecture
#### **ChatStore** (`app/models/ChatStore.ts`)
Central state management for all chat operations.
**Key Properties**:
- `channels`: Array of available channels
- `rooms`: Array of direct message rooms
- `videoRooms`: Array of video meeting rooms
- `messages`: Current conversation messages
- `conversationMessages`: Isolated message storage per conversation
- `unseenMessages`: Unread message counts
- `selectedChannelId/selectedRoomId`: Current conversation context
**Key Methods**:
- `fetchChannels()`: Load organization channels
- `joinChannel()`: Join a channel
- `createRoom()`: Create direct message room
- `sendMessage()`: Send message to conversation
- `loadMessages()`: Load conversation history
- `handleSocketMessage()`: Process real-time updates
#### **SocketStore** (`app/models/SocketStore.ts`)
Manages WebSocket connections and real-time event handling.
**Responsibilities**:
- Connection state management
- Event subscription and cleanup
- Authentication synchronization
- Real-time message delivery
### Data Models
#### **ChannelModel**
```typescript
interface Channel {
id: string
name: string
description: string
isPrivate: boolean
memberCount: number
lastMessage?: Message
unseenCount: number
}
```
#### **ChatRoomModel**
```typescript
interface ChatRoom {
id: string
userOne: string
userTwo: string
lastMessage?: Message
unseenCount: number
}
```
#### **ReceivedMessage**
```typescript
interface ReceivedMessage {
id: string
content: string
sender: string
timestamp: string
messageType: 'text' | 'image' | 'file' | 'video'
attachments?: Attachment[]
reactions?: Reaction[]
parentMessage?: string
isDeleted: boolean
isEdited: boolean
}
```
## Service Layer Architecture
```mermaid
graph TD
subgraph "API Services"
CA[ChatApi]
AA[AuthApi]
DA[DriveApi]
end
subgraph "Real-time Services"
SS[SocketService]
LKS[LiveKitService]
end
subgraph "Utility Services"
AS[AttachmentService]
PS[PermissionService]
AR[AudioRecorder]
end
CA --> SS
SS --> CA
AS --> DA
LKS --> PS
AR --> AS
classDef api fill:#e8f5e8
classDef realtime fill:#e1f5fe
classDef utility fill:#fff3e0
class CA,AA,DA api
class SS,LKS realtime
class AS,PS,AR utility
```
### Service Details
#### **ChatApi** (`app/services/api/chat/chatApi.ts`)
RESTful API client for chat operations.
**Key Methods**:
- `getChatRooms()`: Fetch user's chat rooms
- `browseChannels()`: Get available channels
- `createChannel()`: Create new channel
- `joinChannel()`: Join existing channel
- `getMessages()`: Load conversation messages
- `addMessage()`: Send new message
- `getPinnedMessages()`: Get pinned messages
- `getChannelMedia()`: Load media attachments
#### **SocketService** (`app/services/socket/socketService.ts`)
WebSocket client for real-time communication.
**Event Handling**:
- Connection lifecycle events
- Message events (`sentMessage`, `updateMessage`, `deleteMessage`)
- Channel events (`joinChannel`, `addUserToChannel`, `removeUserFromChannel`)
- Reaction events (`reactToMessage`, `removeReactToMessage`)
- Pin events (`pinMessage`, `pinMessageChannel`)
#### **LiveKitService** (`app/services/livekit/`)
WebRTC video conferencing integration.
**Features**:
- Room creation and joining
- Participant management
- Audio/video controls
- Screen sharing
- Connection quality monitoring
## Message Flow Architecture
```mermaid
sequenceDiagram
participant U as User
participant C as Component
participant S as ChatStore
participant A as ChatApi
participant WS as SocketService
participant R as Recipient
U->>C: Type message
C->>S: sendMessage()
S->>A: addMessage()
A->>WS: Broadcast event
WS->>S: sentMessage event
S->>C: Update UI
WS->>R: Real-time delivery
R->>R: Update conversation
```
### Message Processing Pipeline
1. **Input Capture**: MessageInput component captures user input
2. **Validation**: Content validation and attachment processing
3. **API Call**: ChatApi sends message to server
4. **Optimistic Update**: Local UI updates immediately
5. **Socket Broadcast**: Server broadcasts to participants
6. **State Sync**: All clients update via socket events
7. **Persistence**: Messages stored in local cache
## Real-time Event Flow
```mermaid
graph LR
subgraph "Client A"
A1[User Action]
A2[Local Update]
A3[API Call]
end
subgraph "Server"
S1[Process Request]
S2[Broadcast Event]
S3[Database Update]
end
subgraph "Client B"
B1[Receive Event]
B2[Update Store]
B3[Re-render UI]
end
A1 --> A2
A2 --> A3
A3 --> S1
S1 --> S2
S1 --> S3
S2 --> B1
B1 --> B2
B2 --> B3
```
## Component Flow: GiftedChat to Message Evaluation
### Complete Message Rendering Pipeline
```mermaid
sequenceDiagram
participant GCA as GiftedChatAdapter
participant MI as MessageItem
participant MF as MessageFactory
participant MP as MessageParser
participant DC as DynamicComponent
participant MH as MessageHeader
GCA->>GCA: convertToReceivedMessage()
GCA->>GCA: processedData with grouping
GCA->>GCA: giftedMessages (reverse order)
GCA->>MI: renderMessage(ExtendedIMessage)
MI->>MI: Convert ReceivedMessage to ApiMessage
MI->>MF: MessageFactory(apiMessage, user, props)
MF->>MP: MessageParser.parseMessage(apiMessage)
MP->>MP: extractFeatures() + extractMetadata()
MP->>MP: determineComponentType()
MP->>MF: Return analysis + componentType
MF->>MF: getUserDetails() + enhancedUser
MF->>DC: Render specific component (NormalMessage, WithReactionsMessage, etc.)
MF->>MH: MessageHeader wrapper
MH->>MI: Complete rendered message
MI->>GCA: Final message with TouchableOpacity + QuickActions
```
### Data Transformation Chain
1. **Raw API Message** → `GiftedChatAdapter.convertToReceivedMessage()`
- Handles nested/flat API structure
- Resolves user details via `getUserDetails()`
- Creates `ReceivedMessage` format
2. **Message Grouping** → `processedData` with `showAvatar`/`showUsername` logic
- 5-minute grouping threshold
- Same user message clustering
- Avatar visibility rules
3. **GiftedChat Format** → `ExtendedIMessage` with `_originalData`
- Reverse chronological order (newest first)
- GiftedChat-compatible structure
- Preserves original data for custom rendering
4. **MessageItem Conversion** → `ApiMessage` reconstruction
```typescript
// PROBLEMATIC: Double conversion in MessageItem.tsx lines 235-265
const apiMessage: ApiMessage = message._originalApiMessage || {
id: message.id,
content: message.contentMessage?.text || "",
sender: message.user?.id || "unknown",
// Manual reconstruction of nested structure
message: {
id: message.id,
createdDate: message.timestamp,
// ... more manual mapping
}
}
```
5. **MessageParser Analysis** → Component type determination
- `extractFeatures()`: deleted, pinned, reply, attachments, reactions, edited, mentions, links
- `extractMetadata()`: boolean flags for all features
- `determineComponentType()`: Priority-based component selection
6. **Dynamic Component Rendering** → Feature-specific components
- `MessageComponentType` enum-based switching
- Legacy format conversion for backward compatibility
### Legacy Components & Non-DRY Issues
#### 1. **Legacy Component References** (`DynamicComponents/index.ts`)
```typescript
// Legacy imports (commented for reference to what was moved)
// export { NormalMessage } from "../Cards/Legacy_NormalMessage" // Now local: ./NormalMessage
// export { HighlightedMessage } from "../Cards/Legacy_HighlightedMessage" // Now local: ./HighlightedMessage
// export { RepliedMessage as LegacyRepliedMessage } from "../Cards/Legacy_RepliedMessage" // Now local: ./RepliedMessage
```
**Issue**: Old legacy components still referenced but moved to new locations
#### 2. **Double Message Conversion** (`MessageItem.tsx` lines 235-265)
```typescript
// Convert ReceivedMessage to ApiMessage format for MessageFactory
const apiMessage: ApiMessage = message._originalApiMessage || {
// Manual reconstruction of API message structure
message: {
attachements: message.contentMessage?.attachments?.map((att) => ({
// Manual mapping of attachment structure
})) || [],
}
}
```
**Issue**: `ReceivedMessage` → `ApiMessage` → `legacyMessage` conversion chain is inefficient
#### 3. **MessageParser Legacy Compatibility** (`MessageParser.ts` lines 424-478)
```typescript
static convertToLegacyFormat(apiMessage: ApiMessage): any {
// Another conversion layer for backward compatibility
return {
contentMessage: {
attachments: messageData.attachements?.map((a) => ({
type: a.fileType.startsWith('image/') ? 'image' :
a.fileType.startsWith('video/') ? 'video' : 'file',
// More manual type conversion
})),
},
}
}
```
**Issue**: Triple conversion: `ApiMessage` → `legacyMessage` → component props
#### 4. **Inconsistent Attachment Handling**
- `attachements` (API) vs `attachments` (UI) naming inconsistency
- Multiple attachment transformers: `attachmentTransformer.ts`, `attachmentService.ts`
- Different attachment structures across components
#### 5. **QuickActionsController Singleton Pattern** (`GiftedChatAdapter.tsx` lines 58-83)
```typescript
export class QuickActionsController {
private static instance: QuickActionsController
private dismissCallbacks: Array<() => void> = []
static getInstance(): QuickActionsController {
if (!QuickActionsController.instance) {
QuickActionsController.instance = new QuickActionsController()
}
return QuickActionsController.instance
}
}
```
**Issue**: Global singleton for UI state management - should use React context
#### 6. **TODO Comments in Production Code** (`MessageFactory.tsx` lines 19-24)
```typescript
// TODO: Create these new dynamic components
// import { DeletedMessage } from "./Cards/DeletedMessage"
// import { WithAttachmentsMessage } from "./Cards/WithAttachmentsMessage"
```
**Issue**: Unfinished migration comments in production code
### Component Complexity Issues
#### MessageItem State Management (lines 46-122)
- 7 different useEffect hooks for quick actions
- Complex timing logic with `hideTimer.current`
- Multiple boolean flags: `longPressJustHappened`, `shouldShowQuickActionsOnSelection`
- 200ms/5000ms magic numbers for timeouts
#### GiftedChatAdapter Message Processing
- 174-line `useMemo` for message processing
- Complex grouping logic with time thresholds
- Double array operations: `.map().filter().sort().reverse()`
<style>
section#notes-recommendations,
section#notes-recommendations hr {
display: none !important;
}
</style>