Fix read-receipt eviction retry, GeoDM reconnect retry, and dead code (#1948)

* Fix read-receipt eviction retry, GeoDM offline queuing, and dead code

* Keep offline GeoDM read receipts retryable until DM relay connects

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
This commit is contained in:
jackandjack authored and GitHub committed 2026-11-28 12:24:47 -10:00
1 parent a00cc51be2
commit cfbb7e0205
11 files changed
+183 -15

No files matched your search

@@ -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] {
@@ -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,
+2 -2
View File
@@ -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
+4
View File
@@ -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)
}
@@ -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
@@ -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(
+3
View File
@@ -2579,6 +2579,9 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
status: status
)
case .readReceiptEvicted(let messageID):
unmarkReadReceiptsSent([messageID])
case .bluetoothStateUpdated(let state):
updateBluetoothState(state)
}
@@ -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
@@ -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)
+69
View File
@@ -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
@@ -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)")
})
}
}