From 13b599fad70c86329b728abd8a8f82fcb589fa45 Mon Sep 17 00:00:00 2001 From: jack <212554440+jackjackbits@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:08:48 -1000 Subject: [PATCH] perf(launch): share Keychain/NostrIdentityBridge, offload startup loads, debounce read receipts, and batch sightings (#1895) --- bitchat/App/AppRuntime.swift | 2 +- bitchat/Nostr/GeoRelayDirectory.swift | 78 +++++++++++++++++- bitchat/Nostr/NostrIdentityBridge.swift | 2 + bitchat/Services/Board/BoardManager.swift | 4 +- bitchat/Services/Board/BoardStore.swift | 80 ++++++++++++++----- bitchat/Services/GeohashPresenceService.swift | 2 +- bitchat/Services/LocationNotesManager.swift | 2 +- bitchat/Services/MeshSightingsTracker.swift | 75 +++++++++++++---- .../MessageDeduplicationService.swift | 13 ++- .../Services/NostrProcessedEventStore.swift | 13 +++ bitchat/Services/PrivateChatManager.swift | 7 +- .../ViewModels/ChatLiveVoiceCoordinator.swift | 22 ++++- .../ViewModels/ChatPeerListCoordinator.swift | 4 +- bitchat/ViewModels/ChatViewModel.swift | 51 ++++++++++-- .../ChatLiveVoiceCoordinatorTests.swift | 20 +++++ .../Services/MeshSightingsTrackerTests.swift | 22 +++++ 16 files changed, 335 insertions(+), 62 deletions(-) diff --git a/bitchat/App/AppRuntime.swift b/bitchat/App/AppRuntime.swift index 3b21c595..daa03861 100644 --- a/bitchat/App/AppRuntime.swift +++ b/bitchat/App/AppRuntime.swift @@ -61,7 +61,7 @@ final class AppRuntime: ObservableObject { init( keychain: KeychainManagerProtocol = KeychainManager.makeDefault(), - idBridge: NostrIdentityBridge = NostrIdentityBridge(), + idBridge: NostrIdentityBridge = .shared, sharedContentStore: SharedContentStore? = nil ) { self.idBridge = idBridge diff --git a/bitchat/Nostr/GeoRelayDirectory.swift b/bitchat/Nostr/GeoRelayDirectory.swift index 55f68b3d..29fbe3a3 100644 --- a/bitchat/Nostr/GeoRelayDirectory.swift +++ b/bitchat/Nostr/GeoRelayDirectory.swift @@ -150,6 +150,7 @@ final class GeoRelayDirectory { var observers: [NSObjectProtocol] = [] var refreshTimer: Timer? var retryTask: Task? + var localLoadTask: Task? init(notificationCenter: NotificationCenter) { self.notificationCenter = notificationCenter @@ -159,6 +160,7 @@ final class GeoRelayDirectory { observers.forEach { notificationCenter.removeObserver($0) } refreshTimer?.invalidate() retryTask?.cancel() + localLoadTask?.cancel() } } @@ -201,13 +203,14 @@ final class GeoRelayDirectory { private let dependencies: GeoRelayDirectoryDependencies private let cleanupState: CleanupState + private var didCompleteLocalLoad = false private var retryAttempt: Int = 0 private var isFetching: Bool = false private init() { self.dependencies = .live() self.cleanupState = CleanupState(notificationCenter: dependencies.notificationCenter) - entries = loadLocalEntries() + startAsyncLocalLoad() if dependencies.autoStart { registerObservers() startRefreshTimer() @@ -219,6 +222,7 @@ final class GeoRelayDirectory { self.dependencies = dependencies self.cleanupState = CleanupState(notificationCenter: dependencies.notificationCenter) entries = loadLocalEntries() + didCompleteLocalLoad = true if dependencies.autoStart { registerObservers() startRefreshTimer() @@ -226,8 +230,46 @@ final class GeoRelayDirectory { } } + private func startAsyncLocalLoad() { + let cacheURL = dependencies.cacheURL() + let bundleURLs = dependencies.bundledCSVURLs() + let cwd = dependencies.currentDirectoryPath() + let policy = dependencies.validationPolicy + + cleanupState.localLoadTask = Task { [weak self] in + let loaded = await Task.detached(priority: .userInitiated) { + Self.loadLocalEntriesOffMain( + cacheURL: cacheURL, + bundleURLs: bundleURLs, + currentDirectoryPath: cwd, + policy: policy + ) + }.value + guard !Task.isCancelled, let self else { return } + self.cleanupState.localLoadTask = nil + self.didCompleteLocalLoad = true + if self.entries.isEmpty && !loaded.isEmpty { + self.entries = loaded + self.dependencies.notificationCenter.post(name: .geoRelayDirectoryDidRefresh, object: nil) + } + } + } + + private func ensureLocalEntriesLoaded() { + guard !didCompleteLocalLoad else { return } + cleanupState.localLoadTask?.cancel() + cleanupState.localLoadTask = nil + didCompleteLocalLoad = true + if entries.isEmpty { + entries = loadLocalEntries() + } + } + /// Returns up to `count` relay URLs (wss://) closest to the geohash center. func closestRelays(toGeohash geohash: String, count: Int = 5) -> [String] { + if entries.isEmpty && !didCompleteLocalLoad { + ensureLocalEntriesLoaded() + } guard !entries.isEmpty, count > 0 else { return [] } let key = ClosestRelaysCacheKey(geohash: geohash, count: count) if let cached = closestRelaysCache[key] { @@ -246,6 +288,9 @@ final class GeoRelayDirectory { /// Ties break by host so every device with the same directory picks the /// same relay set — publishers and subscribers must agree on relays. func closestRelays(toLat lat: Double, lon: Double, count: Int = 5) -> [String] { + if entries.isEmpty && !didCompleteLocalLoad { + ensureLocalEntriesLoaded() + } guard !entries.isEmpty, count > 0 else { return [] } let rad = Double.pi / 180.0 @@ -470,6 +515,35 @@ final class GeoRelayDirectory { return [] } + nonisolated private static func loadLocalEntriesOffMain( + cacheURL: URL?, + bundleURLs: [URL], + currentDirectoryPath: String?, + policy: GeoRelayDirectoryValidationPolicy + ) -> [Entry] { + if let cacheURL, + let data = try? Data(contentsOf: cacheURL), + let entries = validatedEntries(from: data, policy: policy, minimumEntries: 1) { + return entries + } + + for url in bundleURLs { + if let data = try? Data(contentsOf: url), + let entries = validatedEntries(from: data, policy: policy, minimumEntries: 1) { + return entries + } + } + + if let cwd = currentDirectoryPath, + let data = try? Data(contentsOf: URL(fileURLWithPath: cwd).appendingPathComponent("relays/online_relays_gps.csv")), + let entries = validatedEntries(from: data, policy: policy, minimumEntries: 1) { + return entries + } + + SecureLogger.warning("GeoRelayDirectory: no local CSV found; entries empty", category: .session) + return [] + } + /// Parses the fixed three-column format as an all-or-nothing trust unit. /// One malformed or conflicting row rejects the complete dataset rather /// than silently shrinking or partially replacing the current directory. @@ -678,6 +752,8 @@ final class GeoRelayDirectory { /// from Application Support. func resetForPanic() { cancelRetry() + cleanupState.localLoadTask?.cancel() + cleanupState.localLoadTask = nil retryAttempt = 0 closestRelaysCache.removeAll(keepingCapacity: false) dependencies.userDefaults.removeObject(forKey: lastFetchKey) diff --git a/bitchat/Nostr/NostrIdentityBridge.swift b/bitchat/Nostr/NostrIdentityBridge.swift index 066289fb..ba528570 100644 --- a/bitchat/Nostr/NostrIdentityBridge.swift +++ b/bitchat/Nostr/NostrIdentityBridge.swift @@ -4,6 +4,8 @@ import CryptoKit /// Bridge between Noise and Nostr identities final class NostrIdentityBridge { + static let shared = NostrIdentityBridge() + private let keychainService = "chat.bitchat.nostr" private let currentIdentityKey = "nostr-current-identity" private let deviceSeedKey = "nostr-device-seed" diff --git a/bitchat/Services/Board/BoardManager.swift b/bitchat/Services/Board/BoardManager.swift index 82f78a8f..26d79abd 100644 --- a/bitchat/Services/Board/BoardManager.swift +++ b/bitchat/Services/Board/BoardManager.swift @@ -167,7 +167,7 @@ final class BoardManager: ObservableObject { return nil } do { - let identity = try NostrIdentityBridge().deriveIdentity(forGeohash: geohash) + let identity = try NostrIdentityBridge.shared.deriveIdentity(forGeohash: geohash) let event = try NostrProtocol.createGeohashTextNote( content: content, geohash: geohash, @@ -188,7 +188,7 @@ final class BoardManager: ObservableObject { let relays = GeoRelayDirectory.shared.closestRelays(toGeohash: geohash, count: TransportConfig.nostrGeoRelayCount) guard !relays.isEmpty else { return } do { - let identity = try NostrIdentityBridge().deriveIdentity(forGeohash: geohash) + let identity = try NostrIdentityBridge.shared.deriveIdentity(forGeohash: geohash) let deletion = try NostrProtocol.createDeleteEvent(ofEventID: eventID, senderIdentity: identity) NostrRelayManager.shared.sendEvent(deletion, to: relays) } catch { diff --git a/bitchat/Services/Board/BoardStore.swift b/bitchat/Services/Board/BoardStore.swift index db6a9605..603dec30 100644 --- a/bitchat/Services/Board/BoardStore.swift +++ b/bitchat/Services/Board/BoardStore.swift @@ -99,7 +99,15 @@ final class BoardStore { init(persistsToDisk: Bool = true, fileURL: URL? = nil, now: @escaping () -> Date = Date.init) { self.now = now self.fileURL = persistsToDisk ? (fileURL ?? Self.defaultFileURL()) : nil - loadFromDisk() + if self.fileURL != nil { + // Restore off the calling thread (cold launch on MainActor) on the + // serial store queue. Every read/write (`posts`, `syncCandidates`, + // `ingest`, `wipe`) serializes on `queue`, so callers are linearly + // ordered after restore without blocking init(). + queue.async { [self] in + loadFromDiskLocked() + } + } } // MARK: - Ingest @@ -168,18 +176,38 @@ final class BoardStore { packet: BitchatPacket, rawPacket: Data, nowMs: UInt64, - retainUntilOverride: UInt64? = nil + retainUntilOverride: UInt64? = nil, + publishSnapshot: Bool = true ) -> BoardIngestResult { - pruneExpiredLocked(nowMs: nowMs) + pruneExpiredLocked(nowMs: nowMs, publishSnapshot: publishSnapshot) switch wire { case .post(let post): - return ingestPostLocked(post, packet: packet, rawPacket: rawPacket, nowMs: nowMs) + return ingestPostLocked( + post, + packet: packet, + rawPacket: rawPacket, + nowMs: nowMs, + publishSnapshot: publishSnapshot + ) case .tombstone(let tombstone): - return ingestTombstoneLocked(tombstone, packet: packet, rawPacket: rawPacket, nowMs: nowMs, retainUntilOverride: retainUntilOverride) + return ingestTombstoneLocked( + tombstone, + packet: packet, + rawPacket: rawPacket, + nowMs: nowMs, + retainUntilOverride: retainUntilOverride, + publishSnapshot: publishSnapshot + ) } } - private func ingestPostLocked(_ post: BoardPostPacket, packet: BitchatPacket, rawPacket: Data, nowMs: UInt64) -> BoardIngestResult { + private func ingestPostLocked( + _ post: BoardPostPacket, + packet: BitchatPacket, + rawPacket: Data, + nowMs: UInt64, + publishSnapshot: Bool = true + ) -> BoardIngestResult { guard post.expiresAt > nowMs else { return .rejected } // Receive-time sanity (this is the single chokepoint for radio, sync, // and disk restores): the decoder only enforces the createdAt to @@ -204,7 +232,9 @@ final class BoardStore { if posts.count > Limits.maxPosts { evictOldestLocked(from: posts, keep: Limits.maxPosts) } - publishSnapshotLocked() + if publishSnapshot { + publishSnapshotLocked() + } // Even when the new post itself was the eviction victim it stays // valid mesh-wide; peers with room should still receive it. return .accepted @@ -215,7 +245,8 @@ final class BoardStore { packet: BitchatPacket, rawPacket: Data, nowMs: UInt64, - retainUntilOverride: UInt64? = nil + retainUntilOverride: UInt64? = nil, + publishSnapshot: Bool = true ) -> BoardIngestResult { guard !tombstones.contains(where: { $0.tombstone.postID == tombstone.postID }) else { return .duplicate } @@ -238,7 +269,9 @@ final class BoardStore { retainUntil = target.expiresAt isOrphan = false posts.remove(at: index) - publishSnapshotLocked() + if publishSnapshot { + publishSnapshotLocked() + } } else if let retainUntilOverride { // Restored from disk: the post is long gone, so trust the // retention deadline recorded when the delete was first applied. @@ -289,11 +322,11 @@ final class BoardStore { posts.removeAll { victimIDs.contains($0.post.postID) } } - private func pruneExpiredLocked(nowMs: UInt64) { + private func pruneExpiredLocked(nowMs: UInt64, publishSnapshot: Bool = true) { let postsBefore = posts.count posts.removeAll { $0.post.expiresAt <= nowMs } tombstones.removeAll { $0.retainUntil <= nowMs } - if posts.count != postsBefore { + if publishSnapshot && posts.count != postsBefore { publishSnapshotLocked() } } @@ -335,23 +368,28 @@ final class BoardStore { } } - private func loadFromDisk() { + private func loadFromDiskLocked() { guard let fileURL, let data = try? Data(contentsOf: fileURL), let payloads = try? JSONDecoder().decode([PersistedEntry].self, from: data) else { return } let nowMs = currentMs() - queue.sync { - for entry in payloads { - guard let packet = BitchatPacket.from(entry.packet), - packet.type == MessageType.boardPost.rawValue, - let wire = BoardWire.decode(from: packet.payload), - wire.verifySignature() else { continue } - _ = ingestLocked(wire, packet: packet, rawPacket: entry.packet, nowMs: nowMs, retainUntilOverride: entry.retainUntil) - } - publishSnapshotLocked() + for entry in payloads { + guard let packet = BitchatPacket.from(entry.packet), + packet.type == MessageType.boardPost.rawValue, + let wire = BoardWire.decode(from: packet.payload), + wire.verifySignature() else { continue } + _ = ingestLocked( + wire, + packet: packet, + rawPacket: entry.packet, + nowMs: nowMs, + retainUntilOverride: entry.retainUntil, + publishSnapshot: false + ) } + publishSnapshotLocked() } private static func defaultFileURL() -> URL? { diff --git a/bitchat/Services/GeohashPresenceService.swift b/bitchat/Services/GeohashPresenceService.swift index 73a335f4..c329f581 100644 --- a/bitchat/Services/GeohashPresenceService.swift +++ b/bitchat/Services/GeohashPresenceService.swift @@ -78,7 +78,7 @@ final class GeohashPresenceService: ObservableObject { ] private init() { - let idBridge = NostrIdentityBridge() + let idBridge = NostrIdentityBridge.shared self.availableChannelsProvider = { LocationStateManager.shared.availableChannels } self.locationChanges = LocationStateManager.shared.$availableChannels.eraseToAnyPublisher() self.torReadyPublisher = NotificationCenter.default.publisher(for: .TorDidBecomeReady) diff --git a/bitchat/Services/LocationNotesManager.swift b/bitchat/Services/LocationNotesManager.swift index 3213af37..7d84b466 100644 --- a/bitchat/Services/LocationNotesManager.swift +++ b/bitchat/Services/LocationNotesManager.swift @@ -22,7 +22,7 @@ struct LocationNotesDependencies { /// fires without data. Defaults to true so tests keep legacy behavior. var anyRelayConnected: @MainActor (_ relayUrls: [String]) -> Bool = { _ in true } - private static let idBridge = NostrIdentityBridge() + private static let idBridge = NostrIdentityBridge.shared /// Panic-wipe hook: drop cached per-geohash secp256k1 keys held by the /// live dependencies bridge so post-panic notes/drops cannot sign with diff --git a/bitchat/Services/MeshSightingsTracker.swift b/bitchat/Services/MeshSightingsTracker.swift index 12bd7255..985526e1 100644 --- a/bitchat/Services/MeshSightingsTracker.swift +++ b/bitchat/Services/MeshSightingsTracker.swift @@ -33,6 +33,9 @@ final class MeshSightingsTracker: ObservableObject { private let defaults: UserDefaults private let now: () -> Date private var seenHashes: Set = [] + private var seenPeerIDsToday: Set = [] + private var currentDayKey: String = "" + private var currentSalt: Data = Data() init(defaults: UserDefaults = .standard, now: @escaping () -> Date = { Date() }) { self.defaults = defaults @@ -41,14 +44,32 @@ final class MeshSightingsTracker: ObservableObject { } func recordSighting(peerID: PeerID) { - rollOverIfNeeded() - let hash = saltedHash(peerID.id) + recordSightings([peerID]) + } + + func recordSightings(_ peerIDs: [PeerID]) { + guard !peerIDs.isEmpty else { return } let seenAt = now() - lastSightingAt = seenAt - defaults.set(seenAt, forKey: Keys.lastSeenAt) - guard seenHashes.insert(hash).inserted else { return } - todayCount = seenHashes.count - defaults.set(Array(seenHashes), forKey: Keys.hashes) + rollOverIfNeeded(at: seenAt) + + var insertedAnyHash = false + for peerID in peerIDs { + let rawID = peerID.id + guard seenPeerIDsToday.insert(rawID).inserted else { continue } + let hash = saltedHash(rawID) + if seenHashes.insert(hash).inserted { + insertedAnyHash = true + } + } + + if lastSightingAt != seenAt { + lastSightingAt = seenAt + defaults.set(seenAt, forKey: Keys.lastSeenAt) + } + if insertedAnyHash { + todayCount = seenHashes.count + defaults.set(Array(seenHashes), forKey: Keys.hashes) + } } /// Re-evaluates the day boundary for the UI. `recordSighting` handles @@ -56,11 +77,14 @@ final class MeshSightingsTracker: ObservableObject { /// would otherwise keep showing yesterday's tally until the next sighting; /// the empty-state view calls this on its periodic refresh tick. func refreshForDisplay() { - rollOverIfNeeded() + rollOverIfNeeded(at: now()) } func clear() { seenHashes.removeAll() + seenPeerIDsToday.removeAll() + currentDayKey = "" + currentSalt = Data() todayCount = 0 lastSightingAt = nil defaults.removeObject(forKey: Keys.dayKey) @@ -70,7 +94,7 @@ final class MeshSightingsTracker: ObservableObject { } private func restore() { - rollOverIfNeeded() + rollOverIfNeeded(at: now()) seenHashes = Set(defaults.stringArray(forKey: Keys.hashes) ?? []) todayCount = seenHashes.count lastSightingAt = defaults.object(forKey: Keys.lastSeenAt) as? Date @@ -78,26 +102,43 @@ final class MeshSightingsTracker: ObservableObject { /// Resets the tally when the local calendar day changes; the salt rotates /// with it so hashes from different days can never be correlated. - private func rollOverIfNeeded() { - let today = Self.dayKey(for: now()) - guard defaults.string(forKey: Keys.dayKey) != today else { return } + private func rollOverIfNeeded(at date: Date) { + let today = Self.dayKey(for: date) + if currentDayKey == today && !currentSalt.isEmpty { + return + } + if defaults.string(forKey: Keys.dayKey) == today { + currentDayKey = today + if let persistedSalt = defaults.data(forKey: Keys.salt), !persistedSalt.isEmpty { + currentSalt = persistedSalt + } else { + let fresh = Self.randomSalt() + currentSalt = fresh + defaults.set(fresh, forKey: Keys.salt) + } + return + } + let freshSalt = Self.randomSalt() + currentDayKey = today + currentSalt = freshSalt defaults.set(today, forKey: Keys.dayKey) - defaults.set(Self.randomSalt(), forKey: Keys.salt) + defaults.set(freshSalt, forKey: Keys.salt) defaults.removeObject(forKey: Keys.hashes) defaults.removeObject(forKey: Keys.lastSeenAt) seenHashes.removeAll() + seenPeerIDsToday.removeAll() todayCount = 0 lastSightingAt = nil } private func saltedHash(_ value: String) -> String { - let salt = defaults.data(forKey: Keys.salt) ?? { + if currentSalt.isEmpty { let fresh = Self.randomSalt() + currentSalt = fresh defaults.set(fresh, forKey: Keys.salt) - return fresh - }() + } var digest = SHA256() - digest.update(data: salt) + digest.update(data: currentSalt) digest.update(data: Data(value.utf8)) return digest.finalize().map { String(format: "%02x", $0) }.joined() } diff --git a/bitchat/Services/MessageDeduplicationService.swift b/bitchat/Services/MessageDeduplicationService.swift index 8575c710..35fb8849 100644 --- a/bitchat/Services/MessageDeduplicationService.swift +++ b/bitchat/Services/MessageDeduplicationService.swift @@ -223,6 +223,7 @@ final class MessageDeduplicationService { private var persistScheduled = false private var persistTask: Task? private var pendingPersistIDs: [String] = [] + private var clearAllGeneration: UInt64 = 0 /// Creates a new deduplication service with specified capacities. /// - Parameters: @@ -241,8 +242,15 @@ final class MessageDeduplicationService { self.nostrEventStore = nostrEventStore self.nostrEventCapacity = nostrEventCapacity if let nostrEventStore { - for eventID in nostrEventStore.load() { - nostrEventCache.record(eventID, value: true) + let generation = clearAllGeneration + nostrEventStore.loadAsync { [weak self] eventIDs in + guard !eventIDs.isEmpty else { return } + Task { @MainActor [weak self] in + guard let self, self.clearAllGeneration == generation else { return } + for eventID in eventIDs where !self.nostrEventCache.contains(eventID) { + self.nostrEventCache.record(eventID, value: true) + } + } } } } @@ -363,6 +371,7 @@ final class MessageDeduplicationService { /// Clears all caches. This is the wipe/panic path: the persisted /// private-envelope record goes with everything else. func clearAll() { + clearAllGeneration &+= 1 persistTask?.cancel() persistTask = nil persistScheduled = false diff --git a/bitchat/Services/NostrProcessedEventStore.swift b/bitchat/Services/NostrProcessedEventStore.swift index 760f887c..0f9c77b9 100644 --- a/bitchat/Services/NostrProcessedEventStore.swift +++ b/bitchat/Services/NostrProcessedEventStore.swift @@ -57,6 +57,19 @@ final class NostrProcessedEventStore { } } + /// Loads processed event IDs asynchronously on the utility I/O queue so + /// cold launch does not block the main actor on disk I/O + JSON decoding. + func loadAsync(completion: @escaping @Sendable ([String]) -> Void) { + ioQueue.async { [self] in + switch loadLocked() { + case .loaded(let ids): + completion(ids) + case .transientError: + completion([]) + } + } + } + /// Merge new IDs onto the persisted record, oldest-first, trimming from /// the front past `cap`. Append-merge (not snapshot-overwrite) so the /// in-memory cache being cleared transiently (channel switches) can diff --git a/bitchat/Services/PrivateChatManager.swift b/bitchat/Services/PrivateChatManager.swift index 9b7e3e33..0d56c13d 100644 --- a/bitchat/Services/PrivateChatManager.swift +++ b/bitchat/Services/PrivateChatManager.swift @@ -151,17 +151,20 @@ final class PrivateChatManager: ObservableObject { @MainActor func syncReadReceiptsForSentMessages(peerID: PeerID, externalReceipts: inout Set) { guard let myPeerID = meshService?.myPeerID else { return } + var syncedIDs: [String] = [] for message in messages(for: peerID) { if message.isOwn(myPeerID: myPeerID, myGeoChatPeerID: nil) { switch message.deliveryStatus { case .read, .delivered: - externalReceipts.insert(message.id) - sentReadReceipts.insert(message.id) + syncedIDs.append(message.id) case .notSentYet, .failed, .partiallyDelivered, .sending, .sent, .carried: break } } } + guard !syncedIDs.isEmpty else { return } + externalReceipts.formUnion(syncedIDs) + sentReadReceipts.formUnion(syncedIDs) } /// Start a private chat with a peer. Selection is mutated through the diff --git a/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift b/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift index 78fa83e1..723b47d5 100644 --- a/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift +++ b/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift @@ -158,7 +158,13 @@ final class ChatLiveVoiceCoordinator { /// `sweepsOnInit` exists for tests whose coordinator shares the real /// application-support directory: they pass `false` so parallel test /// runs never sweep each other's in-flight capture files. - init(context: any ChatLiveVoiceContext, fileStore: BLEIncomingFileStore = BLEIncomingFileStore(), sweepsOnInit: Bool = true) { + /// `asyncStartupSweep` moves the disk sweep off the main actor for cold launch. + init( + context: any ChatLiveVoiceContext, + fileStore: BLEIncomingFileStore = BLEIncomingFileStore(), + sweepsOnInit: Bool = true, + asyncStartupSweep: Bool = false + ) { self.context = context self.fileStore = fileStore // Orphaned partial captures from a previous session (live-only bursts @@ -166,7 +172,14 @@ final class ChatLiveVoiceCoordinator { // never reclaim (eviction skips voice_live_* by design) — sweep them // on startup. if sweepsOnInit { - sweepStaleLiveCaptures() + if asyncStartupSweep { + let store = fileStore + Task.detached(priority: .utility) { + Self.sweepStaleLiveCaptures(in: store) + } + } else { + Self.sweepStaleLiveCaptures(in: fileStore) + } } } @@ -679,7 +692,7 @@ final class ChatLiveVoiceCoordinator { return Data(hexString: hex) } - private static let incomingSubdirectory = "\(MimeType.Category.audio.mediaDir)/incoming" + nonisolated private static let incomingSubdirectory = "\(MimeType.Category.audio.mediaDir)/incoming" /// The peer ID and scope in the name mirror the assembly key: colliding /// burst IDs from different senders — or from the same sender across DM @@ -700,7 +713,8 @@ final class ChatLiveVoiceCoordinator { /// only (ConversationStore never persists; the gossip archive replays /// `MessageType.message` packets only), so no row from a previous /// process can reference the file. - private func sweepStaleLiveCaptures() { + nonisolated private static func sweepStaleLiveCaptures(in fileStore: BLEIncomingFileStore) { + let fileManager = fileStore.fileManager guard let directory = try? fileStore.incomingDirectory(subdirectory: Self.incomingSubdirectory), let contents = try? fileManager.contentsOfDirectory( at: directory, diff --git a/bitchat/ViewModels/ChatPeerListCoordinator.swift b/bitchat/ViewModels/ChatPeerListCoordinator.swift index bc0689cb..73c8bb9e 100644 --- a/bitchat/ViewModels/ChatPeerListCoordinator.swift +++ b/bitchat/ViewModels/ChatPeerListCoordinator.swift @@ -65,9 +65,7 @@ extension ChatViewModel: ChatPeerListContext { } func recordMeshSightings(peerIDs: [PeerID]) { - for peerID in peerIDs { - MeshSightingsTracker.shared.recordSighting(peerID: peerID) - } + MeshSightingsTracker.shared.recordSightings(peerIDs) } } diff --git a/bitchat/ViewModels/ChatViewModel.swift b/bitchat/ViewModels/ChatViewModel.swift index 638d5f60..d3832b36 100644 --- a/bitchat/ViewModels/ChatViewModel.swift +++ b/bitchat/ViewModels/ChatViewModel.swift @@ -214,7 +214,8 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage lazy var mediaTransferCoordinator = ChatMediaTransferCoordinator(context: self) lazy var liveVoiceCoordinator = ChatLiveVoiceCoordinator( context: self, - sweepsOnInit: !TestEnvironment.isRunningTests + sweepsOnInit: !TestEnvironment.isRunningTests, + asyncStartupSweep: true ) lazy var verificationCoordinator = ChatVerificationCoordinator(context: self) lazy var groupCoordinator = ChatGroupCoordinator(context: self) @@ -476,19 +477,52 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage return scratch } - // Track sent read receipts to avoid duplicates (persisted across launches) - // Note: Persistence happens automatically in didSet, no lifecycle observers needed + // Track sent read receipts to avoid duplicates (persisted across launches). + // Mutations coalesce into a debounced off-main encode/write so rapid bursts + // (opening a chat, reconnecting) do not re-encode the whole set on MainActor. + private var readReceiptPersistTask: Task? + private var readReceiptPersistGeneration: UInt64 = 0 + var sentReadReceipts: Set = [] { // messageID set didSet { - // Only persist if there are changes guard oldValue != sentReadReceipts else { return } + schedulePersistSentReadReceipts() + } + } - // Persist whenever it changes (no manual synchronize/verify re-read) - if let data = try? JSONEncoder().encode(Array(sentReadReceipts)) { - readReceiptsDefaults.set(data, forKey: "sentReadReceipts") + private func schedulePersistSentReadReceipts() { + readReceiptPersistTask?.cancel() + readReceiptPersistGeneration &+= 1 + let generation = readReceiptPersistGeneration + let snapshot = Array(sentReadReceipts) + let defaults = readReceiptsDefaults + readReceiptPersistTask = Task.detached(priority: .utility) { [weak self] in + try? await Task.sleep(nanoseconds: 250_000_000) + guard !Task.isCancelled else { return } + if let data = try? JSONEncoder().encode(snapshot) { + defaults.set(data, forKey: "sentReadReceipts") } else { SecureLogger.error("❌ Failed to encode read receipts for persistence", category: .session) } + await MainActor.run { [weak self] in + guard let self, self.readReceiptPersistGeneration == generation else { return } + self.readReceiptPersistTask = nil + } + } + } + + /// Cancels any pending debounced write and persists `sentReadReceipts` + /// synchronously (used on termination and panic wipe). + func flushPersistedReadReceiptsSynchronously() { + readReceiptPersistTask?.cancel() + readReceiptPersistTask = nil + readReceiptPersistGeneration &+= 1 + if sentReadReceipts.isEmpty { + readReceiptsDefaults.removeObject(forKey: "sentReadReceipts") + } else if let data = try? JSONEncoder().encode(Array(sentReadReceipts)) { + readReceiptsDefaults.set(data, forKey: "sentReadReceipts") + } else { + SecureLogger.error("❌ Failed to encode read receipts for persistence", category: .session) } } @@ -1550,10 +1584,12 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage /// Save identity state without stopping services (for backgrounding) func saveIdentityState() { + flushPersistedReadReceiptsSynchronously() lifecycleCoordinator.saveIdentityState() } @objc func applicationWillTerminate() { + flushPersistedReadReceiptsSynchronously() lifecycleCoordinator.applicationWillTerminate() } @@ -1719,6 +1755,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage // Clear read receipt tracking sentReadReceipts.removeAll() + flushPersistedReadReceiptsSynchronously() privateChatManager.resetForPanic() deduplicationService.clearAll() diff --git a/bitchatTests/ChatLiveVoiceCoordinatorTests.swift b/bitchatTests/ChatLiveVoiceCoordinatorTests.swift index 2e5ca317..5931370a 100644 --- a/bitchatTests/ChatLiveVoiceCoordinatorTests.swift +++ b/bitchatTests/ChatLiveVoiceCoordinatorTests.swift @@ -610,6 +610,26 @@ struct ChatLiveVoiceCoordinatorTests { #expect(FileManager.default.fileExists(atPath: promoted.path)) } + @Test func asyncStartupSweepRemovesStaleLiveCapturesOffMain() async throws { + let (store, incoming, cleanup) = try makeTempStore() + defer { cleanup() } + + let stale = incoming.appendingPathComponent("voice_live_00cc00cc00cc00cc_ddddeeeeffff0002_dm.aac") + let finalized = incoming.appendingPathComponent("voice_00112233445566ff.m4a") + try Data([0x01]).write(to: stale) + try Data([0x02]).write(to: finalized) + + let context = MockChatLiveVoiceContext() + _ = ChatLiveVoiceCoordinator(context: context, fileStore: store, sweepsOnInit: true, asyncStartupSweep: true) + + let swept = await TestHelpers.waitUntil( + { !FileManager.default.fileExists(atPath: stale.path) }, + timeout: TestConstants.settleTimeout + ) + #expect(swept) + #expect(FileManager.default.fileExists(atPath: finalized.path)) + } + @Test func finalizedFallbackSurvivesNextStartupSweep() throws { let (store, incoming, cleanup) = try makeTempStore() defer { cleanup() } diff --git a/bitchatTests/Services/MeshSightingsTrackerTests.swift b/bitchatTests/Services/MeshSightingsTrackerTests.swift index e6795e7b..d65605cb 100644 --- a/bitchatTests/Services/MeshSightingsTrackerTests.swift +++ b/bitchatTests/Services/MeshSightingsTrackerTests.swift @@ -78,4 +78,26 @@ struct MeshSightingsTrackerTests { let reloaded = MeshSightingsTracker(defaults: defaults, now: { self.noon }) #expect(reloaded.todayCount == 0) } + + @Test + func recordsBatchedSightingsOnceAndDeduplicatesAcrossRepeatCalls() { + let defaults = makeDefaults() + let tracker = MeshSightingsTracker(defaults: defaults, now: { self.noon }) + + let peerA = PeerID(str: "aaaa111122223333") + let peerB = PeerID(str: "bbbb444455556666") + let peerC = PeerID(str: "cccc777788889999") + + tracker.recordSightings([peerA, peerB, peerA]) + #expect(tracker.todayCount == 2) + #expect(tracker.lastSightingAt == noon) + + tracker.recordSightings([peerA, peerB, peerC]) + #expect(tracker.todayCount == 3) + + let reloaded = MeshSightingsTracker(defaults: defaults, now: { self.noon.addingTimeInterval(30) }) + #expect(reloaded.todayCount == 3) + reloaded.recordSightings([peerA, peerB, peerC]) + #expect(reloaded.todayCount == 3) + } }