Commit Graph
51 Commits
Author SHA1 Message Date
jack 0ab1f2ecfd Add public domain license and copyright headers
- Added LICENSE file with Unlicense (public domain dedication)
- Added public domain headers to all main source files
- Updated README to mention public domain status
- All code is free and unencumbered, released into the public domain

Anyone is free to use this code for any purpose without restriction.
2025-07-04 16:21:49 +02:00
jack 87d4455c25 Fix peer discovery stability and connection cycling issues
- Added debouncing for peer list updates (500ms) to prevent UI spam
- Fixed race conditions in activePeers management by adding proper locking
- Prevent duplicate key exchange processing with tracking set
- Only notify delegate when peer list actually changes
- Fixed thread safety issues in disconnect/unsubscribe handlers
- Clear processed key exchanges periodically with bloom filter

This resolves the rapid connect/disconnect cycles and excessive peer list updates.
2025-07-04 16:19:52 +02:00
jack 9ef9ef8056 Fix timestamp bug causing peer discovery failures
- Fixed BitchatPacket convenience initializer to use milliseconds (was using seconds)
- Fixed BitchatMessage binary encoding to use milliseconds for consistency
- Updated decoding logic to properly handle millisecond timestamps
- This resolves the issue where packets were being dropped due to timestamp validation failures

All timestamps are now consistently in milliseconds throughout the codebase.
2025-07-04 16:07:49 +02:00
jack 6023ff8af0 Fix thread safety issue causing peer count to show 0
- Add thread safety lock for activePeers Set access
- Force UI update when peer list changes with objectWillChange
- Add debug logging to track peer additions/removals
- This fixes the 'alone :/' display when peers are actually connected
2025-07-04 15:59:56 +02:00
jack be08f4c8a7 Fix peer discovery issue by enabling announce relay
- Increase announce TTL from 1 to 3 to allow relaying
- Add relay logic for announce packets (was missing\!)
- This fixes the issue where peers can chat but don't see each other
- Announces now propagate through the mesh properly
2025-07-04 15:53:35 +02:00
jack aa8fe7527a Remove backwards compatibility code
- Remove timestamp conversion for old clients (seconds vs milliseconds)
- Remove fallback for old favorite checking method
- All clients must now use millisecond timestamps
- Simplifies codebase and reduces potential bugs
2025-07-04 15:49:01 +02:00
jack 38a7ba07ee Fix connection tracking and timestamp compatibility issues
- Fix 'alone :/' bug by not requiring nicknames for peer counting
- Handle both second and millisecond timestamps for compatibility with older clients
- Fix NaN errors in autocomplete positioning with bounds checking
- Simplify getAllConnectedPeerIDs to show all valid active peers
- Add timestamp conversion logic to handle ~55 year time difference bug
2025-07-04 15:45:29 +02:00
jack 986106fea4 Fix warnings and improve autocomplete positioning, add unit tests
- Remove unused variables (beforeCount, beforeFavCount)
- Remove Tx Power Level from advertising (not allowed)
- Fix autocomplete popup to appear near cursor position
- Calculate position based on nickname width and @ location
- Add comprehensive unit tests for:
  - Binary protocol encoding/decoding
  - Message padding for privacy
  - Bloom filter duplicate detection
  - BitchatMessage serialization
