AI-Powered Messaging Platform for Remote Teams
A production-ready iOS messaging application built with SwiftUI and Supabase, featuring integrated AI assistants to help remote professionals manage communication overload, track decisions, and maintain team alignment across time zones.
MessageAI combines enterprise-grade messaging infrastructure with intelligent AI assistants designed specifically for distributed teams. Built on a modern SwiftUI + Supabase architecture, it delivers WhatsApp-quality real-time messaging enhanced with contextual AI features that surface insights without leaving your conversations.
Target Users: Engineering managers, product leads, and remote team coordinators managing high-volume async communication across time zones.
Core Value: Transforms message overload into actionable intelligence through embedded AI agents.
Your intelligent work companion that lives inside your conversations:
- π Thread Summarization - Digest 50+ message threads in seconds
- π― Action Item Extraction - Auto-detect commitments and owners ("I'll do X")
- β Decision Tracking - Surface agreed-upon decisions from discussions
- π¨ Priority Detection - Flag urgent messages automatically
- π Smart Semantic Search - Find information by meaning, not keywords
- π¬ Direct Chat - Ask MoChain questions about your team coordination
- π§ Multi-Step Workflows - Execute complex tasks autonomously
Dedicated fitness and wellness AI for busy remote professionals:
- πͺ Workout Planning - Personalized training programs
- π₯ Nutrition Guidance - Meal planning and dietary advice
- π Fitness Tracking - Progress monitoring and motivation
- βοΈ Work-Life Balance - Wellness tips for remote workers
Real-Time Communication
- Instant message delivery via Supabase Realtime
- WhatsApp-style message status (sent β, delivered ββ, read π΅)
- Typing indicators and presence system
- Group chats with participant management
- Direct one-on-one conversations
Rich Media Support
- πΈ Image sharing via S3/CloudFront CDN
- π₯ Video messages with playback controls
- ποΈ Voice messages with waveform visualization
- πΌοΈ Group avatars and profile pictures
Smart Features
- π Message pinning for important updates
- ποΈ Delete for Me vs Delete for Everyone
- π§Ή Clear chat history (personal view only)
- π― Lazy conversation creation (DB created on first message)
- πΎ Offline support with auto-sync
- β‘ Optimistic UI for instant feedback
Beautiful Interface
- WhatsApp-inspired gradients and animations
- Custom message bubble shapes with tail pointers
- Glass morphism effects on AI action toolbar
- Smooth spring-based transitions (60fps)
- Professional design token system (Colors, Typography, Shadows, Spacing)
Smart Notifications
- In-app banner notifications (no developer account needed)
- APNs push notification support
- Conversation-aware notification routing
Helpful Guidance
- Character counter (4096 limit)
- Empty states with onboarding hints
- User-friendly error messages
- AI configuration banner for setup
Dual-Database Design
- Global DB for shared conversations and messages
- Per-user privacy layer for personal deletions
- Server-side message filtering for optimal privacy
- ISO8601 timestamp standardization
Optimization
- NSCache reduces Supabase reads by ~70%
- Lazy loading with pagination (100 messages at a time)
- Smart UI updates (only re-render on actual changes)
- 15MB cache limit with auto-cleanup
- Optimized queries with delta polling
- <200ms latency with optimistic UI
Observability
- Performance monitoring dashboard
- Sync service monitoring
- Database operation tracing
- State inspector for debugging
- Test data seeding for development
Frontend
- SwiftUI - Declarative UI framework
- SwiftData - Modern local persistence
- iOS 17+ - Latest platform features
- CoreML - On-device AI inference
- AVFoundation - Audio/video playback
Backend
- Supabase Postgres - Realtime JSON document store with JSONB
- Supabase Auth - Email/password authentication
- Supabase Edge Functions - Serverless API endpoints (Deno runtime)
- AWS S3 + CloudFront - Media storage and CDN
- OpenAI GPT-4 - AI assistant capabilities
AI Infrastructure
- On-device Apple Intelligence for translations
- Server-side inference via Edge Functions
- Multiple inference provider support (CoreML, Foundation Models, Server)
- iOS: 17.0 or later
- Xcode: 16.0 or later
- Swift: 5.9+
- Supabase: Project with Postgres database
- Optional: AWS S3 bucket for media, OpenAI API key for AI features
For simulator and local testing, use the automated setup script:
# Clone the repository
git clone https://github.com/MomenMushtaha/MessageAI.git
cd message-ai
# Run Supabase setup (installs CLI, starts local instance, creates schema)
./scripts/setup-supabase.sh
# Start AI agent backend (optional - for MoChain/MushLifts)
./scripts/start-backend.shThe setup script automatically:
- Installs Supabase CLI (if needed)
- Initializes local Supabase at
http://127.0.0.1:54321 - Creates
realtime_documentstable with RLS policies - Sets up authentication system
To test on a physical iOS device connected to your local Supabase:
-
Find your Mac's local IP address:
ifconfig | grep "inet " | grep -v 127.0.0.1
-
Update Info.plist with your local IP:
<key>SUPABASE_URL</key> <string>http://192.168.x.x:54321</string>
-
Enable Local Network permission:
- iOS Settings β Privacy & Security β Local Network β MessageAI β
Create a production Supabase project:
# Create project at https://supabase.com/dashboard
# Then configure your project:
# Create realtime documents table
psql $SUPABASE_DB_URL -c "
CREATE TABLE IF NOT EXISTS realtime_documents (
path TEXT PRIMARY KEY,
data JSONB
);
-- Enable RLS
ALTER TABLE realtime_documents ENABLE ROW LEVEL SECURITY;
-- Allow authenticated users full access
CREATE POLICY \"Allow authenticated access\"
ON realtime_documents
FOR ALL
USING (auth.role() = 'authenticated')
WITH CHECK (auth.role() = 'authenticated');
"Copy the example config and fill in your credentials:
cp Config.example.xcconfig Config.xcconfigEdit Config.xcconfig:
SUPABASE_URL = https://your-project.supabase.co
SUPABASE_ANON_KEY = your-anon-key-here
SUPABASE_FUNCTIONS_URL = https://your-project.functions.supabase.co
S3_UPLOAD_ENDPOINT = $(SUPABASE_FUNCTIONS_URL)/generate-upload-url
MOCHAIN_CHAT_ENDPOINT = $(SUPABASE_FUNCTIONS_URL)/mochain
MUSHLIFTS_CHAT_ENDPOINT = $(SUPABASE_FUNCTIONS_URL)/mushliftsDeploy the AI and media handling functions:
cd supabase/functions
# Deploy all functions
supabase functions deploy mochain
supabase functions deploy mushlifts
supabase functions deploy generate-upload-url
supabase functions deploy send-notification
supabase functions deploy aiSummarize
supabase functions deploy summarizeText
# Set environment variables
supabase secrets set OPENAI_API_KEY=sk-your-key-here
supabase secrets set AWS_BUCKET=your-bucket-name
supabase secrets set AWS_REGION=us-east-1
supabase secrets set CLOUDFRONT_DOMAIN=d123.cloudfront.netFor media storage:
-
Create S3 Bucket
- Enable private ACLs and block public access
- Note the bucket name and region
-
Create CloudFront Distribution (optional but recommended)
- Point to your S3 bucket
- Note the distribution domain (e.g.,
d123.cloudfront.net)
-
Configure IAM Credentials
- Create IAM user with S3 write permissions
- Generate access keys
- Store in Edge Function environment variables
-
Update Edge Function Config
supabase secrets set AWS_ACCESS_KEY_ID=your-access-key supabase secrets set AWS_SECRET_ACCESS_KEY=your-secret-key
For production push notifications:
- Generate APNs key in Apple Developer Console
- Upload key to Supabase (or configure in Edge Function)
- Device tokens automatically register via app's built-in flow
- Stored at
users/{userId}/pushTokens/{token}in realtime_documents
message-ai/
βββ MessageAI/ # Main iOS app directory
β βββ MessageAIApp.swift # App entry point, Supabase + SwiftData init
β βββ MainAppView.swift # Root view with auth state management
β β
β βββ Models/ # Data models
β β βββ User.swift # User model with online presence
β β βββ Conversation.swift # Conversation (direct/group)
β β βββ LocalMessage.swift # SwiftData message persistence
β β βββ LocalConversation.swift # SwiftData conversation cache
β β βββ TypingStatus.swift # Typing indicator state
β β
β βββ Views/ # SwiftUI screens
β β βββ Auth/ # Authentication screens
β β β βββ LoginView.swift # Email/password login
β β β βββ SignUpView.swift # User registration
β β β
β β βββ Chat/ # AI Assistant interfaces
β β β βββ MoChainChatView.swift # MoChain AI chat
β β β βββ MushLiftsChatView.swift # MushLifts wellness chat
β β β
β β βββ ChatList/ # Conversation list screens
β β β βββ ChatListView.swift # Main conversations list
β β β βββ ConversationRow.swift # Conversation cell UI
β β β βββ NewChatView.swift # Start direct chat
β β β βββ NewGroupView.swift # Create group chat
β β β βββ MoChainCard.swift # MoChain entry point card
β β β βββ MushLiftsCard.swift # MushLifts entry point card
β β β βββ AIConfigBanner.swift # AI setup prompt
β β β
β β βββ Conversation/ # Message detail screens
β β β βββ ConversationDetailView.swift # Message thread view
β β β βββ GroupDetailsView.swift # Group settings
β β β βββ GroupInfoView.swift # Group info sheet
β β β βββ OpenAISettingsView.swift # Configure AI API keys
β β β
β β βββ Profile/ # User profile screens
β β β βββ UserProfileView.swift # View user profile
β β β βββ EditProfileView.swift # Edit own profile
β β β
β β βββ Settings/ # App settings
β β β βββ InferenceSettingsView.swift # AI inference config
β β β
β β βββ Debug/ # Development tools
β β β βββ ConversationDebugView.swift # Message debugging
β β β βββ UserDiagnosticView.swift # User data inspection
β β β βββ StateInspectorView.swift # App state viewer
β β β βββ DatabaseExplorerView.swift # DB browser
β β β βββ TestDataDebugView.swift # Test data management
β β β
β β βββ Components/ # Reusable view components
β β βββ AIInsightsView.swift # AI results display
β β βββ MessageActionsSheet.swift # Message context menu
β β βββ TypingIndicatorView.swift # Typing animation
β β βββ ForwardMessageView.swift # Message forwarding
β β βββ ReactionPickerView.swift # Message reactions
β β
β βββ Components/ # Standalone UI components
β β βββ AIBottomBar.swift # AI actions toolbar
β β βββ MessageBubbleShape.swift # Custom bubble shape
β β βββ AIResultCard.swift # AI insight card
β β βββ InAppNotificationBanner.swift # Notification banner
β β βββ OfflineBanner.swift # Offline indicator
β β βββ AudioMessageView.swift # Voice message player
β β βββ VideoMessageView.swift # Video player
β β βββ ImageMessageView.swift # Image viewer
β β βββ VoiceRecordingView.swift # Voice recorder UI
β β βββ PinnedMessagesView.swift # Pinned messages sheet
β β βββ AnimatedTypingIndicator.swift # Typing dots
β β βββ SelectableMessageText.swift # Text selection
β β βββ SkeletonView.swift # Loading placeholders
β β
β βββ Services/ # Business logic layer
β β βββ AuthService.swift # Authentication
β β βββ AuthService+ServiceProtocol.swift
β β βββ ChatService.swift # Core messaging orchestration
β β βββ ChatService+Conversations.swift # Conversation CRUD
β β βββ ChatService+Messages.swift # Message CRUD
β β βββ ChatService+Sending.swift # Message sending logic
β β βββ ChatService+MessageActions.swift # Delete, pin, etc.
β β βββ ChatService+Groups.swift # Group management
β β βββ ChatService+Users.swift # User lookups
β β βββ ChatService+Media.swift # Media handling
β β βββ ChatService+Notifications.swift # In-app notifications
β β βββ ChatService+ServiceProtocol.swift
β β βββ PresenceService.swift # Online status + typing
β β βββ PresenceService+ServiceProtocol.swift
β β βββ SyncService.swift # Offline sync coordination
β β βββ SyncService+ServiceProtocol.swift
β β βββ SyncMonitor.swift # Sync health monitoring
β β βββ LocalStorageService.swift # SwiftData persistence
β β βββ LocalStorageService+ServiceProtocol.swift
β β βββ MediaService.swift # S3 media uploads
β β βββ AIService.swift # AI features coordinator
β β βββ InferenceManager.swift # Multi-provider AI inference
β β βββ CoreMLInferenceProvider.swift # On-device inference
β β βββ FoundationModelsInferenceProvider.swift # Apple Intelligence
β β βββ ServerInferenceProvider.swift # Edge Function calls
β β βββ NotificationService.swift # In-app notification manager
β β βββ PushNotificationService.swift # APNs registration
β β βββ NetworkMonitor.swift # Connectivity monitoring
β β βββ NetworkMonitor+ServiceProtocol.swift
β β βββ CacheManager.swift # NSCache for users/convos
β β βββ RateLimiter.swift # API rate limiting
β β βββ HealthCheckService.swift # Service health monitoring
β β βββ ErrorRecoveryService.swift # Auto-recovery logic
β β βββ PerformanceMonitor.swift # Performance tracking
β β βββ LoggingService.swift # Centralized logging
β β βββ DatabaseOperationTracer.swift # DB query tracing
β β βββ AudioService.swift # Audio recording/playback
β β βββ AppConfig.swift # App configuration
β β βββ ServiceProtocol.swift # Service lifecycle protocol
β β β
β β βββ Supabase/ # Supabase integration
β β βββ SupabaseAuthClient.swift # Auth REST wrapper
β β βββ SupabaseRealtimeDatabase.swift # Realtime DB w/ polling
β β βββ SupabaseConfiguration.swift # Config validation
β β
β βββ Theme/ # Design system tokens
β β βββ Colors.swift # Color palette
β β βββ Typography.swift # Font styles
β β βββ Shadows.swift # Shadow presets
β β βββ Spacing.swift # Spacing constants
β β
β βββ Utilities/ # Helper utilities
β β βββ ValidationUtility.swift # Input validation
β β βββ TestDataSeeder.swift # Test data generation
β β
β βββ AppDelegate.swift # AppDelegate for APNs
β
βββ supabase/ # Backend infrastructure
β βββ functions/ # Edge Functions (Deno)
β βββ mochain/ # MoChain AI agent
β β βββ index.ts # GPT-4 streaming chat
β βββ mushlifts/ # MushLifts AI agent
β β βββ index.ts # Fitness/wellness AI
β βββ generate-upload-url/ # Media upload handler
β β βββ index.ts # S3 presigned URL generation
β βββ send-notification/ # Push notifications
β β βββ index.ts # APNs dispatcher
β β βββ apns.ts # APNs client
β βββ aiSummarize/ # Thread summarization
β β βββ index.ts # Conversation summarizer
β βββ summarizeText/ # Generic text summary
β βββ index.ts # Text summarization
β
βββ scripts/ # Development scripts
β βββ setup-supabase.sh # Automated Supabase local setup
β βββ start-backend.sh # Start all edge functions locally
β βββ start-ai-agents.sh # Start AI agent servers
β βββ stop-agents.sh # Stop AI agent servers
β βββ .env-setup.sh # Environment configuration
β
βββ MessageAI.xcodeproj/ # Xcode project
βββ Config.xcconfig # App configuration (git-ignored)
βββ Config.example.xcconfig # Configuration template
βββ Info.plist # App info and permissions
βββ Info.plist.example # Info.plist template
βββ MessageAI.entitlements # App capabilities
βββ README.md # This file
MessageAI uses a dual-database architecture for privacy and performance:
Stores all conversations and messages accessible to participants:
realtime_documents.data:
{
"conversations": {
"{conversationId}": {
"type": "direct" | "group",
"name": "Group Name", // only for groups
"avatarUrl": "https://...", // optional group avatar
"participantIds": ["user1", "user2", ...],
"participantMap": { "user1": true, "user2": true },
"createdAt": "2024-01-01T00:00:00Z",
"lastMessageAt": "2024-01-01T12:34:56Z",
"messages": {
"{messageId}": {
"senderId": "user1",
"text": "Hello world",
"createdAt": "2024-01-01T12:34:56Z",
"type": "text" | "image" | "video" | "audio",
"mediaUrl": "https://...", // for media messages
"deliveredTo": ["user2"],
"readBy": ["user2"],
"deletedForEveryone": true, // if sender deleted for all
"isPinned": true // optional
}
}
}
},
"users": {
"{userId}": {
"profile": {
"displayName": "John Doe",
"email": "john@example.com",
"avatarUrl": "https://...",
"createdAt": "2024-01-01T00:00:00Z"
},
"presence": {
"isOnline": true,
"lastSeen": "2024-01-01T12:34:56Z"
},
"typing": {
"{conversationId}": {
"isTyping": true,
"timestamp": "2024-01-01T12:34:56Z"
}
}
}
}
}
Personal deletions and preferences invisible to other users:
realtime_documents.data:
{
"users": {
"{userId}": {
"deletedMessages": {
"{conversationId}": {
"{messageId}": true // marked as deleted for this user
}
},
"pushTokens": {
"{token}": {
"createdAt": "2024-01-01T00:00:00Z",
"deviceName": "iPhone 15 Pro"
}
}
}
}
}
- Lazy Creation: Conversations created in DB only when first message is sent
- Delete for Me: Adds messageId to
users/{userId}/deletedMessages(private) - Delete for Everyone: Sets
deletedForEveryone: trueon message (global) - Clear Chat: Bulk adds all message IDs to user's deletedMessages
- Server-Side Filtering: Messages filtered during fetch based on deletion lists
- ISO8601 Timestamps: All dates use ISO8601 strings for consistency
- Participant Map: Enables efficient
WHERE participantMap ? :userIdqueries
Access via ChatListView menu:
- State Inspector - View app-wide state in real-time
- Database Explorer - Browse Supabase documents
- Conversation Debug - Inspect message metadata
- User Diagnostic - View user data and presence
- Test Data Debug - Seed conversations for testing
- Performance Monitor - Track app performance metrics
Use TestDataSeeder to generate realistic test data:
// In TestDataDebugView
let seeder = TestDataSeeder(userId: currentUserId)
await seeder.seedConversations(count: 10)
await seeder.seedMessages(conversationId: id, count: 50)# Start local Supabase
./scripts/setup-supabase.sh
# Start edge functions locally (requires Deno)
./scripts/start-backend.sh
# Start AI agents
./scripts/start-ai-agents.sh
# Stop AI agents
./scripts/stop-agents.shMain app configuration (copy from Config.example.xcconfig):
SUPABASE_URL = https://your-project.supabase.co
SUPABASE_ANON_KEY = your-anon-key
SUPABASE_FUNCTIONS_URL = https://your-project.functions.supabase.co
S3_UPLOAD_ENDPOINT = $(SUPABASE_FUNCTIONS_URL)/generate-upload-url
MOCHAIN_CHAT_ENDPOINT = $(SUPABASE_FUNCTIONS_URL)/mochain
MUSHLIFTS_CHAT_ENDPOINT = $(SUPABASE_FUNCTIONS_URL)/mushliftsRuntime configuration (copy from Info.plist.example):
<key>SUPABASE_URL</key>
<string>http://127.0.0.1:54321</string> <!-- Local dev -->
<key>SUPABASE_ANON_KEY</key>
<string>your-local-anon-key</string>
<!-- AI Endpoints -->
<key>MOCHAIN_CHAT_ENDPOINT</key>
<string>http://127.0.0.1:54321/functions/v1/mochain</string>
<key>MUSHLIFTS_CHAT_ENDPOINT</key>
<string>http://127.0.0.1:54321/functions/v1/mushlifts</string>
<!-- Media -->
<key>S3_UPLOAD_ENDPOINT</key>
<string>http://127.0.0.1:54321/functions/v1/generate-upload-url</string>Glassmorphic toolbar with 5 AI actions available in conversations:
- Summarize β¨ - Generate thread summary
- Actions β - Extract action items with owners
- Decisions π - Find agreed-upon decisions
- Search π - Semantic search within conversation
- Translate π - On-device message translation
Implemented in AIBottomBar.swift
WhatsApp-style delivery receipts:
- β (Gray) - Sent to server
- ββ (Gray) - Delivered to recipient device
- π΅ββ (Blue) - Read by recipient
Managed by ChatService+Messages.swift with real-time updates via observers.
Real-time online/offline status:
- Heartbeat: 60-second intervals update
users/{userId}/presence/isOnline - Last Seen: Displays "last seen X ago" when offline
- Typing Indicators: Real-time typing status per conversation
- Auto-Cleanup: Observer pattern ensures presence updates stop when view dismissed
Implemented in PresenceService.swift
Comprehensive offline-first architecture:
- SwiftData Persistence - All messages/conversations cached locally
- Optimistic UI - Messages appear instantly, sync in background
- Network Monitor - Detects connectivity changes, shows offline banner
- SyncService - Queues operations, auto-syncs when online
- Conflict Resolution - Server timestamp wins on conflicts
See SyncService.swift and NetworkMonitor.swift
Centralized design tokens in MessageAI/Theme/:
// Colors.swift - Semantic color system
Color.brandBlue
Color.aiActionPurple
Color.textPrimary
Color.backgroundPrimary
// Typography.swift - Text styles
Font.headline
Font.bodyText
Font.caption
// Shadows.swift - Shadow presets
View().shadow(.card)
View().shadow(.elevated)
// Spacing.swift - Consistent spacing
Spacing.xs // 4pt
Spacing.sm // 8pt
Spacing.md // 16pt
Spacing.lg // 24pt- Update
Config.xcconfigwith production Supabase credentials - Update
Info.plistwith production endpoints - Deploy all Edge Functions to Supabase
- Set up AWS S3 bucket and CloudFront distribution
- Configure APNs certificates and upload to Supabase
- Set
OPENAI_API_KEYsecret in Supabase - Test AI features with production API keys
- Enable Supabase RLS policies on all tables
- Test on physical device with production backend
- Remove debug views from production builds
- Update app version and build number
- Monitor Supabase usage and costs
- Monitor OpenAI API usage
- Monitor S3/CloudFront bandwidth
- Set up error tracking (Sentry, etc.)
- Monitor APNs delivery rates
- Review performance metrics
- Gather user feedback on AI accuracy
This is a reference implementation showcasing modern iOS + Supabase architecture with AI integration. Feel free to:
- Fork and customize for your use case
- Report issues or suggest improvements
- Use as learning material for SwiftUI + Supabase
- Extend with additional AI features
See LICENSE file for details.
- Built with Supabase
- AI powered by OpenAI
- Media delivery via AWS S3 and CloudFront
- On-device AI via Apple CoreML and Foundation Models
MessageAI - Intelligent messaging for distributed teams. Built with β€οΈ using SwiftUI and Supabase.