diff --git a/bitchat/Services/BLE/BLENoiseSessionQueues.swift b/bitchat/Services/BLE/BLENoiseSessionQueues.swift index 907f93bb..c54dd061 100644 --- a/bitchat/Services/BLE/BLENoiseSessionQueues.swift +++ b/bitchat/Services/BLE/BLENoiseSessionQueues.swift @@ -45,25 +45,32 @@ struct BLENoiseSessionQueues { privateMessagesByPeerID[peerID, default: []].insert(contentsOf: messages, at: 0) } - mutating func appendTypedPayload(_ payload: Data, transferId: String? = nil, for peerID: PeerID) { + @discardableResult + mutating func appendTypedPayload( + _ payload: Data, + transferId: String? = nil, + for peerID: PeerID + ) -> BLEPendingTypedPayload? { let entry = BLEPendingTypedPayload(payload: payload, transferId: transferId) var queue = typedPayloadsByPeerID[peerID] ?? [] // Deduplicate identical control payloads (e.g. repeated read/delivery // receipts queued before handshake completion). if transferId == nil, queue.contains(entry) { - return + return nil } queue.append(entry) + var evicted: BLEPendingTypedPayload? if queue.count > Self.maxTypedPayloadsPerPeer { // Prefer evicting the oldest non-media control payload over an // in-flight media transfer tracked by TransferProgressManager. if let controlIndex = queue.firstIndex(where: { $0.transferId == nil }) { - queue.remove(at: controlIndex) + evicted = queue.remove(at: controlIndex) } else { - queue.removeFirst() + evicted = queue.removeFirst() } } typedPayloadsByPeerID[peerID] = queue + return evicted } mutating func takeTypedPayloads(for peerID: PeerID) -> [BLEPendingTypedPayload] { diff --git a/bitchat/Services/BLE/BLEService+NoiseSession.swift b/bitchat/Services/BLE/BLEService+NoiseSession.swift index 6f73f2bf..cfab6c4e 100644 --- a/bitchat/Services/BLE/BLEService+NoiseSession.swift +++ b/bitchat/Services/BLE/BLEService+NoiseSession.swift @@ -464,7 +464,7 @@ extension BLEService { // may pass the full 64-hex noise key. let peerID = peerID.toShort() guard noiseService.hasEstablishedSession(with: peerID) else { - pendingNoiseSessionQueues.appendTypedPayload(typedPayload, for: peerID) + enqueuePendingTypedPayload(typedPayload, for: peerID) SecureLogger.debug("📥 Queued \(logLabel) for \(peerID.id.prefix(8))… pending handshake", category: .session) if !initiateOnlyIfReachable || (!noiseService.hasSession(with: peerID) && isPeerReachable(peerID)) { initiateNoiseHandshake(with: peerID) @@ -478,6 +478,32 @@ extension BLEService { } } + /// Queues a pre-handshake typed Noise payload on `messageQueue` and + /// notifies the UI if an older `.readReceipt` payload was evicted so it + /// remains eligible for retry once authentication finishes. + func enqueuePendingTypedPayload( + _ typedPayload: Data, + transferId: String? = nil, + for peerID: PeerID + ) { + guard let evicted = pendingNoiseSessionQueues.appendTypedPayload( + typedPayload, + transferId: transferId, + for: peerID + ) else { + return + } + guard let rawType = evicted.payload.first, + NoisePayloadType.decoded(rawValue: rawType) == .readReceipt, + let messageID = String(data: evicted.payload.dropFirst(), encoding: .utf8), + !messageID.isEmpty else { + return + } + notifyUI { [weak self] in + self?.deliverTransportEvent(.readReceiptEvicted(messageID: messageID)) + } + } + func makeEncryptedNoisePacket( _ typedPayload: Data, to peerID: PeerID, diff --git a/bitchat/Services/BLE/BLEService.swift b/bitchat/Services/BLE/BLEService.swift index 97356f54..b2e1fdba 100644 --- a/bitchat/Services/BLE/BLEService.swift +++ b/bitchat/Services/BLE/BLEService.swift @@ -1810,7 +1810,7 @@ final class BLEService: NSObject { } let queued = onEngine { self.privateMediaTransferAdmissions.withActive(transferId) { - self.pendingNoiseSessionQueues.appendTypedPayload( + self.enqueuePendingTypedPayload( typedPayload, transferId: transferId, for: targetID @@ -5510,7 +5510,7 @@ extension BLEService { // exact payload back until authenticated 0x21 state // arrives; that handler calls this drain again. onEngine { - pendingNoiseSessionQueues.appendTypedPayload( + enqueuePendingTypedPayload( pending.payload, transferId: pending.transferId, for: peerID diff --git a/bitchat/Services/Transport.swift b/bitchat/Services/Transport.swift index b60868a7..546c33f7 100644 --- a/bitchat/Services/Transport.swift +++ b/bitchat/Services/Transport.swift @@ -79,6 +79,10 @@ enum TransportEvent: @unchecked Sendable { case peerDisconnected(PeerID) case peerListUpdated([PeerID]) case messageDeliveryStatusUpdated(messageID: String, status: DeliveryStatus) + /// Emitted when a pre-handshake queued read receipt is evicted from a + /// bounded transport queue so the view model unmarks it for retry after + /// authentication completes. + case readReceiptEvicted(messageID: String) case bluetoothStateUpdated(CBManagerState) } diff --git a/bitchat/ViewModels/ChatLifecycleCoordinator.swift b/bitchat/ViewModels/ChatLifecycleCoordinator.swift index 59aa4ed8..d101b260 100644 --- a/bitchat/ViewModels/ChatLifecycleCoordinator.swift +++ b/bitchat/ViewModels/ChatLifecycleCoordinator.swift @@ -91,6 +91,12 @@ extension ChatViewModel: ChatLifecycleContext { } var canSendGeohashReadReceipt: Bool { + // Require network activation AND at least one connected DM relay so + // offline GeoDM reads stay unmarked instead of entering + // NostrRelayManager's bounded in-memory send queue (cap 200), where + // evicted or pre-termination receipts would be permanently lost. + // ChatViewModelBootstrapper re-scans the open chat when + // `$isDMRelayConnected` or `$activationAllowed` becomes true. networkActivationAllowed && NetworkActivationService.shared.activationAllowed && NostrRelayManager.shared.isDMRelayConnected diff --git a/bitchat/ViewModels/ChatVerificationCoordinator.swift b/bitchat/ViewModels/ChatVerificationCoordinator.swift index b5e97a1b..2dd6a5a6 100644 --- a/bitchat/ViewModels/ChatVerificationCoordinator.swift +++ b/bitchat/ViewModels/ChatVerificationCoordinator.swift @@ -61,6 +61,10 @@ protocol ChatVerificationContext: AnyObject { /// session and still pending an ack. Both ephemeral and stable aliases /// are supplied because either can own the outbox entry. func retrySecurePrivateMessagesAfterAuthentication(for peerIDAliases: [PeerID]) + /// Re-runs the read-receipt scan if the user is actively viewing one of + /// the newly authenticated peer's conversation aliases (recovering any + /// receipts evicted from the pre-handshake queue). + func retryPendingReadReceiptsIfViewing(peerIDAliases: [PeerID]) func sendVerifyChallenge(to peerID: PeerID, noiseKeyHex: String, nonceA: Data) func sendVerifyResponse(to peerID: PeerID, noiseKeyHex: String, nonceA: Data) @@ -127,6 +131,15 @@ extension ChatViewModel: ChatVerificationContext { messageRouter.retrySecurePrivateMessagesAfterAuthentication(for: peerIDAliases) } + func retryPendingReadReceiptsIfViewing(peerIDAliases: [PeerID]) { + guard isAppActive, let selectedPeer = selectedPrivateChatPeer else { return } + let selectedShort = selectedPeer.toShort() + guard peerIDAliases.contains(where: { $0 == selectedPeer || $0.toShort() == selectedShort }) else { + return + } + markPrivateMessagesAsRead(from: selectedPeer) + } + /// QR verification rides the mesh's Noise sessions only. private var verifyTransport: MeshVerifying? { meshService as? MeshVerifying } @@ -261,6 +274,7 @@ final class ChatVerificationCoordinator { peerIDAliases.append(stablePeerID) } self.context.retrySecurePrivateMessagesAfterAuthentication(for: peerIDAliases) + self.context.retryPendingReadReceiptsIfViewing(peerIDAliases: peerIDAliases) if var pending = self.pendingQRVerifications[peerID], pending.sent == false { self.context.sendVerifyChallenge( diff --git a/bitchat/ViewModels/ChatViewModel.swift b/bitchat/ViewModels/ChatViewModel.swift index 8b22a7ed..e2a3c0e6 100644 --- a/bitchat/ViewModels/ChatViewModel.swift +++ b/bitchat/ViewModels/ChatViewModel.swift @@ -2579,6 +2579,9 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel status: status ) + case .readReceiptEvicted(let messageID): + unmarkReadReceiptsSent([messageID]) + case .bluetoothStateUpdated(let state): updateBluetoothState(state) } diff --git a/bitchat/ViewModels/ChatViewModelBootstrapper.swift b/bitchat/ViewModels/ChatViewModelBootstrapper.swift index c850f647..0055af77 100644 --- a/bitchat/ViewModels/ChatViewModelBootstrapper.swift +++ b/bitchat/ViewModels/ChatViewModelBootstrapper.swift @@ -638,7 +638,32 @@ private extension ChatViewModelBootstrapper { NostrRelayManager.shared.$isDMRelayConnected .removeDuplicates() .receive(on: DispatchQueue.main) - .sink { _ in BridgeCourierService.shared.refresh() } + .sink { [weak viewModel] connected in + BridgeCourierService.shared.refresh() + guard connected, + let viewModel, + viewModel.isAppActive, + let peerID = viewModel.selectedPrivateChatPeer else { + return + } + viewModel.markPrivateMessagesAsRead(from: peerID) + } + .store(in: &viewModel.cancellables) + + // Retry deferred GeoDM/Nostr read receipts when network activation or + // general relay connectivity returns while a private chat is open. + NetworkActivationService.shared.$activationAllowed + .removeDuplicates() + .receive(on: DispatchQueue.main) + .sink { [weak viewModel] allowed in + guard allowed, + let viewModel, + viewModel.isAppActive, + let peerID = viewModel.selectedPrivateChatPeer else { + return + } + viewModel.markPrivateMessagesAsRead(from: peerID) + } .store(in: &viewModel.cancellables) // Toggle changes re-evaluate the watch set. BridgeService.shared.$isEnabled diff --git a/bitchatTests/ChatVerificationCoordinatorContextTests.swift b/bitchatTests/ChatVerificationCoordinatorContextTests.swift index 06bb5d8a..a38d180e 100644 --- a/bitchatTests/ChatVerificationCoordinatorContextTests.swift +++ b/bitchatTests/ChatVerificationCoordinatorContextTests.swift @@ -97,6 +97,7 @@ private final class MockChatVerificationContext: ChatVerificationContext { private(set) var triggeredHandshakes: [PeerID] = [] private(set) var privateMediaAuthenticatedPeers: [PeerID] = [] private(set) var securePrivateMessageRetryAliases: [[PeerID]] = [] + private(set) var readReceiptRetryAliases: [[PeerID]] = [] private(set) var sentChallenges: [(peerID: PeerID, noiseKeyHex: String, nonceA: Data)] = [] private(set) var sentResponses: [(peerID: PeerID, noiseKeyHex: String, nonceA: Data)] = [] @@ -121,6 +122,10 @@ private final class MockChatVerificationContext: ChatVerificationContext { securePrivateMessageRetryAliases.append(peerIDAliases) } + func retryPendingReadReceiptsIfViewing(peerIDAliases: [PeerID]) { + readReceiptRetryAliases.append(peerIDAliases) + } + func sendVerifyChallenge(to peerID: PeerID, noiseKeyHex: String, nonceA: Data) { sentChallenges.append((peerID, noiseKeyHex, nonceA)) } @@ -290,6 +295,7 @@ struct ChatVerificationCoordinatorContextTests { #expect(context.invalidatedEncryptionCachePeers.contains(peerID)) #expect(context.privateMediaAuthenticatedPeers == [peerID]) #expect(context.securePrivateMessageRetryAliases == [[peerID, stablePeerID]]) + #expect(context.readReceiptRetryAliases == [[peerID, stablePeerID]]) // Handshake required -> handshaking status. callbacks?.onHandshakeRequired(peerID) diff --git a/bitchatTests/ChatViewModelTests.swift b/bitchatTests/ChatViewModelTests.swift index 57420689..35df5285 100644 --- a/bitchatTests/ChatViewModelTests.swift +++ b/bitchatTests/ChatViewModelTests.swift @@ -1252,6 +1252,75 @@ struct ChatViewModelPrivateChatTests { #expect(transport.sentReadReceipts.isEmpty) #expect(defaults.object(forKey: "sentReadReceipts") == nil) } + + @Test @MainActor + func evictedReadReceipt_unmarksAndRetriesWhenPeerAuthenticatesWhileViewing() async { + let (viewModel, transport) = makeTestableViewModel() + let noiseKey = Data(repeating: 0xAA, count: 32) + let fullPeerID = PeerID(hexData: noiseKey) + let shortPeerID = fullPeerID.toShort() + let otherPeerID = PeerID(str: "bbbbbbbbbbbbbbbb") + + transport.connectedPeers.insert(shortPeerID) + transport.reachablePeers.insert(shortPeerID) + + viewModel.seedPrivateChat([ + BitchatMessage( + id: "evicted-rr-1", + sender: "Alice", + content: "hello", + timestamp: Date(), + isRelay: false, + isPrivate: true, + recipientNickname: viewModel.nickname, + senderPeerID: shortPeerID + ) + ], for: shortPeerID) + + viewModel.startPrivateChat(with: shortPeerID) + await Task.yield() + #expect(transport.sentReadReceipts.map(\.receipt.originalMessageID) == ["evicted-rr-1"]) + #expect(viewModel.hasSentReadReceipt("evicted-rr-1")) + + // Queue eviction unmarks the receipt so it becomes eligible for retry. + viewModel.didReceiveTransportEvent(.readReceiptEvicted(messageID: "evicted-rr-1")) + #expect(!viewModel.hasSentReadReceipt("evicted-rr-1")) + + // Unrelated peer authentication does not trigger retry. + viewModel.retryPendingReadReceiptsIfViewing(peerIDAliases: [otherPeerID]) + await Task.yield() + #expect(transport.sentReadReceipts.count == 1) + + // Backgrounded app does not emit retry receipts even for the open peer. + viewModel.setAppActive(false) + viewModel.retryPendingReadReceiptsIfViewing(peerIDAliases: [shortPeerID, fullPeerID]) + await Task.yield() + #expect(transport.sentReadReceipts.count == 1) + #expect(!viewModel.hasSentReadReceipt("evicted-rr-1")) + + // Foreground authentication matching via full-key alias retries and re-marks. + viewModel.setAppActive(true) + viewModel.retryPendingReadReceiptsIfViewing(peerIDAliases: [fullPeerID]) + await Task.yield() + #expect(transport.sentReadReceipts.map(\.receipt.originalMessageID) == ["evicted-rr-1", "evicted-rr-1"]) + #expect(viewModel.hasSentReadReceipt("evicted-rr-1")) + } + + @Test @MainActor + func canSendGeohashReadReceipt_requiresConnectedDMRelaySoOfflineReadsStayRetryable() { + let (viewModel, _) = makeTestableViewModel() + #expect(viewModel.networkActivationAllowed) + #expect(!NostrRelayManager.shared.isDMRelayConnected) + #expect(!viewModel.canSendGeohashReadReceipt) + + // Failed panic recovery also keeps GeoDM read receipts blocked. + let blockedKeychain = MockKeychain() + blockedKeychain.simulatedDeleteAllResult = false + let (blockedViewModel, _) = makeTestableViewModel(keychain: blockedKeychain) + _ = blockedViewModel.panicClearAllData() + #expect(!blockedViewModel.networkActivationAllowed) + #expect(!blockedViewModel.canSendGeohashReadReceipt) + } } // MARK: - Private Chat Selection Tests diff --git a/bitchatTests/Services/BLENoiseSessionQueuesTests.swift b/bitchatTests/Services/BLENoiseSessionQueuesTests.swift index e6a18d4e..3aa50800 100644 --- a/bitchatTests/Services/BLENoiseSessionQueuesTests.swift +++ b/bitchatTests/Services/BLENoiseSessionQueuesTests.swift @@ -91,23 +91,31 @@ struct BLENoiseSessionQueuesTests { var queues = BLENoiseSessionQueues() let readPayload = BLENoisePayloadFactory.readReceipt(originalMessageID: "dup-id") - // Identical control payloads deduplicate. - queues.appendTypedPayload(readPayload, for: peerID) - queues.appendTypedPayload(readPayload, for: peerID) + // Identical control payloads deduplicate and never evict. + #expect(queues.appendTypedPayload(readPayload, for: peerID) == nil) + #expect(queues.appendTypedPayload(readPayload, for: peerID) == nil) #expect(queues.takeTypedPayloads(for: peerID).count == 1) // Filling past maxTypedPayloadsPerPeer evicts oldest control payload - // first while keeping tracked media transfers intact. - queues.appendTypedPayload(Data([0x20, 0x01]), transferId: "keep-media", for: peerID) + // first while keeping tracked media transfers intact, and returns + // each evicted payload so callers can unmark dropped read receipts. + #expect(queues.appendTypedPayload(Data([0x20, 0x01]), transferId: "keep-media", for: peerID) == nil) + var evictedPayloads: [BLEPendingTypedPayload] = [] for index in 0..<(BLENoiseSessionQueues.maxTypedPayloadsPerPeer + 5) { - queues.appendTypedPayload( + if let evicted = queues.appendTypedPayload( BLENoisePayloadFactory.readReceipt(originalMessageID: "msg-\(index)"), for: peerID - ) + ) { + evictedPayloads.append(evicted) + } } let drained = queues.takeTypedPayloads(for: peerID) #expect(drained.count == BLENoiseSessionQueues.maxTypedPayloadsPerPeer) #expect(drained.contains(where: { $0.transferId == "keep-media" })) + #expect(evictedPayloads.count == 6) + #expect(evictedPayloads.map(\.payload) == (0..<6).map { + BLENoisePayloadFactory.readReceipt(originalMessageID: "msg-\($0)") + }) } }