- Add test target to project.yml
2025-07-04 15:40:47 +02:00
jack e3cc469bf8 Remove voice memo references and improve duplicate message prevention
- Remove NSMicrophoneUsageDescription from Info.plist and project.yml
- Add millisecond timestamps to prevent same-second message collisions
- Include payload hash in message ID for absolute uniqueness
- Add recentlySentMessages tracking to prevent any duplicate sends
- Reduce retries from 2 to 1 for broadcast messages
- Clean up sent message tracking after 10 seconds
2025-07-04 15:35:26 +02:00
jack da44be9449 Add Bluetooth optimizations for maximum range
- Add TX power level hint to advertising for better signal strength
- Add comment about BLE 5.0 2M PHY support (iOS handles automatically)
- These optimizations help achieve maximum 300m+ range
2025-07-04 15:28:57 +02:00
jack b22c6e4bc6 Improve relay mechanism for better message delivery distance
- Increase max TTL from 5 to 7 hops for long-distance delivery
- Keep TTL higher in larger networks (6 for small, 5 for medium, 4 for large)
- Increase relay probabilities (85% at 30 users, 70% at 50 users, min 40%)
- Smart relay: always relay if TTL >= 4 or few peers connected
- Boost relay probability by 15% for private messages (they're important)
- Clean up excessive logging while keeping duplicate detection warnings
- Ensure messages can travel 300m+ by maintaining higher relay rates
2025-07-04 15:22:09 +02:00
jack 7b24293666 Add duplicate message detection logging and improve connection timing
- Track exact message content and timestamps to detect duplicates
- Log when duplicate messages are received within 5 seconds
- Delay sending cached messages by 0.5s to ensure connection is established
- Log all incoming message IDs and types for debugging
- Add warning when same message is received multiple times
2025-07-04 15:15:03 +02:00
jack 975c86e6f3 Add comprehensive logging to store-and-forward system for debugging 2025-07-04 15:08:29 +02:00
jack a569b87a18 Fix store-and-forward duplicate message delivery and timestamp ordering
- Add tracking to prevent sending cached messages multiple times to the same peer
- Only cache messages for offline favorites, not online ones
- Sort messages by timestamp when adding to ensure proper chronological order
- Clean up tracking sets when peers disconnect to allow re-sending on reconnect
- Cache our own messages when sending to offline favorites
- Update favorite online notification text to "wanna get in there?"
2025-07-04 15:02:49 +02:00
jack 3c894bcb2f Fix store-and-forward to properly deliver once and remove
- Filter cached messages by recipient (only send to intended peer)
- Remove messages from cache after successful delivery
- Stop caching broadcast messages (they're not targeted)
- Add safety check to never cache broadcasts
- Messages are now delivered exactly once per recipient

The store-and-forward system now correctly:
1. Stores only private messages for specific recipients
2. Delivers only to the intended recipient when they connect
3. Removes messages after delivery to prevent duplicates
4. Preserves original timestamps throughout the process
2025-07-04 14:43:36 +02:00
jack 31abe1a1ce Fix remaining Bluetooth write errors
- Check characteristic write properties before all writes
- Add proper error handling for specific BLE error codes
- Rediscover services on invalid handle errors
- Increase delay between key exchange and announce
- Reduce connection flooding by spacing out initial messages

The ATT Error 242 was caused by writing too quickly after
connection establishment. Adding delays gives the connection
time to stabilize.
2025-07-04 14:36:15 +02:00
jack 7b3cfb6227 Fix Bluetooth errors and improve store-and-forward
- Add peripheral state checks before all write operations
- Fix 'can only accept commands while connected' errors
- Check characteristic write properties to avoid ATT errors
- Preserve original timestamps in store-and-forward messages
- Only log crypto errors once per peer to reduce noise
- Store-and-forward now correctly maintains message ordering

The timestamp preservation ensures messages appear in the correct
chronological order even when delivered later via store-and-forward.
2025-07-04 14:30:00 +02:00
jack 3f882eec0f Fix thread safety crash with NSLock
- Replace problematic messageQueue.sync with NSLock for peerNicknames
- Prevents deadlock when accessing from within messageQueue
- Add thread-safe access to all peerNicknames read/write operations
- Fixes EXC_BREAKPOINT crash from recursive queue access

The previous approach using messageQueue.sync caused deadlock when
getAllConnectedPeerIDs was called from within the messageQueue itself.
2025-07-04 14:12:59 +02:00
jack a59c3f7ec6 Fix macOS crash and Bluetooth errors
- Fix NSInvalidArgumentException crash by adding thread-safe access to peerNicknames
- Fix 'can only accept commands while connected' by checking peripheral state
- Add safety checks for characteristic write properties
- Clean up disconnected peripherals from tracking
- Prevent type confusion in getAllConnectedPeerIDs

These fixes address the crash when accessing peerNicknames dictionary
which could be corrupted by concurrent access from multiple threads.
2025-07-04 13:49:14 +02:00
jack e6fcae6275 Fix RSSI display inconsistency between devices
- Add default RSSI value (-60) for connected peers without RSSI data
- Transfer RSSI from peripheral discovery to peer after key exchange
- Fixes red dot showing for nearby devices that can't report RSSI
- Centrals (phones acting as servers) now show green by default
2025-07-04 13:35:46 +02:00
jack 6f85faa6c0 Fix BLE advertisement warnings and duplicate registrations
- Remove 'Is Connectable' and 'Manufacturer Data' keys from BLE ads
- Only use allowed keys: service UUIDs and local name
- Prevent duplicate fingerprint registrations in favorites
- Comment out unused fragment type string variable

The warnings about advertisement keys should no longer appear.
2025-07-04 13:33:38 +02:00
jack 1e2717f152 Implement practical scaling optimizations for 50-100 users
- Probabilistic flooding: Relay probability adapts to network size (30-100%)
- Bloom filter duplicate detection: O(1) lookups with 4096-bit filter
- Connection pooling: Reuse connections with exponential backoff
- Adaptive TTL: Reduces hops based on network size (2-5)
- Message aggregation framework: 100ms batching window
- BLE advertisements: Include network size/battery hints

These optimizations improve capacity from ~20-30 to ~50-100 users while
maintaining privacy (no routing tables) and simplicity. The system now
adapts automatically to network conditions without configuration.

Trade-offs: Slightly higher CPU for bloom filter, probabilistic relay
may miss edge cases, but overall much better scaling behavior.
2025-07-04 13:26:37 +02:00
jack 2cd8443292 Remove grey overlay and reduce logging noise
- Removed grey background overlay during sidebar slide-over for cleaner UI
- Removed excessive logging while keeping critical error/security logs
- Kept only: error conditions, connection events, panic mode, security events
- Significantly reduced console noise for better production readiness
2025-07-04 12:28:00 +02:00
jack f77cec3fb2 Analyze scalability and prepare for TestFlight
- Deep analysis of mesh network scalability limits
- Current full mesh topology supports ~20-30 users maximum
- Identified bottlenecks: O(n²) connections, message flooding, battery impact
- Documented future scaling solutions: hierarchical topology, DHT routing
- Ready for TestFlight submission with current capacity constraints
2025-07-04 11:53:57 +02:00
jack cce43fcfc7 Add interactive logo with info/panic modes and battery optimization
- Single tap logo shows comprehensive app info and features
- Triple tap logo triggers panic mode (instant data wipe)
- Implement adaptive Bluetooth scanning based on battery level
- Remove hardcoded development team ID for security
- Fix store-and-forward description (12h for all, indefinite for favorites)
- Add technical debt remediation plan
- Fix macOS compatibility issues with navigation
2025-07-04 02:21:59 +02:00
jack c7baf31f03 Implement indefinite store-and-forward for favorite peers
- Change message cache timeout from 5 minutes to 12 hours for regular peers
- Add indefinite message storage for favorite peers with 1000 message limit
- Cache relayed messages for offline favorites
- Automatically send cached messages when favorites come online
- Use public key fingerprints to identify favorites persistently
- Add isFavorite delegate method to check favorites by fingerprint
2025-07-04 01:51:37 +02:00
jack fe986ed397 Fix encryption key exchange and add persistent identity for favorites
- Implement three-tier key system: ephemeral encryption, ephemeral signing, persistent identity
- Fix signature verification by properly separating KeyAgreement and Signing keys
- Add persistent identity key for favorites that survives app restarts
- Fix Data subscript crashes by converting to byte arrays
- Add proper error handling for key exchange
- Private messages remain fully encrypted with ephemeral keys
2025-07-04 01:43:16 +02:00
jack 34e51b3d9a Fix peer nickname display once and for all
- Only show peers in UI who have announced (have nicknames)
- Filter out peers without nicknames from getAllConnectedPeerIDs()
- Send announces proactively when app starts, not just on connection
- Send announces immediately when nickname changes via saveNickname()
- Send announces when Bluetooth services become available
- Send announces multiple times (0.5s, 1s, 2s) for reliability
- Add sendBroadcastAnnounce() method for proactive announcing

This ensures peers always see proper nicknames, never 'person-xxx'
2025-07-03 23:38:17 +02:00
jack 7e8c5d0153 Fix voice note fragment handling and narrow macOS sidebar
- Fix fragment processing bug where fragments were logged but not handled
- Remove redundant 'Processing fragment directly' check that prevented handling
- Make macOS sidebar narrower (300px max or 40% of width, whichever is smaller)
- iOS sidebar remains at 70% width for better touch interaction
2025-07-03 23:33:44 +02:00
jack 8346ecd2a7 Fix message display and add voice note debugging
- Fix escaped backslashes in timestamp and sender name display
- Add comprehensive logging for voice note transmission pipeline
- Add peripheral write completion logging
- Track broadcast success/failure for central updates
- Log audio recorder creation and preparation steps
- Better diagnostics for troubleshooting voice note issues
2025-07-03 23:28:07 +02:00
jack 78ddb36db7 Add tap-to-PM and favorite features
- Make sender names tappable in messages to start private chat
- Add star button in private chat header to favorite/unfavorite peers
- Refactor message view to separate timestamp, sender, and content
- Add helper methods for formatting different parts of messages
- Own sender name is not tappable (only other users)
- Voice notes remain tappable to play/pause
2025-07-03 23:24:30 +02:00
jack d6ae19e11e Enable notifications on macOS
- Add macOS support to NotificationService
- Use NSApplication.shared.isActive to check app state on macOS
- Move notification logic outside of iOS-only block in ChatViewModel
- Notifications now work for both mentions and private messages on macOS
- Keep haptic feedback iOS-only as it's not available on macOS
2025-07-03 23:21:29 +02:00
jack 63c0ed4960 Fix private message routing
- Add recipient ID to private message packets for proper routing
- Private messages now correctly include recipientID field
- Add comprehensive debug logging for private message flow
- Messages are now properly delivered to intended recipients
- Add asterisk after bitchat text in header
2025-07-03 23:20:07 +02:00
jack 6652d1f429 Fix voice recording and notification issues
- Fix mic button gesture handling by removing Button wrapper
  - Use direct gesture on ZStack for more reliable touch detection
  - Add debug logging for recording start/stop

- Fix notification delivery on iOS
  - Change from checking .background to checking != .active
  - Notifications now work when app is inactive or background
  - Add NSUserNotificationsUsageDescription to Info.plist

- Improve voice note fragment transmission
  - Reduce fragment size from 400 to 200 bytes for better reliability
  - Simplify fragment timing from batch-based to linear 100ms delays
  - Lower packet size threshold from 512 to 400 bytes for fragmentation
  - Add peripheral connection state checking before writes
  - Better error logging throughout transmission pipeline

- Add comprehensive debug logging for troubleshooting
  - Log audio file size and duration
  - Log peripheral connection states during broadcast
  - Log fragment send progress with timing info
2025-07-03 23:14:42 +02:00
jack 2993fc3e06 Implement favorites, notifications, and improve fragment handling
- Add favorites functionality for peers with persistent storage
  - Star icon to toggle favorites in sidebar
  - Favorites appear at top of peer list
  - Storage persists across app launches using peer ID

- Add local notifications for mentions and private messages
  - Notifications appear when app is in background
  - Separate notification types for mentions vs private messages
  - Request notification permissions on app launch

- Fix sidebar header alignment to match main toolbar (44pt)
  - Add background color to sidebar header for visual consistency

- Improve voice note fragment transmission
  - Send fragments in batches of 5 with delays to prevent congestion
  - Better logging to debug fragment transmission issues
  - Reduce delay between fragments from 50ms to batch-based timing

- Fix other UI issues
  - Ensure mic recording ripples originate from mic button
  - Update sidebar to swipe from right edge smoothly
2025-07-03 22:13:28 +02:00
jack 94a9888ef5 Add push-to-talk voice notes functionality
- Added voice note support to BitchatMessage with audio data and duration
- Updated binary protocol to encode/decode voice notes (flag 0x40)
- Created AudioRecordingService for recording up to 10s voice clips
- Created AudioPlaybackService for playing voice notes
- Added microphone permission to Info.plist and project.yml
- Implemented push-to-talk UI with mic button in ContentView
- Voice notes use AAC compression at 16kHz/32kbps for small file sizes
- Added play/pause buttons for voice notes in message list
- Voice notes display as '🎤 Voice note (X.Xs)' in chat
- Platform-specific audio session handling for iOS/macOS
2025-07-03 01:13:16 +02:00
jack d142fde11d Add @ autocomplete functionality
- Added autocomplete state tracking in ChatViewModel
- Implemented updateAutocomplete() to parse @ mentions and show suggestions
- Added completeNickname() to handle nickname completion
- Created autocomplete UI overlay above input field
- Shows list of matching nicknames when typing @
- Highlights selected suggestion
- Clicking suggestion completes the mention
2025-07-03 01:08:11 +02:00
jack 4b98aa7918 Fix iOS background BLE, RSSI tracking, and peer nickname display
- Add UIBackgroundModes for bluetooth-central/peripheral to restore background messaging
- Implement RSSI tracking with proper peer ID mapping and UI updates
- Fix announce packet delivery for immediate nickname display
- Convert to binary protocol for 62-69% size reduction
- Fix peer count to exclude self from display
- Add platform-specific UI improvements (font sizes, dropdown styling)
2025-07-03 00:51:59 +02:00
jack 20ebaa109c Convert JSON protocol to efficient binary format
- Implemented compact binary encoding for packets and messages
- Reduced packet size significantly (13-byte fixed header + variable payload)
- Optimized for BLE's limited MTU with smaller message sizes
- Added BinaryProtocol.swift with encode/decode functions
- Updated all message types to use binary serialization
- Maintains all existing functionality with better performance
2025-07-02 22:09:02 +02:00
jack f43d31b960 Fix iOS peer dropdown positioning
- Remove frame constraint on peer status view
- Add fixedSize() to menu label for compact layout
- Reduce internal spacing in menu label from 4 to 2 points
2025-07-02 21:46:04 +02:00
jack 16dded48b4 Reduce spacing between bitchat and peer dropdown
- Changed spacing from 12 to 8 points for tighter layout on iOS
2025-07-02 21:44:14 +02:00
jack 1eaba703e9 Fix peer dropdown layout and announcement timing
- Move peer dropdown next to bitchat title
- Add immediate peer announcement on connection
- Fix iOS menu chevron visibility with platform-specific styling
- Force UI updates for join/leave messages
- Add peers to active list immediately on connection
- Remove all announcement delays for instant name resolution
2025-07-02 21:39:31 +02:00
jack e50f14eeed Fix notification dot size and improve peer announcements
- Make notification dot smaller (5x5) for better appearance
- Remove all delays from announcement sending
- Send announcements immediately on connection
- Add debug logging for join/leave messages
- Ensure join/leave messages are properly displayed
2025-07-02 21:32:51 +02:00
jack d67e11cdab Update terminology to be more human-friendly
- Change 'nick:' to 'name:' in the UI
- Replace 'peer/peers' with 'person/people' throughout
- Update 'No peers connected' to 'No people connected'
- Fix menu layout with fixedSize()
- Update debug messages to use 'people' instead of 'peers'
2025-07-02 21:25:35 +02:00
jack b517cb7cc3 Clarify peer dropdown UI elements order
- Added comments to clarify the order: dot, text, chevron
- Notification dot works on both macOS and iOS
- Elements are properly ordered left to right
2025-07-02 21:21:04 +02:00
jack 13686b3ce9 Fix private message notifications and chat updates
- Remove self-notification when sending private messages
- Clear unread indicator when viewing active chat
- Properly update UI when private messages are sent/received
- Prevent duplicate messages in chat history
- Use objectWillChange to force SwiftUI updates
2025-07-02 21:19:32 +02:00
jack fc5eba4a58 Fix header bouncing and add private message notifications
- Fix header bar height to prevent bouncing when switching views
- Add in-app notification banner for incoming private messages
- Show orange notification that slides down from top
- Tap notification to jump directly to private chat
- Use medium haptic feedback for private messages (iOS)
- Auto-dismiss notifications after 3 seconds
2025-07-02 21:14:42 +02:00
jack 5c9d2122dc Add private chat feature and fix peer discovery issues
- Implement 1:1 private messaging with IRC-style interface
- Add private message type to protocol with routing through mesh
- Show orange notification dot for unread private messages
- Fix peer list not showing connected peers
- Update peer nicknames immediately on first message
- Auto-exit private chat when peer disconnects
- Improve join/leave channel messages visibility
- Make send button larger for better UX
- Center and color private chat header in orange
2025-07-02 21:11:12 +02:00
jack 304c121467 Fix peer discovery: include connected peripherals in peer list even before announce 2025-07-02 19:26:36 +02:00
jack 3c38bdc791 Add debug logging to troubleshoot peer discovery issues 2025-07-02 19:20:57 +02:00
jack 7e90bf6369 Initial commit: Bluetooth mesh chat app with end-to-end encryption 2025-07-02 19:18:35 +02:00