NoiseCoverageTests' session-callback test failed on the first CI run
that actually executed it (every run since it landed had hung and been
killed before completion): onSessionEstablished fires via
DispatchQueue.global().async, and the test waited only 0.5s — fine on
a dev machine, too tight on a loaded CI runner saturated by parallel
test workers.
Raise every positive-wait timeout from 0.5s to 5s (matching
TestConstants.defaultTimeout) across the suites that poll for async
callbacks. waitUntil returns as soon as the condition holds, so
passing runs are unaffected; only genuine failures wait longer. The
two negative waits in BLEServiceCoreTests ("expect nothing arrives")
deliberately keep their short windows.
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Exclude perf baselines from parallel CI via --skip; sample hung tests
Every app-suite CI run since the perf baselines landed (#1335) has
timed out at the 15-minute job limit — main has been red for five
consecutive runs. The job logs show the PerformanceBaselineTests
fixtures dispatched into the parallel phase despite the
BITCHAT_SKIP_PERF_BASELINES env guard from #1336, followed by ~11
minutes of silence until the timeout kills swiftpm-testing. The suite
passes locally in seconds with identical flags, so the hang is
specific to the CI toolchain/runners — consistent with the known
XCTest-measure-under-parallel-workers hang the serial step was
created to avoid.
Two changes:
- Exclude the baselines from the parallel phase with --skip at the
SPM level, which removes them from the worker processes entirely
instead of relying on the env guard reaching setUpWithError. They
still run (and gate) in the dedicated serial step.
- Wrap the parallel run in a 10-minute watchdog that samples any
still-running test processes before killing them, so if anything
else ever hangs, the run fails fast with thread stacks in the log
instead of a silent 15-minute timeout.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Arm the test-hang watchdog only for the test execution phase
Codex review: swift test builds before running, so the watchdog timer
included dependency resolution and compilation — a cold-cache coverage
build on a slow runner could be killed before tests ever started.
Build the tests in their own step (bounded by the 15-minute job
timeout like any build) and run the watchdog around swift test
--skip-build, tightened to 5 minutes now that it times only test
execution.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Hammer transport thread-safety tests from the dispatch pool, not the cooperative pool
The watchdog added in this PR captured the actual CI hang twice, with
identical stacks both times: NostrTransportTests' 100-task groups park
every Swift Concurrency cooperative thread in a blocking queue.sync
(the pool has one thread per core — 3 on CI runners, 10+ on dev
machines, which is why this never reproduced locally). Blocking the
entire cooperative pool violates the forward-progress contract, and
the runners' dispatch wedges under the resulting asyncAndWait flood —
taking concurrently running tests down with it (the panic-reset test
deadlocked in a serviceQueue barrier that never got scheduled).
Run the same 100 concurrent hammer iterations via
DispatchQueue.concurrentPerform from a single global-queue hop instead:
identical thread-safety coverage, executed on dispatch worker threads
where blocking is legal, zero cooperative threads parked.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Centralize UI theme colors into semantic ThemePalette tokens
Introduce AppTheme/ThemePalette (Utils/Theme.swift) with an environment
key and @ThemedPalette property wrapper, persisted via @AppStorage.
Views now resolve background/primary/secondary/accentBlue/alertRed/
divider tokens from the environment instead of computing colors inline,
removing the backgroundColor/textColor/secondaryTextColor prop-drilling
through the header, composer, and people-sheet hierarchy.
Matrix theme output is pixel-identical; this is groundwork for a
user-selectable theme switcher.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Add liquid glass theme with in-app appearance switcher
Add a .liquidGlass AppTheme alongside the matrix terminal theme,
selectable from a one-line APPEARANCE row in the app info sheet
(persisted via @AppStorage, applies live).
Liquid glass renders system fonts and colors over a subtle gradient
backdrop, with the header and composer floating as Liquid Glass panels
(real .glassEffect() on iOS/macOS 26, compiler-gated with an
ultraThinMaterial fallback for older SDKs). The message list scrolls
underneath the chrome via safe-area insets, and all sheets share the
same backdrop and surface language. The matrix theme is unchanged.
Details:
- Theme is threaded through ChatMessageFormatter so message
AttributedStrings switch font design per theme; the per-message
format cache gains a variant key so themes never serve each other's
cached strings
- New palette tokens: accent (interactive tint) and locationAccent
(geohash green), replacing scattered hardcoded greens/blues in the
voice note, waveform, verification, and people-sheet views
- Header controls get full-height tap targets and the people count
becomes a real Button (previously a tap gesture on the cluster)
- CommandSuggestionsView renders nothing when empty instead of a
zero-height view that pushed the composer input off-center
- New appearance strings localized for all 29 catalog languages
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Make location notes robust: durable relay subscriptions, failure decay, auto-recovery
Location notes (and geohash chat / DMs) intermittently stopped showing
events because the Nostr relay layer lost subscriptions and blacklisted
relays:
- Replay active subscriptions on every relay (re)connect. Relays drop
REQs with the socket; previously a drop silently killed the
subscription on that relay for the rest of the session. Durable
subscription intent now also survives disconnect()/resetAllConnections
(background -> foreground).
- Keep failed REQ sends queued instead of dropping them.
- Raise the EOSE fallback from a fixed 2s Timer to a 10s injected
schedule (Tor needs more than 2s), and settle EOSE trackers when a
relay disconnects before answering so initial load doesn't stall.
- Decay "permanently failed" relay markings after a 10-minute cooldown;
previously ~9 minutes of outage (or one DNS hiccup) excluded a relay
until app restart, with nothing resetting it on macOS.
- Make geo relay selection deterministic (distance, then host) so
publishers and subscribers with the same directory agree on relays.
- Post .geoRelayDirectoryDidRefresh after a directory fetch and let
LocationNotesManager auto-resubscribe out of the "no relays" state
instead of requiring a manual retry.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Guard subscription activation on connection identity
A REQ send completion from a dead socket could land after
handleDisconnection cleared the relay's subscriptions and re-mark the
subscription active, making the next connection skip the durable replay
and leave that relay silent. Only mark a subscription active if the
completing socket is still the relay's live connection.
Regression test defers send completions in the mock so the stale
completion deterministically interleaves between disconnect and
reconnect.
Addresses Codex review on #1333.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Refactor BLE transport event handling
* Make image output paths unique
* Keep queued Nostr read receipts alive
* Refine BLE ingress fanout
* Rediscover BLE service after invalidation
* Extract BLE notification retry buffer
* Extract BLE inbound write buffer
* Extract BLE fragment assembly buffer
* Tidy secure log handling from device run
* Extract BLE outbound fragment scheduler
* Harden app CI media tests
* Redact BLE message content from logs
* Extract BLE Noise session queues
* Fix BLE read receipt UI updates
* Allow self-authored RSR ingress replies
* Harden read receipt queue test timing
* Extract BLE outbound policy and incoming file storage
* Avoid duplicate BLE link snapshots during send
* Canonicalize Nostr relay URLs
* Extract BLE link state store
* Extract BLE connection scheduler
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Refactor BLE transport event handling
* Make image output paths unique
* Keep queued Nostr read receipts alive
* Refine BLE ingress fanout
* Rediscover BLE service after invalidation
* Extract BLE notification retry buffer
* Extract BLE inbound write buffer
* Extract BLE fragment assembly buffer
* Tidy secure log handling from device run
* Extract BLE outbound fragment scheduler
* Harden app CI media tests
* Redact BLE message content from logs
* Extract BLE Noise session queues
* Fix BLE read receipt UI updates
* Allow self-authored RSR ingress replies
* Harden read receipt queue test timing
* Extract BLE outbound policy and incoming file storage
* Avoid duplicate BLE link snapshots during send
* Canonicalize Nostr relay URLs
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Refactor BLE transport event handling
* Make image output paths unique
* Keep queued Nostr read receipts alive
* Refine BLE ingress fanout
* Rediscover BLE service after invalidation
* Extract BLE notification retry buffer
* Extract BLE inbound write buffer
* Extract BLE fragment assembly buffer
* Tidy secure log handling from device run
* Allow self-authored RSR ingress replies
* Harden read receipt queue test timing
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Run GeoRelay fetch pipeline off main actor
* Capture GeoRelay session before detached fetch
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Expand protocol coverage with edge-case tests
* Stabilize read receipt transport test
* Stabilize BLE duplicate packet test
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Expand coverage for transport, chat, and media flows
* Stabilize transport and media coverage tests
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Expand coverage for relay, identity, and location flows
* Fix macOS SwiftPM CI failures
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* fix: Rate limit iOS peer notifications to prevent flood
- Remove aggressive formIntersection that cleared recentlySeenPeers
when peers temporarily dropped, causing them to be treated as "new"
- Add 5-minute cooldown between notifications (aligns with Android)
- Use fixed notification identifier so iOS updates existing notification
instead of creating new ones
- Only mark peers as seen when notification is sent, so peers arriving
during cooldown are included in the next notification
Fixes notification spam every 10-30 seconds when peers fluctuate.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* chore: Bump version to 1.5.1
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* Improve BLE mesh reliability for large transfers
Major reliability improvements for fragment-based transfers (photos, files):
**Notification Queue Fixes**
- Fix silent packet loss when notification queue is full - now queues for retry
- Fix retry queue bug where remaining items were lost when one retry failed
- Add periodic drain mechanism as backup (every 5 seconds)
**Write Queue Fixes**
- Fix drainPendingWrites to use atomic take-send-requeue pattern
- Add logging when peripheral is ready for more writes
- Add periodic drain for pending writes as backup
**Fragment Pacing**
- Increase fragment spacing from 4-5ms to 25-30ms to prevent buffer overflow
- Conservative pacing prevents packet loss on congested BLE connections
**Thread Safety**
- Fix race conditions in stopServices() and emergencyDisconnectAll()
- Synchronize access to peripherals/centrals dictionaries during cleanup
- Clear pending message queues in emergencyDisconnectAll()
**Error Recovery**
- Add handlers for all BLE state transitions (poweredOff, unauthorized, etc.)
- Clear Noise session and re-initiate handshake on decryption failure
- Queue ACKs/receipts for delivery after handshake instead of dropping
- Re-queue failed pending messages for retry
**Other Improvements**
- Add route freshness validation in MeshTopologyTracker (60s threshold)
- Add TTL (24h) and size limits (100 per peer) for MessageRouter outbox
- Fix connection timeout to check peripheral.state before canceling
- Add NoiseEncryptionService.clearSession(for:) method
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix race condition and increase test timeouts
- Fix race in sendNoisePayload: use sync barrier instead of async
to ensure payload is queued before initiating handshake
(addresses Codex review feedback)
- Increase BLEServiceTests sleep from 0.5s to 1.0s for CI reliability
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* Add comprehensive test coverage for ChatViewModel and BLEService
This commit adds 14 new tests to improve the safety net for future
refactoring of ChatViewModel and BLEService:
New test files:
- ChatViewModelTorTests: Tor lifecycle notification handlers (8 tests)
- ChatViewModelDeliveryStatusTests: Delivery status state machine (6 tests)
- ChatViewModelRefactoringTests: Command routing and message handling (4 tests)
- BLEServiceCoreTests: Packet deduplication and stale broadcast filtering (2 tests)
- PublicMessagePipelineTests: Message ordering and deduplication (4 tests)
- MessageRouterTests: Transport selection and outbox behavior (4 tests)
- PrivateChatManagerTests: Chat selection and read receipts (2 tests)
- UnifiedPeerServiceTests: Fingerprint resolution and blocking (2 tests)
- RelayControllerTests: TTL, handshake, and fragment relay logic (4 tests)
Modified files:
- MockTransport: Added peer snapshot publishing on connect/disconnect
- TestHelpers: Added waitUntil polling helper for async tests
- MockIdentityManager: Extended for new test scenarios
Total: 454 tests across 64 suites (was 440)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix flaky test by using waitUntil instead of fixed sleep
Replace fixed 200ms sleep with waitUntil helper for more reliable
async assertion in routing tests. This prevents timing issues on CI.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* Fix verification persistence on iOS when app backgrounds (#785)
Verification status was not being saved when the iOS app entered background
state, causing verified contacts to lose their verification status after the
app was closed. This happened because iOS can terminate backgrounded apps
without calling applicationWillTerminate.
Changes:
- Add saveIdentityState() method to force-save identity data without stopping services
- Call saveIdentityState() when iOS app enters background state
- Refactor applicationWillTerminate() to use new method
- Fix selector name typo (appWillTerminate -> applicationWillTerminate)
The verification data is now properly persisted to encrypted keychain storage
whenever the app backgrounds, ensuring verification status persists across
app launches.
Fixes#785
* Save identity state during verification events
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Harden background BLE restoration and notifications
* Guard BLE restoration paths to iOS
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Simplify validation, compression heuristics, and notification scheduling
* Consolidate notification logic and add InputValidator monitoring
Follow-up improvements to address PR feedback:
1. Consolidate notification functions
- Add interruptionLevel parameter to sendLocalNotification
- Refactor sendNetworkAvailableNotification to use consolidated function
- Removes 12 lines of duplicate code
2. Add monitoring to InputValidator
- Log control character rejections for production monitoring
- Privacy-preserving: logs length + count, not actual content
- Uses .security category for proper log routing
3. Add comprehensive InputValidator tests
- 28 test cases covering validation, control characters, unicode, edge cases
- Ensures behavioral changes are well-tested and documented
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Improve mesh media throughput
* Reserve media slots atomically
* Prioritize small fragment trains
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Implements mutually-exclusive image picker presentations to fix the error
"Currently, only presenting a single sheet is supported" when tapping
camera in a DM.
Solution:
- ContentView: Only presents image picker when NOT in a sheet
(when showSidebar=false and no private chat active)
- peopleSheetView: Only presents image picker when IN a sheet
(when showSidebar=true or private chat active)
This ensures only ONE presentation is active at any time, preventing
conflicts. Uses fullScreenCover on iOS to allow presentation over sheets.
Addresses feedback from @qalandarov in PR #834 with minimal approach.
Co-authored-by: jack <jackjackbits@users.noreply.github.com>