* Add MARK headers to improve code organization in major files
* Reorganize peer management functions in BluetoothMeshService
- Removed duplicate getCurrentPeerID(for:) function
- Consolidated peer identity functions in Peer Identity Mapping section
- Moved getPeerFingerprint(), getFingerprint(for:), isPeerIDOurs() to proper location
- Moved getCurrentPeerIDForFingerprint() and getCurrentPeerIDs() from Message Sending section
- Moved notifyPeerIDChange() to Peer Management section
* Consolidate peer management functions in BluetoothMeshService
- Moved getCachedPublicKey() and getCachedSigningKey() from Identity Cache Methods to Peer Connection Management
- Moved getPeerNicknames() and getPeerRSSI() to Peer Connection Management section
- Moved getAllConnectedPeerIDs(), notifyPeerListUpdate(), and cleanupStalePeers() to Peer Connection Management
- Removed duplicate function declarations after consolidation
- Improved code organization by grouping all peer-related functions together
* Consolidate message handling functions in ChatViewModel
- Moved handleHandshakeRequest() from floating location to Message Reception section
- Moved trimMessagesIfNeeded() and trimPrivateChatMessagesIfNeeded() to Message Batching section
- Improved code organization by grouping related message handling functions together
- Removed unnecessary comments from trim functions
* Improve ContentView organization with better documentation
- Added descriptive comments for complex inline computations
- Documented message extraction logic for private vs public chats
- Documented peer data computation and sorting logic
- Improved code readability by explaining complex operations inline
- Note: Attempted to extract complex computations into helper functions, but SwiftUI scope limitations made inline documentation a better approach
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
- Added didSet observer to nickname property to trim on every change
- Trim nickname when loading from UserDefaults
- Update validateAndSaveNickname to properly trim
- Trim received nicknames in announce packets
- Add custom init/decoder for NoiseIdentityAnnouncement to ensure trimming
- Trim nicknames when decoding from binary data
- Add handshakeRequest packet type (0x25) to notify recipients about queued messages
- Create HandshakeRequest struct with binary encoding for efficient transmission
- Send handshake requests when messages are queued due to missing session
- Display notifications when someone wants to send messages
- Fix verification persistence bug by adding forceSave on app termination
- Update UI to handle optional encryption icons (hide when no handshake attempted)
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* send nonce in packet
* sliding window and 8 byte nonce
* do not process encrypted messages that arent addressed to us, same for nacks
* compiler error: remove comma
* nonce window 4 bytes
* clean up logging
* Remove sequence numbers from protocol
- Remove sequenceNumber field from BitchatPacket struct
- Update BinaryProtocol to not encode/decode sequence numbers (header size reduced from 17 to 13 bytes)
- Replace sequence-based duplicate detection with content-based using packet ID hash
- Update packet ID generation to use SHA256(senderID + timestamp + type + payload prefix)
- Remove all sequence tracking variables and methods
- Simplify duplicate detection to rely on timestamp and content hashing
* Fix connection stability issues
- Increase peer availability check interval from 5 to 15 seconds
- Fix availability logic to not mark connected peers as unavailable
- Add BLE connection keepalive timer (20s) to prevent iOS timeouts
- Fix missing delivery ACKs by passing peripheral context through Noise decryption
- Reduce identity announce frequency from 2 to 10 seconds minimum
- Remove unnecessary identity announces on connection
- Debounce identity cache keychain saves (2 second delay)
- Add message retry notification handler in ChatViewModel
- Fix version negotiation redundancy by checking existing negotiations
- Keep Noise sessions for already-connected peers
* Fix build errors in message retry handler
- Fix reference to 'displayedMessages' - should be 'messages'
- Fix sendMessage call signature to use individual parameters instead of message object
- Both iOS and macOS builds now succeed
* Fix remaining connection stability issues
- Fix duplicate identity announces with content-based deduplication
- Simplify peripheral mapping with cleaner temp ID to peer ID transitions
- Improve graceful leave detection across peer ID rotations
- Track previousPeerID from announcements to maintain state
- Add time-based cleanup for gracefully left peers
* Fix connection stability issues
- Add special duplicate detection for identity announces
- Simplify peripheral mapping with dedicated structure
- Improve graceful leave detection with peer ID rotation handling
- Track graceful leave timestamps for cleanup
- Transfer states properly during peer ID rotation
* Improve BLE connection stability and message reliability
- Increase peer availability timeout from 5s to 15s to prevent flapping
- Add BLE keepalive timer with 30s interval to maintain connections
- Fix missing delivery ACKs by passing peripheral context through decryption
- Reduce identity announce frequency from 2s to 10s minimum interval
- Add keychain save debouncing with 2s delay to prevent excessive writes
- Implement message retry system for failed deliveries to favorites
- Fix version negotiation redundancy by checking existing state
- Add special duplicate detection for identity announcements
- Implement graceful leave detection with peer ID rotation support
- Simplify peripheral mapping to reduce complexity
- Fix switch statement structure issues causing build errors
These changes significantly improve connection stability, eliminate peer availability flapping, and ensure reliable message delivery.
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
- Add 150ms debounce to text field onChange handler
- Prevents excessive autocomplete calculations during rapid typing
- Add timer cleanup in onDisappear
- Works for both main chat and private chat inputs
- Added message batching system with 100ms window
- Created pendingMessages array for public messages
- Created pendingPrivateMessages dictionary for private messages
- Added scheduleBatchFlush() to consolidate updates
- Batch all incoming messages from didReceiveMessage
- Batch system messages (connect/disconnect/screenshot)
- Keep immediate updates for user's own sent messages
- Single UI update per batch instead of per message
- Flush pending messages on app background/terminate
- Clear timer on deinit
This reduces UI updates when multiple messages arrive quickly
- Added font weight logic to formatMessageAsText and formatMessage
- User's own @nickname appears bold (weight: .bold)
- Other nicknames remain medium weight
- Helps visually distinguish own messages from others
- Simplified getSenderColor to always return primary color
- Removed RSSI color calculation logic from formatMessageAsText
- Removed RSSI color calculation logic from formatMessage
- All sender names now use consistent green color
- RSSI information remains visible only in peer list
- Cache getRSSIColor results with key format: "\(rssi)_\(isDark)"
- Cache getEncryptionStatus results with peerID as key
- Add cache invalidation methods for both caches
- Invalidate encryption cache when:
- Encryption status is updated
- Fingerprints are verified
- Peer authentication callbacks trigger
- Invalidate RSSI cache when peer list updates
- Clear all caches in panicClearAllData
This reduces redundant calculations during view updates and improves performance
- Add URL detection to message formatting with blue color and underline
- Replace List with ScrollView for precise spacing control
- Use minimal vertical padding (1px) between messages
- Remove LazyLinkPreviewView, use LinkPreviewView directly
- URLs now appear highlighted in message text AND show preview below
- Reduce VStack spacing from 4 to 2 and nested VStack from 2 to 0
- Set list row insets top/bottom to 0 to minimize spacing on iPhone
- Remove all markdown link parsing and formatting
- Share plain URLs instead of markdown when using share extension
- Keep only plain text URL detection and preview functionality
- Convert BitchatMessage from struct to class for efficient caching
- Cache formatted AttributedStrings to avoid expensive regex on every render
- Replace ScrollView+LazyVStack with native List for better cell reuse
- Implement message windowing (show last 100 messages for performance)
- Add LazyLinkPreviewView that defers loading for 0.5s to improve scroll performance
These optimizations significantly improve scroll performance, especially with large message lists.
- Validate nickname only when field loses focus or on submit
- Replace empty nicknames with anon+random 4 digits (e.g. anon3847)
- Remove auto-save timer to prevent validation while typing
- Add FocusState to detect when user exits the field
- Don't show PM notifications when the private chat is already open
- Store peer ID in notification userInfo for reliable chat opening
- Tap notification to open the correct private chat using peer ID
- Check both in ChatViewModel (when receiving) and NotificationDelegate (when presenting)
- Fix blank row appearing when peer disconnects by ensuring display names are never empty
- Add validation to prevent system messages with empty content from being displayed
- Fix API MISUSE warnings by adding connection state checks before writing to peripherals
- Improve write queue processing with additional safety checks
- Update activity tracking when processing queued writes
These fixes address UI glitches and improve Bluetooth reliability.
Always accept handshake initiations even with valid sessions, as the peer must have cleared their session for a good reason (e.g., decryption failure). This prevents deadlock where one peer has no session while the other maintains an invalid one.
- Add peer presence tracking with lastHeardFromPeer to detect reconnections
- Automatically send identity announcement when detecting peer reconnection after 30s
- Clear stale sessions when receiving handshake from recently-seen peer (likely restart)
- Add peers to activePeers when successfully decrypting their messages
- Fix thread safety in handshake coordinator with concurrent collections
- Extend message delivery timeouts (30s→120s private, 60s→180s room, 300s→600s favorite)
- Add per-peer encryption queues to prevent nonce desynchronization
- Make NoiseSession encrypt/decrypt operations thread-safe with barrier flag
- Initialize lastSuccessfulMessageTime when handshake completes
- Send identity announcement when decryption fails to prompt session reset
- Improve handshake state logging and debugging
This fixes:
- Peers stuck in "establishing encryption" after restart
- Nonce desynchronization causing "Decryption failed at nonce N"
- Asymmetric peer visibility (one peer sees the other but not vice versa)
- Thread safety issues causing crashes with pendingPrivateMessages
- Sessions marked as stale immediately after establishment
- Remove channel UI elements from ContentView
- Remove channel data structures and methods from ChatViewModel
- Remove channel commands (/j, /leave, /channels)
- Remove channel field from BitchatMessage protocol
- Remove channel message types and handling
- Remove NoiseChannelEncryption.swift entirely
- Clean up all channel references across the codebase
- Fix compilation warnings (var to let conversions)
- Remove all outdated test files that used incorrect APIs
- Simplify app to only support public broadcast and 1:1 private messages
- Replaced all print() calls with appropriate SecureLogger.log() calls
- Used proper categories: noise, encryption, session, security
- Applied appropriate log levels: debug, info, warning, error
- Converted 25 prints in BluetoothMeshService.swift
- Converted 1 print in ChatViewModel.swift
- Converted 8 prints in DeliveryTracker.swift
- Test files kept as-is for debugging purposes
- Verified successful build on iOS
This improves security by using structured logging that can filter sensitive data.
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Changed toolbar text from "bitchat*" to "bitchat/" with tighter spacing
- Removed blue intro message when no peers are connected
- Changed RSSI indicator back to simple dot instead of radiowaves icon
- Added triple-tap gesture on chat area to clear current context
- Improved LinkPreviewView performance with metadata caching
- Moved link previews closer to messages for better visual connection
- Fixed AppInfoView duplication by consolidating strings into single location
- Better error handling for link preview ATS errors
In my testing the app crashes in the background when receiving a notification. This is probably due to UIFeedbackGenerator requiring the main thread which isn't available
- Moved encryption/handshake status icons to appear after peer names in sidebar and private message headers
- Converted private messages and channels to slide-over views with smooth transitions
- Added swipe-right gesture to dismiss private chats and channels
- Added vertical separator bars to slide-over views for visual consistency
- Add version negotiation messages (0x20 versionHello, 0x21 versionAck)
- Implement VersionHello and VersionAck message types with platform info
- Add ProtocolVersion struct for version management and negotiation
- Update BinaryProtocol to check supported versions
- Add version negotiation to connection flow before Noise handshake
- Maintain backward compatibility with legacy peers (assume v1)
- Add comprehensive test suite with 40+ test cases
- Update documentation with version negotiation details
This ensures BitChat clients can negotiate protocol versions for smooth
upgrades while maintaining full backward compatibility with existing clients.
- Implement share extension to receive URLs from other apps
- Display shared links with emoji indicator and rich preview cards
- Add custom compact link preview with image, title, and domain
- Configure app groups for data sharing between extension and main app
- Handle URL detection and parsing in share extension
- Update message formatting to show only emoji for shared links
- Add proper entitlements and activation rules for share extension
- Add content validation to skip empty or whitespace-only messages
- Apply validation in both channel and regular message handling
- Add validation at retry service level to prevent queuing empty messages
- This fixes the phantom space issue between synced messages
- Introduce thread safety for recentlySentMessages using NSLock to prevent race conditions.
- Adjust message delay parameters for faster synchronization: reduce min/max message delays and adjust initial announce timing.
- Update sendMessage and sendEncryptedRoomMessage methods to accept optional messageID and timestamp parameters for better tracking.
- Improve message deduplication logic in ChatViewModel to prevent duplicates from being added when echoing back sent messages.
- Modify MessageRetryService to include original message ID and timestamp for better retry handling.
- Screenshot notifications now properly appear as system messages
- Send messages directly via mesh service to avoid local echo
- Remove 'private:' prefix from private chat header
- Keep only lock icon and peer name in private chat header
- Detect when users take screenshots on iOS
- Send system notification to all participants
- Works in public chat, channels, and private messages
- Display screenshot notifications as system messages
- Change @user to @name in all documentation
- Change 'blocked users' to 'blocked peers' for consistency
- Add /block and /unblock commands to autocomplete menu
Implemented user blocking functionality:
- /block <nickname> - blocks a user from private messaging and ignores their messages in channels
- /block - lists all blocked users
- /unblock <nickname> - unblocks a user
Implementation details:
- Blocks are stored by public key fingerprint for persistence across sessions
- Blocked users cannot send private messages or have their public messages displayed
- Blocked users are silently ignored (they don't know they're blocked)
- Blocking a user automatically removes them from favorites
- Added getPeerPublicKey() method to BluetoothMeshService for accessing peer identity keys
- Changed system messages from green to grey with consistent 12pt font
- Fixed text wrapping to flow naturally under timestamps
- Changed default nickname to anonXXXX format
- Replaced text with icon representations in status bar
- Added icons to sidebar section headers
- Made autocomplete UI consistent between commands and @mentions
- Added welcome message for new users (3 second delay)
- Changed sidebar header to 'YOUR NETWORK'
- Added command aliases (/join, /msg)
- Implemented /hug and /slap commands with haptic feedback
- Improved command help display with alphabetization
- Renamed 'rooms' to 'channels' throughout entire codebase
Critical fixes:
1. Match messages by sender nickname in addition to peer ID (since peer IDs change)
2. Send read receipts to CURRENT peer ID, not old senderPeerID from message
3. Remove requirement for senderPeerID to be non-nil (blocks older messages)
4. Add extensive logging to trace the flow
The core issue was that peer IDs are ephemeral and change between sessions:
- Rick sends message with peer ID A
- Later, Jack connects to Rick who now has peer ID B
- Read receipt needs to be sent to B, not A
- Messages need to be matched by nickname, not just peer ID
- Added logic to prevent downgrading from 'read' status to 'delivered'
- When an ACK arrives after a read receipt, the read status is preserved
- This fixes the issue where blue checkmarks briefly appear then revert to green
- Applied fix to all message types (main, private, room)
- Added app activation observer to send read receipts when app becomes active
- Send read receipts for all unread messages when receiving a new message while chat is open
- Added import for NSApplication/UIApplication notifications
- This ensures messages are marked as read even when opening chat from notifications or returning to app
- Added delay to ensure messages are loaded before checking
- Fixed logic to check if message is FROM the other person (not TO them)
- Added onAppear handler to send read receipts when view loads
- Added detailed logging to debug the flow
- Now correctly identifies received messages that need read receipts