Harden read receipts: single owner, privacy controls, and encrypted persistence (#1945)

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
This commit is contained in:
jackandjack authored and GitHub committed 2026-11-28 11:26:34 -10:00
1 parent 504541ae4c
commit 15ea762abc
33 files changed
+1289 -468

No files matched your search

+372
View File
@@ -15892,6 +15892,378 @@
}
}
},
"app_info.settings.read_receipts.subtitle" : {
"comment" : "Subtitle explaining the read receipts toggle",
"extractionState" : "manual",
"localizations" : {
"ar" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"bn" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"de" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"es" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"fa" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"fil" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"fr" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"he" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"hi" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"id" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"it" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"ja" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"ko" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"ms" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"ne" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"nl" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"pl" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"pt" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"pt-BR" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"ru" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"sv" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"ta" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"th" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"tr" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"uk" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"ur" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"vi" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Lets people know when you’ve viewed their private messages. Automatically off in Stealth Mode."
}
}
}
},
"app_info.settings.read_receipts.title" : {
"comment" : "Title of the setting that controls whether private message read receipts are sent",
"extractionState" : "manual",
"localizations" : {
"ar" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"bn" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"de" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Send Read Receipts"
}
},
"es" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"fa" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"fil" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"fr" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"he" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"hi" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"id" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"it" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"ja" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"ko" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"ms" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"ne" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"nl" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"pl" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"pt" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"pt-BR" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"ru" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"sv" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"ta" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"th" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"tr" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"uk" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"ur" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"vi" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "needs_review",
"value" : "Send Read Receipts"
}
}
}
},
"app_info.settings.relays.add" : {
"comment" : "Button that adds the typed relay address to the list",
"extractionState" : "manual",
@@ -14,6 +14,10 @@ struct BLEPendingTypedPayload: Equatable {
}
struct BLENoiseSessionQueues {
/// Bounds queued pre-handshake control/media payloads per peer so a peer
/// that never finishes a handshake cannot grow RAM without bound.
static let maxTypedPayloadsPerPeer = 128
private var privateMessagesByPeerID: [PeerID: [BLEPendingPrivateMessage]] = [:]
private var typedPayloadsByPeerID: [PeerID: [BLEPendingTypedPayload]] = [:]
@@ -42,9 +46,24 @@ struct BLENoiseSessionQueues {
}
mutating func appendTypedPayload(_ payload: Data, transferId: String? = nil, for peerID: PeerID) {
typedPayloadsByPeerID[peerID, default: []].append(
BLEPendingTypedPayload(payload: payload, transferId: transferId)
)
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
}
queue.append(entry)
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)
} else {
queue.removeFirst()
}
}
typedPayloadsByPeerID[peerID] = queue
}
mutating func takeTypedPayloads(for peerID: PeerID) -> [BLEPendingTypedPayload] {
+51 -3
View File
@@ -93,19 +93,46 @@ final class EncryptedHistoryStore: ObservableObject {
var timersByPeerID: [String: DisappearingTimer]
var unreadPeerIDs: [String]
var nostrKeyMapping: [String: String]
var geoDMGeohashByPeerID: [String: String]
var sentReadReceipts: [String]
init(
version: Int = currentVersion,
messagesByPeerID: [String: [BitchatMessage]] = [:],
timersByPeerID: [String: DisappearingTimer] = [:],
unreadPeerIDs: [String] = [],
nostrKeyMapping: [String: String] = [:]
nostrKeyMapping: [String: String] = [:],
geoDMGeohashByPeerID: [String: String] = [:],
sentReadReceipts: [String] = []
) {
self.version = version
self.messagesByPeerID = messagesByPeerID
self.timersByPeerID = timersByPeerID
self.unreadPeerIDs = unreadPeerIDs
self.nostrKeyMapping = nostrKeyMapping
self.geoDMGeohashByPeerID = geoDMGeohashByPeerID
self.sentReadReceipts = sentReadReceipts
}
private enum CodingKeys: String, CodingKey {
case version
case messagesByPeerID
case timersByPeerID
case unreadPeerIDs
case nostrKeyMapping
case geoDMGeohashByPeerID
case sentReadReceipts
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.version = try container.decode(Int.self, forKey: .version)
self.messagesByPeerID = try container.decode([String: [BitchatMessage]].self, forKey: .messagesByPeerID)
self.timersByPeerID = try container.decode([String: DisappearingTimer].self, forKey: .timersByPeerID)
self.unreadPeerIDs = try container.decode([String].self, forKey: .unreadPeerIDs)
self.nostrKeyMapping = try container.decode([String: String].self, forKey: .nostrKeyMapping)
self.geoDMGeohashByPeerID = try container.decodeIfPresent([String: String].self, forKey: .geoDMGeohashByPeerID) ?? [:]
self.sentReadReceipts = try container.decodeIfPresent([String].self, forKey: .sentReadReceipts) ?? []
}
var isEmpty: Bool {
@@ -307,6 +334,8 @@ final class EncryptedHistoryStore: ObservableObject {
func save(
from store: ConversationStore,
nostrKeyMapping: [PeerID: String],
geoDMGeohashByPeerID: [PeerID: String] = [:],
sentReadReceipts: Set<String> = [],
now: Date = Date(),
synchronous: Bool = false
) {
@@ -323,6 +352,8 @@ final class EncryptedHistoryStore: ObservableObject {
var messagesByPeerID: [String: [BitchatMessage]] = [:]
var unreadPeerIDs: [String] = []
var mappedKeys: [String: String] = [:]
var mappedGeohashes: [String: String] = [:]
var persistedMessageIDs = Set<String>()
for (id, conversation) in store.conversationsByID {
guard case .direct(let handle) = id else { continue }
@@ -338,6 +369,9 @@ final class EncryptedHistoryStore: ObservableObject {
? Array(retained.suffix(Self.maxMessagesPerConversation))
: retained
messagesByPeerID[rawPeerID] = bounded
for message in bounded {
persistedMessageIDs.insert(message.id)
}
if conversation.isUnread {
unreadPeerIDs.append(rawPeerID)
@@ -345,6 +379,9 @@ final class EncryptedHistoryStore: ObservableObject {
if let nostrKey = nostrKeyMapping[peerID] {
mappedKeys[rawPeerID] = nostrKey
}
if let geohash = geoDMGeohashByPeerID[peerID] {
mappedGeohashes[rawPeerID] = geohash
}
}
var timersByPeerID: [String: DisappearingTimer] = [:]
@@ -352,11 +389,17 @@ final class EncryptedHistoryStore: ObservableObject {
timersByPeerID[peerID.id] = timer
}
// Only seal read-receipt IDs for retained non-ephemeral messages so
// RAM-only or disappeared chats never leak message IDs onto disk.
let retainedReadReceipts = sentReadReceipts.intersection(persistedMessageIDs).sorted()
let snapshot = Snapshot(
messagesByPeerID: messagesByPeerID,
timersByPeerID: timersByPeerID,
unreadPeerIDs: unreadPeerIDs,
nostrKeyMapping: mappedKeys
nostrKeyMapping: mappedKeys,
geoDMGeohashByPeerID: mappedGeohashes,
sentReadReceipts: retainedReadReceipts
)
persistSnapshot(snapshot, synchronous: synchronous)
}
@@ -400,13 +443,18 @@ final class EncryptedHistoryStore: ObservableObject {
let activeTimers = snapshot.timersByPeerID.filter { $0.value != .off }
let keptKeys = snapshot.nostrKeyMapping.filter { prunedMessages[$0.key] != nil }
let keptGeohashes = snapshot.geoDMGeohashByPeerID.filter { prunedMessages[$0.key] != nil }
let retainedIDs = Set(prunedMessages.values.flatMap { $0.map(\.id) })
let keptReadReceipts = snapshot.sentReadReceipts.filter { retainedIDs.contains($0) }
return Snapshot(
version: Snapshot.currentVersion,
messagesByPeerID: prunedMessages,
timersByPeerID: activeTimers,
unreadPeerIDs: validUnread,
nostrKeyMapping: keptKeys
nostrKeyMapping: keptKeys,
geoDMGeohashByPeerID: keptGeohashes,
sentReadReceipts: keptReadReceipts
)
}
+8 -1
View File
@@ -541,12 +541,19 @@ final class MessageRouter {
}
/// Returns true only when the receipt was handed to a reachable transport.
/// Prefers a transport that can deliver securely right now (established
/// Noise session on BLE, or connected DM relay on Nostr), then a connected
/// transport, then any reachable transport — avoiding throwing receipts
/// into a stale BLE reachability retention window when Nostr is live.
/// A false result means it was dropped (no route) and must NOT be recorded
/// as sent, or the sender's message would stay unread forever — the receipt
/// is retried on the next read scan (chat open / foreground / reconnect).
@discardableResult
func sendReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) -> Bool {
if let transport = reachableTransport(for: peerID) {
let transport = transports.first { $0.isPeerReachable(peerID) && $0.canDeliverSecurely(to: peerID) }
?? connectedTransport(for: peerID)
?? reachableTransport(for: peerID)
if let transport {
SecureLogger.debug("Routing READ ack via \(type(of: transport)) to \(peerID.id.prefix(8))… id=\(receipt.originalMessageID.prefix(8))…", category: .session)
transport.sendReadReceipt(receipt, to: peerID)
return true
+2 -2
View File
@@ -548,7 +548,7 @@ extension NostrTransport {
SecureLogger.error("NostrTransport: failed to embed READ ack", category: .session)
return
}
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity, expectedGeneration: generation)
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity, registerPending: true, expectedGeneration: generation)
case .deliveredDirect(let messageID, let peerID):
guard let recipientNpub = resolveRecipientNpub(for: peerID),
@@ -559,7 +559,7 @@ extension NostrTransport {
SecureLogger.error("NostrTransport: failed to embed DELIVERED ack", category: .session)
return
}
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity, expectedGeneration: generation)
sendWrappedMessage(content: ack, recipientHex: recipientHex, senderIdentity: senderIdentity, registerPending: true, expectedGeneration: generation)
case .deliveredGeohash(let messageID, let recipientHex, let identity):
SecureLogger.debug("GeoDM: send DELIVERED mid=\(messageID.prefix(8))…", category: .session)
@@ -25,6 +25,7 @@ enum PrivacyMode: String, CaseIterable, Identifiable {
enum PrivacyModeSettings {
static let modeKey = "bitchat.privacyMode"
static let persistHistoryKey = "bitchat.persistPrivateHistory"
static let sendReadReceiptsKey = "bitchat.sendReadReceipts"
static let migrationCompletedKey = "bitchat.privacyMode.migrationV2Completed"
static let didChangeNotification = Notification.Name("bitchat.privacyModeDidChange")
@@ -140,6 +141,33 @@ enum PrivacyModeSettings {
notificationCenter.post(name: didChangeNotification, object: nil)
}
/// Whether outbound read receipts are emitted when viewing private messages.
/// Defaults to `true` in Everyday Mode and is always `false` in Stealth Mode
/// so high-risk users never broadcast live reading or foreground activity.
static func shouldSendReadReceipts(in defaults: UserDefaults = .standard) -> Bool {
if currentMode(in: defaults) == .stealth {
return false
}
if let stored = defaults.object(forKey: sendReadReceiptsKey) as? Bool {
return stored
}
return true
}
static var sendReadReceipts: Bool {
get { shouldSendReadReceipts() }
set { setSendReadReceipts(newValue) }
}
static func setSendReadReceipts(
_ enabled: Bool,
in defaults: UserDefaults = .standard,
notificationCenter: NotificationCenter = .default
) {
defaults.set(enabled, forKey: sendReadReceiptsKey)
notificationCenter.post(name: didChangeNotification, object: nil)
}
/// Whether the hidden triple-tap panic wipe gesture on the header logo is armed.
/// Armed in Stealth Mode; in Everyday Mode panic wipe remains available in Settings.
static func isTripleTapPanicEnabled(in defaults: UserDefaults = .standard) -> Bool {
@@ -194,6 +222,7 @@ enum PrivacyModeSettings {
) {
defaults.removeObject(forKey: modeKey)
defaults.removeObject(forKey: persistHistoryKey)
defaults.removeObject(forKey: sendReadReceiptsKey)
notificationCenter.post(name: didChangeNotification, object: nil)
}
@@ -211,6 +240,7 @@ enum PrivacyModeSettings {
|| (wasTorEnabled ?? NetworkActivationService.persistedTorPreference(in: defaults))
defaults.removeObject(forKey: modeKey)
defaults.removeObject(forKey: persistHistoryKey)
defaults.removeObject(forKey: sendReadReceiptsKey)
defaults.set(true, forKey: migrationCompletedKey)
if wasStealthOrTor {
defaults.set(true, forKey: NetworkActivationService.torPreferenceKey)
+9 -86
View File
@@ -10,9 +10,10 @@ import BitLogger
import BitFoundation
import Foundation
/// Manages private chat session policy (selection delegation, read receipts,
/// Manages private chat session policy (selection delegation, unread clearing,
/// consolidation). Message and selection state live in the single-writer
/// `ConversationStore`.
/// `ConversationStore`; read-receipt tracking and sending live exclusively in
/// `ChatViewModel` / `ChatLifecycleCoordinator`.
@MainActor
final class PrivateChatManager {
/// Current direct-conversation selection, read directly from `ConversationStore`.
@@ -20,11 +21,7 @@ final class PrivateChatManager {
conversationStore?.selectedPrivatePeerID
}
var sentReadReceipts: Set<String> = [] // Made accessible for ChatViewModel
weak var meshService: Transport?
// Route acks/receipts via MessageRouter (chooses mesh or Nostr)
weak var messageRouter: MessageRouter?
// Peer service for looking up peer info during consolidation
weak var unifiedPeerService: UnifiedPeerService?
/// Single source of truth for message and selection state; injected by
@@ -36,10 +33,6 @@ final class PrivateChatManager {
self.conversationStore = conversationStore
}
func resetForPanic() {
sentReadReceipts.removeAll(keepingCapacity: false)
}
#if DEBUG
// MARK: - Derived message state (read-only compat views)
@@ -121,39 +114,14 @@ final class PrivateChatManager {
return hasUnreadMessages
}
/// Syncs the read receipt tracking between manager and view model for sent
/// messages. "Sent" means carrying my peer ID, never merely my nickname:
/// a namesake's delivered message still gets its READ receipt, and my
/// messages from before a rename still count as mine.
@MainActor
func syncReadReceiptsForSentMessages(peerID: PeerID, externalReceipts: inout Set<String>) {
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:
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
/// store's intent (the store owns it); the manager keeps its side
/// effects (read receipts, unread clearing).
/// Start a private chat with a peer. Selection and unread clearing mutate
/// through the store's intent API; outbound read-receipt routing is owned
/// solely by `ChatLifecycleCoordinator.markPrivateMessagesAsRead(from:)`.
@MainActor
func startChat(with peerID: PeerID) {
// Also creates the conversation if needed and updates the derived
// `selectedConversationID`; `selectedPeer` mirrors the change.
conversationStore?.setSelectedPrivatePeer(peerID)
// Mark messages as read
markAsRead(from: peerID)
}
@@ -163,56 +131,11 @@ final class PrivateChatManager {
conversationStore?.setSelectedPrivatePeer(nil)
}
/// Mark messages from a peer as read
/// Clears the unread indicator for a peer's direct conversation.
/// Read-receipt transmission is owned exclusively by `ChatLifecycleCoordinator`
/// so there is a single source of truth for sent receipts and privacy gates.
@MainActor
func markAsRead(from peerID: PeerID) {
conversationStore?.markRead(.directPeer(peerID))
// Send read receipts for unread messages that haven't been sent yet
// A courier join preserves the mesh rows' short sender IDs.
let shortPeerID = peerID.toShort()
for message in messages(for: peerID) {
if (message.senderPeerID == peerID || message.senderPeerID == shortPeerID)
&& !message.isRelay && !sentReadReceipts.contains(message.id) {
sendReadReceipt(for: message)
}
}
}
// MARK: - Private Methods
private func sendReadReceipt(for message: BitchatMessage) {
guard !sentReadReceipts.contains(message.id),
let senderPeerID = message.senderPeerID else {
return
}
// Create read receipt using the simplified method
let receipt = ReadReceipt(
originalMessageID: message.id,
readerID: meshService?.myPeerID ?? PeerID(str: ""),
readerNickname: meshService?.myNickname ?? ""
)
// Route via MessageRouter to avoid handshakeRequired spam when session isn't established
if let router = messageRouter {
SecureLogger.debug("PrivateChatManager: sending READ ack for \(message.id.prefix(8))… to \(senderPeerID.id.prefix(8))… via router", category: .session)
let messageID = message.id
// Claim the receipt synchronously so a second read scan in the
// same runloop pass (chat open triggers two) can't route a
// duplicate; release the claim on a failed route (no reachable
// transport) so a later read scan retries instead of permanently
// losing the receipt.
sentReadReceipts.insert(messageID)
Task { @MainActor [weak self] in
if !router.sendReadReceipt(receipt, to: senderPeerID) {
self?.sentReadReceipts.remove(messageID)
}
}
} else {
// Fallback: preserve previous behavior (best-effort mesh send).
sentReadReceipts.insert(message.id)
meshService?.sendReadReceipt(receipt, to: senderPeerID)
}
}
}
+3
View File
@@ -154,6 +154,9 @@ enum TransportConfig {
static let uiStartupPhaseDurationSeconds: TimeInterval = 2.0
static let uiReadReceiptRetryShortSeconds: TimeInterval = 0.1
static let uiReadReceiptRetryLongSeconds: TimeInterval = 0.5
// Only unmark recent incoming messages on BLE disconnect so reconnects
// recover receipts lost mid-drop without replaying full chat history.
static let bleReadReceiptDisconnectRetryWindowSeconds: TimeInterval = 5 * 60
static let uiBatchDispatchStaggerSeconds: TimeInterval = 0.15
static let uiScrollThrottleSeconds: TimeInterval = 0.15
static let uiAnimationMediumSeconds: TimeInterval = 0.2
@@ -123,7 +123,6 @@ final class ChatDeliveryCoordinator {
func cleanupOldReadReceipts() {
guard !context.isStartupPhase else { return }
let validMessageIDs = context.privateMessageIDs()
guard !validMessageIDs.isEmpty else { return }
let removedCount = context.pruneSentReadReceipts(keeping: validMessageIDs)
if removedCount > 0 {
@@ -14,8 +14,14 @@ protocol ChatLifecycleContext: ChatIdentityContext, ChatDirectMessageStoreContex
// MARK: Chat & receipt state
var unreadPrivateMessages: Set<PeerID> { get }
var selectedPrivateChatPeer: PeerID? { get }
var isAppActive: Bool { get }
var sendReadReceiptsEnabled: Bool { get }
var sentReadReceipts: Set<String> { get }
var nostrKeyMapping: [PeerID: String] { get }
/// Originating geohash bound to a GeoDM conversation, if recorded.
func geohashForGeoDM(_ peerID: PeerID) -> String?
/// Whether Nostr network activation permits sending a GeoDM read receipt now.
var canSendGeohashReadReceipt: Bool { get }
/// Records that a read receipt is being sent for `messageID`.
/// Returns `false` when one was already recorded — the caller must skip sending.
@discardableResult
@@ -59,6 +65,13 @@ protocol ChatLifecycleContext: ChatIdentityContext, ChatDirectMessageStoreContex
func verifyIdentityKeyExists() -> Bool
}
extension ChatLifecycleContext {
var isAppActive: Bool { true }
var sendReadReceiptsEnabled: Bool { true }
func geohashForGeoDM(_ peerID: PeerID) -> String? { nil }
var canSendGeohashReadReceipt: Bool { true }
}
extension ChatViewModel: ChatLifecycleContext {
// `messages`, `privateMessages(for:)`, `unreadPrivateMessages`,
// `selectedPrivateChatPeer`, `sentReadReceipts`, `nickname`, `myPeerID`,
@@ -77,6 +90,12 @@ extension ChatViewModel: ChatLifecycleContext {
privateChatManager.markAsRead(from: peerID)
}
var canSendGeohashReadReceipt: Bool {
networkActivationAllowed
&& NetworkActivationService.shared.activationAllowed
&& NostrRelayManager.shared.isDMRelayConnected
}
func scheduleOnMainAfter(_ delay: TimeInterval, _ work: @escaping @MainActor () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
Task { @MainActor in
@@ -122,7 +141,10 @@ final class ChatLifecycleCoordinator {
let context = self.context
context.scheduleOnMainAfter(TransportConfig.uiAnimationMediumSeconds) { [weak context] in
context?.markPrivateMessagesAsRead(from: peerID)
guard let context,
context.isAppActive,
context.selectedPrivateChatPeer == peerID else { return }
context.markPrivateMessagesAsRead(from: peerID)
}
}
@@ -164,10 +186,27 @@ final class ChatLifecycleCoordinator {
// receipt matching can't silently start leaking receipts into groups.
guard !peerID.isGroup else { return }
if peerID.isGeoDM,
let recipientHex = context.nostrKeyMapping[peerID],
case .location(let channel) = context.activeChannel,
let identity = try? context.deriveNostrIdentity(forGeohash: channel.geohash) {
if peerID.isGeoDM {
// GeoDMs are always handled exclusively on the Nostr path — never
// fall through into BLE/favorite routing even when the active
// channel is `.mesh` or read receipts are disabled.
guard context.isAppActive,
context.sendReadReceiptsEnabled,
context.canSendGeohashReadReceipt,
let recipientHex = context.nostrKeyMapping[peerID] else {
return
}
let geohash: String? = context.geohashForGeoDM(peerID) ?? {
if case .location(let channel) = context.activeChannel {
return channel.geohash
}
return nil
}()
guard let geohash,
let identity = try? context.deriveNostrIdentity(forGeohash: geohash) else {
return
}
let messages = context.privateMessages(for: peerID)
for message in messages where message.senderPeerID == peerID && !message.isRelay {
guard !context.sentReadReceipts.contains(message.id) else { continue }
@@ -199,10 +238,14 @@ final class ChatLifecycleCoordinator {
}
}
// Unread state is already cleared above; only emit wire read receipts
// when the app is active in the foreground and the user's privacy
// posture permits read receipts.
guard context.isAppActive, context.sendReadReceiptsEnabled else { return }
// No Nostr-key gate here: the router picks whatever transport can
// reach the peer (mesh included), so read receipts must flow for
// non-favorite mesh peers too. `sentReadReceipts` dedups against the
// PrivateChatManager path; the router drops receipts it can't route.
// non-favorite mesh peers too. The router drops receipts it can't route.
// A full-key conversation can contain mesh rows whose sender IDs stay short.
let shortPeerID = peerID.toShort()
@@ -18,6 +18,8 @@ protocol ChatLiveVoiceContext: AnyObject {
var nickname: String { get }
var myPeerID: PeerID { get }
var selectedPrivateChatPeer: PeerID? { get }
var isAppActive: Bool { get }
var sendReadReceiptsEnabled: Bool { get }
/// Whether the public mesh timeline is what's on screen (autoplay gate
/// for public bursts).
var isViewingPublicMeshTimeline: Bool { get }
@@ -42,6 +44,8 @@ protocol ChatLiveVoiceContext: AnyObject {
func hasSentReadReceipt(_ messageID: String) -> Bool
@discardableResult
func markReadReceiptSent(_ messageID: String) -> Bool
@discardableResult
func routeReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) -> Bool
func sendMeshReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID)
/// Removes a message from whichever conversation holds it.
func removeMessage(withID messageID: String, cleanupFile: Bool)
@@ -63,6 +67,13 @@ protocol ChatLiveVoiceContext: AnyObject {
}
extension ChatLiveVoiceContext {
var isAppActive: Bool { true }
var sendReadReceiptsEnabled: Bool { true }
@discardableResult
func routeReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) -> Bool {
sendMeshReadReceipt(receipt, to: peerID)
return true
}
func setActiveDirectVoiceTalker(_ talker: LiveVoiceTalker?) {}
func resolveAuthorizedGroupPeerID(forGroupID groupID: Data, senderPeerID: PeerID) -> PeerID? { nil }
func appendGroupLiveVoiceMessage(_ message: BitchatMessage, to groupPeerID: PeerID) {}
@@ -476,9 +487,11 @@ final class ChatLiveVoiceCoordinator {
case .directMessage:
// Capture read state before rekeying. The user may have read the
// live bubble and navigated away before the finalized .m4a lands.
let shouldSendAdoptedReadReceipt =
context.hasSentReadReceipt(finished.messageID)
|| context.selectedPrivateChatPeer == finished.peerID
// Never emit a read receipt while backgrounded/locked or when read
// receipts are disabled.
let shouldSendAdoptedReadReceipt = context.sendReadReceiptsEnabled
&& (context.hasSentReadReceipt(finished.messageID)
|| (context.isAppActive && context.selectedPrivateChatPeer == finished.peerID))
// Insert first so replacing the only row in a DM never
// transiently deletes its conversation, unread state, or current
@@ -491,13 +504,15 @@ final class ChatLiveVoiceCoordinator {
// before the sender created its finalized media row. Re-emit once
// for the adopted stable ID now that the file has arrived.
if shouldSendAdoptedReadReceipt,
context.markReadReceiptSent(replacementID) {
!context.hasSentReadReceipt(replacementID) {
let receipt = ReadReceipt(
originalMessageID: replacementID,
readerID: context.myPeerID,
readerNickname: context.nickname
)
context.sendMeshReadReceipt(receipt, to: finished.peerID)
if context.routeReadReceipt(receipt, to: finished.peerID) {
context.markReadReceiptSent(replacementID)
}
}
case .publicMesh:
context.upsertPublicMeshMessage(replacement)
@@ -86,6 +86,9 @@ final class ChatNostrCoordinator {
guard let context else { return }
let convKey = PeerID(nostr_: hex)
context.registerNostrKeyMapping(hex, for: convKey)
if let geohash = context.currentGeohash {
context.registerGeoDMGeohash(geohash, for: convKey)
}
context.startPrivateChat(with: convKey)
}
@@ -50,10 +50,6 @@ protocol ChatPeerIdentityContext: AnyObject {
/// Returns `true` when unread messages were discovered during consolidation.
@discardableResult
func consolidatePrivateMessages(for peerID: PeerID) -> Bool
/// Marks read receipts as sent for own messages already delivered/read in
/// `peerID`'s chat. (Single mutation path into the owner's
/// `sentReadReceipts`; this coordinator never touches the raw set.)
func syncReadReceiptsForSentMessages(for peerID: PeerID)
/// Re-targets the private chat session: selection mutates through the
/// `ConversationStore` intent (the store owns selection).
func beginPrivateChatSession(with peerID: PeerID)
@@ -405,8 +401,6 @@ final class ChatPeerIdentityCoordinator {
SecureLogger.debug("GeoDM: skipping mesh handshake for virtual peerID=\(peerID)", category: .session)
}
context.syncReadReceiptsForSentMessages(for: peerID)
if let fingerprint = getFingerprint(for: peerID) {
context.setStoredFingerprint(fingerprint, for: peerID)
context.selectedPrivateChatFingerprint = fingerprint
@@ -21,6 +21,8 @@ protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageS
/// while the app is backgrounded or the phone is locked must not emit
/// instant read receipts or suppress notifications.
var isAppActive: Bool { get }
/// Whether the user's current privacy posture allows emitting read receipts.
var sendReadReceiptsEnabled: Bool { get }
var nostrKeyMapping: [PeerID: String] { get }
// MARK: Conversation store intents
@@ -44,6 +46,9 @@ protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageS
func privateChatsContainMessage(withID messageID: String) -> Bool
/// `true` when `peerID`'s chat contains a message with `messageID`.
func privateChat(_ peerID: PeerID, containsMessageWithID messageID: String) -> Bool
/// `true` only when `messageID` is one of our outgoing messages in at least
/// one of the authenticated peer's conversation aliases.
func isOutgoingPrivateMessage(_ messageID: String, toAny peerIDs: Set<PeerID>) -> Bool
/// Records that a read receipt is being sent for `messageID`.
/// Returns `false` when one was already recorded — the caller must skip sending.
@@ -82,6 +87,8 @@ protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageS
/// aliases scope the removal to the authenticated sender.
@discardableResult
func markMessageDelivered(_ messageID: String, for peerIDs: [PeerID]) -> Bool
@discardableResult
func routeReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) -> Bool
func sendMeshReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID)
func sendGeohashPrivateMessage(_ content: String, toRecipientHex recipientHex: String, from identity: NostrIdentity, messageID: String)
func sendGeohashDeliveryAck(for messageID: String, toRecipientHex recipientHex: String, from identity: NostrIdentity)
@@ -111,10 +118,23 @@ protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageS
}
extension ChatPrivateConversationContext {
var sendReadReceiptsEnabled: Bool { true }
func reconcileDisappearingTimer(from sourcePeerID: PeerID, to destinationPeerID: PeerID) {}
func registerVerifiedFriendInviteIdentity(_ invite: FriendInvite) {}
func favoriteNoiseKey(forNostrPubkey nostrPubkey: String) -> Data? { nil }
func myNoisePublicKey() -> Data { Data() }
@discardableResult
func routeReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) -> Bool {
sendMeshReadReceipt(receipt, to: peerID)
return true
}
func isOutgoingPrivateMessage(_ messageID: String, toAny peerIDs: Set<PeerID>) -> Bool {
peerIDs.contains { peerID in
privateMessages(for: peerID).contains { message in
message.id == messageID && message.senderPeerID == myPeerID
}
}
}
}
extension ChatViewModel: ChatPrivateConversationContext {
@@ -557,14 +577,7 @@ final class ChatPrivateConversationCoordinator {
// known noise key; the Nostr display name is a geohash-scoped
// fallback (e.g. "anon#678e") that would mislabel favorite-transport
// DMs. Geohash conversations (nostr_ keys) keep the geo name.
let senderName: String = {
if let noiseKey = convKey.noiseKey,
let favoriteNickname = context.favoriteRelationship(forNoiseKey: noiseKey)?.peerNickname,
!favoriteNickname.isEmpty {
return favoriteNickname
}
return context.displayNameForNostrPubkey(senderPubkey)
}()
let senderName = resolvedNostrSenderName(senderPubkey: senderPubkey, convKey: convKey)
// Favorite notifications ride the PM channel over account Nostr DMs;
// never let geohash DMs mutate favorite or identity state.
@@ -605,7 +618,7 @@ final class ChatPrivateConversationCoordinator {
context.markPrivateChatUnread(conversationPeerID)
}
if isViewing {
if isViewing && context.sendReadReceiptsEnabled {
sendReadReceiptIfNeeded(to: messageId, senderPubKey: senderPubkey, from: id)
}
@@ -615,25 +628,35 @@ final class ChatPrivateConversationCoordinator {
}
private func resolvedNostrSenderName(senderPubkey: String, convKey: PeerID) -> String {
if let noiseKey = convKey.noiseKey,
let favoriteNickname = context.favoriteRelationship(forNoiseKey: noiseKey)?.peerNickname,
!favoriteNickname.isEmpty {
return favoriteNickname
}
return context.displayNameForNostrPubkey(senderPubkey)
}
func handleDelivered(_ payload: NoisePayload, senderPubkey: String, convKey: PeerID) {
if context.isNostrBlocked(pubkeyHexLowercased: senderPubkey.lowercased())
|| (convKey.noiseKey != nil && context.isPeerBlocked(convKey)) {
return
}
guard let messageID = String(data: payload.data, encoding: .utf8) else { return }
let aliases = accountConversationAliases(for: convKey)
let clearedRetainedMessage = convKey.noiseKey != nil
? context.markMessageDelivered(messageID, for: aliases)
: false
let hasConversationMessage = aliases.contains {
context.privateChat($0, containsMessageWithID: messageID)
}
if hasConversationMessage {
let isOutgoingMessage = context.isOutgoingPrivateMessage(messageID, toAny: Set(aliases))
if isOutgoingMessage {
let conversationPeerID = consolidateAccountConversationAliases(for: convKey)
let didChange = context.setPrivateDeliveryStatus(
.delivered(to: context.displayNameForNostrPubkey(senderPubkey), at: Date()),
let displayName = resolvedNostrSenderName(senderPubkey: senderPubkey, convKey: convKey)
_ = context.setPrivateDeliveryStatus(
.delivered(to: displayName, at: Date()),
forMessageID: messageID,
peerID: conversationPeerID
)
if didChange {
}
SecureLogger.info(
"GeoDM: recv DELIVERED for mid=\(messageID.prefix(8))… from=\(senderPubkey.prefix(8))…",
category: .session
@@ -652,24 +675,25 @@ final class ChatPrivateConversationCoordinator {
}
func handleReadReceipt(_ payload: NoisePayload, senderPubkey: String, convKey: PeerID) {
if context.isNostrBlocked(pubkeyHexLowercased: senderPubkey.lowercased())
|| (convKey.noiseKey != nil && context.isPeerBlocked(convKey)) {
return
}
guard let messageID = String(data: payload.data, encoding: .utf8) else { return }
let aliases = accountConversationAliases(for: convKey)
let clearedRetainedMessage = convKey.noiseKey != nil
? context.markMessageDelivered(messageID, for: aliases)
: false
let hasConversationMessage = aliases.contains {
context.privateChat($0, containsMessageWithID: messageID)
}
if hasConversationMessage {
let isOutgoingMessage = context.isOutgoingPrivateMessage(messageID, toAny: Set(aliases))
if isOutgoingMessage {
let conversationPeerID = consolidateAccountConversationAliases(for: convKey)
let didChange = context.setPrivateDeliveryStatus(
.read(by: context.displayNameForNostrPubkey(senderPubkey), at: Date()),
let displayName = resolvedNostrSenderName(senderPubkey: senderPubkey, convKey: convKey)
_ = context.setPrivateDeliveryStatus(
.read(by: displayName, at: Date()),
forMessageID: messageID,
peerID: conversationPeerID
)
if didChange {
}
SecureLogger.info("GeoDM: recv READ for mid=\(messageID.prefix(8))… from=\(senderPubkey.prefix(8))…", category: .session)
} else if clearedRetainedMessage {
SecureLogger.debug(
@@ -677,7 +701,7 @@ final class ChatPrivateConversationCoordinator {
category: .session
)
} else {
SecureLogger.warning("GeoDM: read ack for unknown mid=\(messageID.prefix(8))… conv=\(convKey)", category: .session)
SecureLogger.debug("GeoDM: read ack for unknown mid=\(messageID.prefix(8))… conv=\(convKey)", category: .session)
}
}
@@ -737,13 +761,17 @@ final class ChatPrivateConversationCoordinator {
let isViewing = context.isAppActive && context.selectedPrivateChatPeer == peerID
if isViewing {
let receipt = ReadReceipt(
originalMessageID: message.id,
readerID: context.myPeerID,
readerNickname: context.nickname
)
context.sendMeshReadReceipt(receipt, to: peerID)
context.markReadReceiptSent(message.id)
if context.sendReadReceiptsEnabled,
!context.sentReadReceipts.contains(message.id) {
let receipt = ReadReceipt(
originalMessageID: message.id,
readerID: context.myPeerID,
readerNickname: context.nickname
)
if context.routeReadReceipt(receipt, to: peerID) {
context.markReadReceiptSent(message.id)
}
}
} else {
context.markPrivateChatUnread(peerID)
context.notifyPrivateMessage(from: message.sender, message: message.content, peerID: peerID)
@@ -230,6 +230,17 @@ final class ChatTransportEventCoordinator {
stablePeerID = derivedPeerID
}
// Capture recent incoming message IDs BEFORE migrating the selected
// conversation (migration removes the short-ID chat), and bound the
// retry window so a disconnect never triggers a full-history receipt
// burst for older already-acknowledged messages on reconnect.
let retryCutoff = Date().addingTimeInterval(
-TransportConfig.bleReadReceiptDisconnectRetryWindowSeconds
)
let recentReceiptIDs = context.privateMessages(for: peerID)
.filter { $0.senderPeerID == peerID && $0.timestamp >= retryCutoff }
.map(\.id)
if let currentPeerID = context.selectedPrivateChatPeer,
currentPeerID == peerID,
let stablePeerID {
@@ -240,10 +251,9 @@ final class ChatTransportEventCoordinator {
)
}
let receiptIDs = context.privateMessages(for: peerID)
.filter { $0.senderPeerID == peerID }
.map(\.id)
context.unmarkReadReceiptsSent(receiptIDs)
if !recentReceiptIDs.isEmpty {
context.unmarkReadReceiptsSent(recentReceiptIDs)
}
}
}
+53 -81
View File
@@ -482,83 +482,30 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
return scratch
}
// 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 final class ReadReceiptPersistGate: @unchecked Sendable {
private let lock = NSLock()
private var generation: UInt64 = 0
func nextGeneration() -> UInt64 {
lock.lock()
defer { lock.unlock() }
generation &+= 1
return generation
}
func commitIfCurrent(data: Data, expectedGeneration: UInt64, defaults: UserDefaults) {
lock.lock()
defer { lock.unlock() }
guard generation == expectedGeneration else { return }
defaults.set(data, forKey: "sentReadReceipts")
}
func flushSynchronously(receipts: [String], defaults: UserDefaults) {
lock.lock()
defer { lock.unlock() }
generation &+= 1
if receipts.isEmpty {
defaults.removeObject(forKey: "sentReadReceipts")
} else if let data = try? JSONEncoder().encode(receipts) {
defaults.set(data, forKey: "sentReadReceipts")
} else {
SecureLogger.error("❌ Failed to encode read receipts for persistence", category: .session)
}
}
}
private var readReceiptPersistTask: Task<Void, Never>?
private let readReceiptPersistGate = ReadReceiptPersistGate()
// Track sent read receipts to avoid duplicates. Persisted exclusively inside
// `EncryptedHistoryStore` (sealed with the Keychain history key and gated on
// `PrivacyModeSettings.persistPrivateHistory`) so Stealth / RAM-only mode and
// ephemeral chats never write message IDs to plaintext `UserDefaults`.
var sentReadReceipts: Set<String> = [] { // messageID set
didSet {
guard oldValue != sentReadReceipts else { return }
schedulePersistSentReadReceipts()
schedulePersistPrivateHistory()
}
}
private func schedulePersistSentReadReceipts() {
readReceiptPersistTask?.cancel()
let gate = readReceiptPersistGate
let generation = gate.nextGeneration()
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) {
gate.commitIfCurrent(data: data, expectedGeneration: generation, defaults: defaults)
} else {
SecureLogger.error("❌ Failed to encode read receipts for persistence", category: .session)
}
await MainActor.run { [weak self] in
guard let self else { return }
if self.readReceiptPersistTask?.isCancelled == false {
self.readReceiptPersistTask = nil
}
}
}
/// Whether outbound read receipts are currently enabled for this app's privacy posture.
var sendReadReceiptsEnabled: Bool {
PrivacyModeSettings.shouldSendReadReceipts(in: readReceiptsDefaults)
}
/// Cancels any pending debounced write and persists `sentReadReceipts`
/// synchronously (used on termination and panic wipe).
/// Scrubs any legacy plaintext `UserDefaults["sentReadReceipts"]` key and
/// flushes the sealed history store synchronously (used on backgrounding,
/// termination, and panic wipe).
func flushPersistedReadReceiptsSynchronously() {
readReceiptPersistTask?.cancel()
readReceiptPersistTask = nil
readReceiptPersistGate.flushSynchronously(
receipts: Array(sentReadReceipts),
defaults: readReceiptsDefaults
)
if readReceiptsDefaults.object(forKey: "sentReadReceipts") != nil {
readReceiptsDefaults.removeObject(forKey: "sentReadReceipts")
}
flushPersistedPrivateHistorySynchronously()
}
// Track which GeoDM messages we've already sent a delivery ACK for (by messageID)
@@ -580,6 +527,11 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
// Single-writer: mutate only via `registerNostrKeyMapping` / `removeNostrKeyMappings` below.
private(set) var nostrKeyMapping: [PeerID: String] = [:] // senderPeerID -> nostrPubkey
// Track originating geohash per GeoDM conversation so replies and read
// receipts sign with the thread's own per-geohash identity even if the user
// has switched to `.mesh` or a different location channel.
private(set) var geoDMGeohashByPeerID: [PeerID: String] = [:]
// MARK: - Single-Writer Intent Operations
// Owner-side mutation paths for state the coordinator contexts may read
// but not write directly. Each op is the sole way to mutate its backing
@@ -591,11 +543,24 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
nostrKeyMapping[peerID] = pubkey
}
/// Binds a GeoDM conversation key to the geohash whose derived identity owns it.
@MainActor
func registerGeoDMGeohash(_ geohash: String, for peerID: PeerID) {
guard peerID.isGeoDM, !geohash.isEmpty else { return }
geoDMGeohashByPeerID[peerID] = geohash
}
@MainActor
func geohashForGeoDM(_ peerID: PeerID) -> String? {
geoDMGeohashByPeerID[peerID]
}
/// Drops every key mapping that resolves to the given (lowercased) Nostr pubkey.
@MainActor
func removeNostrKeyMappings(matchingPubkeyHexLowercased hex: String) {
for (key, value) in nostrKeyMapping where value.lowercased() == hex {
nostrKeyMapping.removeValue(forKey: key)
geoDMGeohashByPeerID.removeValue(forKey: key)
}
}
@@ -628,17 +593,6 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
sentReadReceipts.subtract(ids)
}
/// Marks read receipts as sent for own messages already delivered/read in
/// `peerID`'s chat, syncing the chat manager's tracking with the persisted
/// set. (Wraps the manager's `inout` sync so the raw set never leaks.)
@MainActor
func syncReadReceiptsForSentMessages(for peerID: PeerID) {
privateChatManager.syncReadReceiptsForSentMessages(
peerID: peerID,
externalReceipts: &sentReadReceipts
)
}
/// Drops every recorded read receipt whose message ID is no longer valid.
/// Returns the number of receipts removed.
@MainActor
@@ -1401,6 +1355,8 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
encryptedHistoryStore.save(
from: conversations,
nostrKeyMapping: nostrKeyMapping,
geoDMGeohashByPeerID: geoDMGeohashByPeerID,
sentReadReceipts: sentReadReceipts,
synchronous: true
)
}
@@ -1409,6 +1365,9 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
historyPersistTask?.cancel()
historyPersistTask = nil
encryptedHistoryStore.clearPersistedHistory()
if readReceiptsDefaults.object(forKey: "sentReadReceipts") != nil {
readReceiptsDefaults.removeObject(forKey: "sentReadReceipts")
}
}
func isConversationMuted(for peerID: PeerID) -> Bool {
@@ -1482,7 +1441,9 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
for id in peerIDsToRemove {
conversations.removeConversation(.directPeer(id))
encryptedHistoryStore.setTimer(.off, for: id)
geoDMGeohashByPeerID.removeValue(forKey: id)
}
_ = pruneSentReadReceipts(keeping: conversations.directMessageIDs())
// Remove any favorite entry for this contact so the deleted chat
// doesn't immediately reappear as an empty favorite row in the inbox.
@@ -1574,6 +1535,12 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
for (rawPeerID, nostrKey) in snapshot.nostrKeyMapping where nostrKeyMapping[PeerID(str: rawPeerID)] == nil {
nostrKeyMapping[PeerID(str: rawPeerID)] = nostrKey
}
for (rawPeerID, geohash) in snapshot.geoDMGeohashByPeerID where geoDMGeohashByPeerID[PeerID(str: rawPeerID)] == nil {
geoDMGeohashByPeerID[PeerID(str: rawPeerID)] = geohash
}
if !snapshot.sentReadReceipts.isEmpty {
sentReadReceipts.formUnion(snapshot.sentReadReceipts)
}
let unreadSet = Set(snapshot.unreadPeerIDs)
for (rawPeerID, messages) in snapshot.messagesByPeerID where !messages.isEmpty {
let peerID = PeerID(str: rawPeerID)
@@ -1592,7 +1559,12 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
historyPersistTask = Task { @MainActor [weak self] in
try? await Task.sleep(nanoseconds: 600_000_000)
guard !Task.isCancelled, let self, !self.isPanicResetting else { return }
self.encryptedHistoryStore.save(from: self.conversations, nostrKeyMapping: self.nostrKeyMapping)
self.encryptedHistoryStore.save(
from: self.conversations,
nostrKeyMapping: self.nostrKeyMapping,
geoDMGeohashByPeerID: self.geoDMGeohashByPeerID,
sentReadReceipts: self.sentReadReceipts
)
self.historyPersistTask = nil
}
}
@@ -2190,13 +2162,13 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel
_ = clearGeoSamplingSubs()
cachedGeohashIdentity = nil
nostrKeyMapping.removeAll()
geoDMGeohashByPeerID.removeAll()
// Every pubkey seen in any geohash this session, with when.
participantTracker.clear()
// Clear read receipt tracking
sentReadReceipts.removeAll()
flushPersistedReadReceiptsSynchronously()
privateChatManager.resetForPanic()
deduplicationService.clearAll()
// IMPORTANT: Clear Nostr-related state
@@ -57,8 +57,19 @@ final class ChatViewModelBootstrapper {
self.viewModel = viewModel
}
/// One-time migration from legacy plaintext `UserDefaults["sentReadReceipts"]`.
/// Read receipts are now sealed inside `EncryptedHistoryStore` alongside private
/// history so Stealth/RAM-only mode never leaves message IDs on disk. Any legacy
/// plaintext key is always scrubbed from `UserDefaults`; its IDs are only loaded
/// into memory when private history persistence is enabled.
static func loadPersistedReadReceipts(userDefaults: UserDefaults = .standard) -> Set<String> {
guard let data = userDefaults.data(forKey: "sentReadReceipts"),
defer {
if userDefaults.object(forKey: "sentReadReceipts") != nil {
userDefaults.removeObject(forKey: "sentReadReceipts")
}
}
guard PrivacyModeSettings.shouldPersistPrivateHistory(in: userDefaults),
let data = userDefaults.data(forKey: "sentReadReceipts"),
let receipts = try? JSONDecoder().decode([String].self, from: data) else {
return []
}
@@ -87,7 +98,6 @@ final class ChatViewModelBootstrapper {
private extension ChatViewModelBootstrapper {
func wireServiceGraph() {
viewModel.privateChatManager.conversationStore = viewModel.conversations
viewModel.privateChatManager.messageRouter = viewModel.messageRouter
viewModel.privateChatManager.unifiedPeerService = viewModel.unifiedPeerService
viewModel.unifiedPeerService.messageRouter = viewModel.messageRouter
// Surface silent outbox drops (attempt cap, TTL expiry, overflow
@@ -260,6 +260,7 @@ final class GeohashSubscriptionManager {
self?.inbound.handleGiftWrap(
giftWrap,
id: identity,
geohash: channel.geohash,
outerSignatureAlreadyVerified: true
)
}
@@ -30,6 +30,8 @@ protocol NostrInboundPipelineContext: AnyObject {
func setGeoNickname(_ nickname: String, forPubkey pubkeyHex: String)
/// Records the Nostr pubkey behind a (possibly virtual) peer ID.
func registerNostrKeyMapping(_ pubkey: String, for peerID: PeerID)
/// Binds a GeoDM conversation key to the geohash whose derived identity owns it.
func registerGeoDMGeohash(_ geohash: String, for peerID: PeerID)
/// `seenAt` is the event's own timestamp, so replayed history doesn't
/// count its authors as present. Returns whether the activity counted.
@discardableResult
@@ -65,6 +67,7 @@ protocol NostrInboundPipelineContext: AnyObject {
}
extension NostrInboundPipelineContext {
func registerGeoDMGeohash(_ geohash: String, for peerID: PeerID) {}
func handlePrivateMessage(
_ payload: NoisePayload,
senderPubkey: String,
@@ -266,6 +269,7 @@ final class NostrInboundPipeline {
func handleGiftWrap(
_ giftWrap: NostrEvent,
id: NostrIdentity,
geohash: String? = nil,
outerSignatureAlreadyVerified: Bool = false
) {
guard let context else { return }
@@ -276,10 +280,12 @@ final class NostrInboundPipeline {
// wipe between spawn and delivery bumps the generation, and the task
// drops its result instead of delivering plaintext post-wipe.
let wipeGeneration = self.wipeGeneration
let resolvedGeohash = geohash ?? context.currentGeohash
Task.detached(priority: .userInitiated) { [weak self] in
await self?.processGiftWrap(
giftWrap,
geohashIdentity: id,
geohash: resolvedGeohash,
initialWipeGeneration: wipeGeneration,
outerSignatureAlreadyVerified: outerSignatureAlreadyVerified
)
@@ -308,6 +314,7 @@ final class NostrInboundPipeline {
await processGiftWrap(
giftWrap,
geohashIdentity: nil,
geohash: nil,
initialWipeGeneration: nil,
outerSignatureAlreadyVerified: outerSignatureAlreadyVerified
)
@@ -320,6 +327,7 @@ final class NostrInboundPipeline {
private func processGiftWrap(
_ giftWrap: NostrEvent,
geohashIdentity: NostrIdentity?,
geohash: String?,
initialWipeGeneration: UInt64?,
outerSignatureAlreadyVerified: Bool
) async {
@@ -407,6 +415,9 @@ final class NostrInboundPipeline {
let convKey: PeerID
if isGeohashDM {
convKey = PeerID(nostr_: senderPubkey)
if let geohash {
context.registerGeoDMGeohash(geohash, for: convKey)
}
} else {
let actualSenderNoiseKey = self.findNoiseKey(for: senderPubkey)
convKey = PeerID(str: actualSenderNoiseKey?.hexEncodedString()) ?? PeerID(nostr_: senderPubkey)
+18
View File
@@ -34,6 +34,7 @@ struct AppInfoView: View {
@State private var showTopology = false
@State private var privacyMode = PrivacyModeSettings.mode
@State private var persistPrivateHistory = PrivacyModeSettings.persistPrivateHistory
@State private var sendReadReceipts = PrivacyModeSettings.sendReadReceipts
@ObservedObject private var pttPreferences = PTTPreferences.shared
@State private var locationNotesEnabled = LocationNotesSettings.enabled
@State private var hideMessagePreviews = NotificationPrivacySettings.hideMessagePreviews
@@ -345,6 +346,7 @@ struct AppInfoView: View {
.onReceive(NotificationCenter.default.publisher(for: PrivacyModeSettings.didChangeNotification)) { _ in
privacyMode = PrivacyModeSettings.mode
persistPrivateHistory = PrivacyModeSettings.persistPrivateHistory
sendReadReceipts = PrivacyModeSettings.sendReadReceipts
hideMessagePreviews = NotificationPrivacySettings.hideMessagePreviews
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
@@ -466,6 +468,7 @@ struct AppInfoView: View {
onClearPersistedHistory: onClearPersistedHistory
)
persistPrivateHistory = PrivacyModeSettings.persistPrivateHistory
sendReadReceipts = PrivacyModeSettings.sendReadReceipts
hideMessagePreviews = NotificationPrivacySettings.hideMessagePreviews
}
)
@@ -719,6 +722,21 @@ struct AppInfoView: View {
.disabled(privacyMode == .stealth)
}
settingsCard {
settingToggle(
title: Text(String(localized: "app_info.settings.read_receipts.title", defaultValue: "Send Read Receipts", comment: "Title of the setting that controls whether private message read receipts are sent")),
subtitle: Text(String(localized: "app_info.settings.read_receipts.subtitle", defaultValue: "Lets people know when you've viewed their private messages. Automatically off in Stealth Mode.", comment: "Subtitle explaining the read receipts toggle")),
isOn: Binding(
get: { sendReadReceipts && privacyMode == .everyday },
set: { newValue in
sendReadReceipts = newValue
PrivacyModeSettings.setSendReadReceipts(newValue)
}
)
)
.disabled(privacyMode == .stealth)
}
settingsCard {
settingToggle(
title: Text(verbatim: Strings.Settings.hidePreviewsTitle),
@@ -10,6 +10,13 @@ import SwiftUI
import BitFoundation
extension DeliveryStatus {
private static let statusTimeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
return formatter
}()
/// Localized, user-facing description of the status. Used for macOS
/// tooltips, the tap-to-reveal caption under a message, and VoiceOver —
/// the glyphs alone are unexplained 10pt icons.
@@ -23,18 +30,20 @@ extension DeliveryStatus {
return String(localized: "content.delivery.sent", comment: "Delivery status description for a sent but not yet confirmed private message")
case .carried:
return String(localized: "content.delivery.carried", defaultValue: "Carried by a friend who may meet them", comment: "Delivery status description for messages handed to a courier for physical delivery")
case .delivered(let nickname, _):
return String(
case .delivered(let nickname, let timestamp):
let base = String(
format: String(localized: "content.delivery.delivered_to", comment: "Tooltip for delivered private messages"),
locale: .current,
nickname
)
case .read(let nickname, _):
return String(
return "\(base) · \(Self.statusTimeFormatter.string(from: timestamp))"
case .read(let nickname, let timestamp):
let base = String(
format: String(localized: "content.delivery.read_by", comment: "Tooltip for read private messages"),
locale: .current,
nickname
)
return "\(base) · \(Self.statusTimeFormatter.string(from: timestamp))"
case .failed(let reason):
return String(
format: String(localized: "content.delivery.failed", comment: "Tooltip for failed message delivery"),
+19 -5
View File
@@ -226,6 +226,7 @@ private struct MessageListContentView: View {
@State private var emptyStateViewportHeight: CGFloat = 0
@State private var quoteHighlightMessageID: String?
@State private var quoteHighlightTask: Task<Void, Never>?
@State private var readReceiptRetryTask: Task<Void, Never>?
@Environment(\.appTheme) private var theme
@ThemedPalette private var palette
@@ -472,17 +473,28 @@ private struct MessageListContentView: View {
Button(String(localized: "common.cancel"), role: .cancel) {}
}
.onAppear {
// Also check when view appears
// Also check when view appears; cancel pending retries if the
// user navigates away or backgrounds before they fire.
readReceiptRetryTask?.cancel()
readReceiptRetryTask = nil
if let peerID = privatePeer,
let privateConversationModel = appEnvironmentModels?.privateConversationModel {
// Try multiple times to ensure read receipts are sent
privateConversationModel.markMessagesAsRead(from: peerID)
DispatchQueue.main.asyncAfter(deadline: .now() + TransportConfig.uiReadReceiptRetryShortSeconds) {
readReceiptRetryTask = Task { @MainActor in
let shortNanos = UInt64(TransportConfig.uiReadReceiptRetryShortSeconds * 1_000_000_000)
try? await Task.sleep(nanoseconds: shortNanos)
guard !Task.isCancelled,
privateConversationModel.selectedPeerID == peerID else { return }
privateConversationModel.markMessagesAsRead(from: peerID)
}
DispatchQueue.main.asyncAfter(deadline: .now() + TransportConfig.uiReadReceiptRetryLongSeconds) {
let remainingSeconds = max(
0,
TransportConfig.uiReadReceiptRetryLongSeconds - TransportConfig.uiReadReceiptRetryShortSeconds
)
try? await Task.sleep(nanoseconds: UInt64(remainingSeconds * 1_000_000_000))
guard !Task.isCancelled,
privateConversationModel.selectedPeerID == peerID else { return }
privateConversationModel.markMessagesAsRead(from: peerID)
}
}
@@ -491,6 +503,8 @@ private struct MessageListContentView: View {
cancelFollowScroll()
quoteHighlightTask?.cancel()
quoteHighlightTask = nil
readReceiptRetryTask?.cancel()
readReceiptRetryTask = nil
}
}
// Reset UIScrollView state when switching channels or DMs so a deep
@@ -32,14 +32,23 @@ private final class MockChatLifecycleContext: ChatLifecycleContext {
}
var unreadPrivateMessages: Set<PeerID> = []
var selectedPrivateChatPeer: PeerID?
var isAppActive = true
var sendReadReceiptsEnabled = true
var canSendGeohashReadReceipt = true
var sentReadReceipts: Set<String> = []
var nickname = "me"
var myPeerID = PeerID(str: "0011223344556677")
var activeChannel: ChannelID = .mesh
var nostrKeyMapping: [PeerID: String] = [:]
var geoDMGeohashByPeerID: [PeerID: String] = [:]
private(set) var derivedGeohashes: [String] = []
private(set) var ownerLevelReadPasses: [PeerID] = []
private(set) var managerReadMarks: [PeerID] = []
func geohashForGeoDM(_ peerID: PeerID) -> String? {
geoDMGeohashByPeerID[peerID]
}
// Conversation store intents
@discardableResult
func appendPrivateMessage(_ message: BitchatMessage, to peerID: PeerID) -> Bool {
@@ -68,11 +77,16 @@ private final class MockChatLifecycleContext: ChatLifecycleContext {
managerReadMarks.append(peerID)
}
// Scheduled work runs synchronously so tests never poll wall-clock queues.
// Scheduled work runs synchronously by default so tests never poll wall-clock queues.
private(set) var scheduledDelays: [TimeInterval] = []
var deferScheduledWork: ((@escaping @MainActor () -> Void) -> Void)?
func scheduleOnMainAfter(_ delay: TimeInterval, _ work: @escaping @MainActor () -> Void) {
scheduledDelays.append(delay)
work()
if let deferScheduledWork {
deferScheduledWork(work)
} else {
work()
}
}
// Peers & sessions
@@ -381,6 +395,92 @@ struct ChatLifecycleCoordinatorContextTests {
#expect(context.sentReadReceipts.contains("in-2"))
}
@Test @MainActor
func markPrivateMessagesAsRead_respectsSendReadReceiptsDisabledAndInactiveApp() {
let context = MockChatLifecycleContext()
let coordinator = ChatLifecycleCoordinator(context: context)
let peerID = PeerID(str: "1122334455667788")
context.privateChats[peerID] = [makePrivateMessage(id: "in-1", senderPeerID: peerID)]
// Inactive app: clears unread via manager, emits no read receipts.
context.isAppActive = false
coordinator.markPrivateMessagesAsRead(from: peerID)
#expect(context.managerReadMarks == [peerID])
#expect(context.routedReadReceipts.isEmpty)
#expect(context.sentReadReceipts.isEmpty)
// Active app, read receipts disabled: still emits nothing.
context.isAppActive = true
context.sendReadReceiptsEnabled = false
coordinator.markPrivateMessagesAsRead(from: peerID)
#expect(context.routedReadReceipts.isEmpty)
#expect(context.sentReadReceipts.isEmpty)
// Re-enabled: emits once.
context.sendReadReceiptsEnabled = true
coordinator.markPrivateMessagesAsRead(from: peerID)
#expect(context.routedReadReceipts.map(\.messageID) == ["in-1"])
#expect(context.sentReadReceipts == ["in-1"])
}
@Test @MainActor
func markPrivateMessagesAsRead_geoDM_usesBoundGeohashAndNeverFallsThroughToBLE() {
let context = MockChatLifecycleContext()
let coordinator = ChatLifecycleCoordinator(context: context)
let convKey = PeerID(nostr_: "feedface00112233")
let recipientHex = "feedface00112233"
context.nostrKeyMapping[convKey] = recipientHex
context.privateChats[convKey] = [makePrivateMessage(id: "geo-1", senderPeerID: convKey)]
// Active channel is .mesh and no geohash bound yet: must NEVER fall through
// into the BLE/favorite router path.
context.activeChannel = .mesh
coordinator.markPrivateMessagesAsRead(from: convKey)
#expect(context.routedReadReceipts.isEmpty)
#expect(context.geoReadReceipts.isEmpty)
#expect(context.sentReadReceipts.isEmpty)
// Bound geohash succeeds even while activeChannel is .mesh, unless
// network activation disallows sending.
context.geoDMGeohashByPeerID[convKey] = "u4pruy"
context.canSendGeohashReadReceipt = false
coordinator.markPrivateMessagesAsRead(from: convKey)
#expect(context.geoReadReceipts.isEmpty)
#expect(context.sentReadReceipts.isEmpty)
context.canSendGeohashReadReceipt = true
coordinator.markPrivateMessagesAsRead(from: convKey)
#expect(context.geoReadReceipts.map(\.messageID) == ["geo-1"])
#expect(context.routedReadReceipts.isEmpty)
#expect(context.sentReadReceipts == ["geo-1"])
}
@Test @MainActor
func handleDidBecomeActive_delayedPassGuardsActiveStateAndSelection() {
let context = MockChatLifecycleContext()
let coordinator = ChatLifecycleCoordinator(context: context)
let peerA = PeerID(str: "1111111111111111")
let peerB = PeerID(str: "2222222222222222")
var deferredWork: [@MainActor () -> Void] = []
context.selectedPrivateChatPeer = peerA
context.deferScheduledWork = { deferredWork.append($0) }
coordinator.handleDidBecomeActive()
#expect(deferredWork.count == 1)
// Switching away before the delayed pass fires suppresses the stale pass.
context.selectedPrivateChatPeer = peerB
deferredWork.removeFirst()()
#expect(context.ownerLevelReadPasses.isEmpty)
// Backgrounding before the delayed pass fires also suppresses it.
context.selectedPrivateChatPeer = peerA
coordinator.handleDidBecomeActive()
context.isAppActive = false
deferredWork.removeFirst()()
#expect(context.ownerLevelReadPasses.isEmpty)
}
}
// MARK: - Screenshot Routing
@@ -16,6 +16,9 @@ private final class MockChatLiveVoiceContext: ChatLiveVoiceContext {
var nickname = "me"
var myPeerID = PeerID(str: "0102030405060708")
var selectedPrivateChatPeer: PeerID?
var isAppActive = true
var sendReadReceiptsEnabled = true
var routeReadReceiptResult = true
var isViewingPublicMeshTimeline = false
var blockedPeers: Set<PeerID> = []
@@ -52,6 +55,11 @@ private final class MockChatLiveVoiceContext: ChatLiveVoiceContext {
func markReadReceiptSent(_ messageID: String) -> Bool {
readReceiptMessageIDs.insert(messageID).inserted
}
@discardableResult
func routeReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) -> Bool {
sentReadReceipts.append((receipt, peerID))
return routeReadReceiptResult
}
func sendMeshReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) {
sentReadReceipts.append((receipt, peerID))
}
@@ -221,6 +229,55 @@ struct ChatLiveVoiceCoordinatorTests {
#expect(!coordinator.absorbFinalizedVoiceNote(note))
}
@Test func absorbDoesNotEmitReadReceiptWhenBackgroundedOrDisabled() throws {
let context = MockChatLiveVoiceContext()
let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false)
coordinator.liveVoiceEnabled = { true }
let burstID = makeBurstID(0xC1)
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([Data(repeating: 7, count: 50)]))), to: coordinator, from: peer)
send(try #require(VoiceBurstPacket(burstID: burstID, seq: 2, kind: .end(totalDataPackets: 1, durationMs: 64))), to: coordinator, from: peer)
// Chat is selected, but app is backgrounded/locked: must NOT emit READ.
context.selectedPrivateChatPeer = peer
context.isAppActive = false
let fileName = "voice_\(burstID.hexEncodedString()).m4a"
let note = BitchatMessage(
id: "stable-bg-voice",
sender: "alice",
content: "[voice] \(fileName)",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "me",
senderPeerID: peer
)
#expect(coordinator.absorbFinalizedVoiceNote(note))
#expect(context.sentReadReceipts.isEmpty)
#expect(!context.hasSentReadReceipt("stable-bg-voice"))
// Active app, but read receipts disabled: also must NOT emit READ.
let burstID2 = makeBurstID(0xC2)
send(try #require(VoiceBurstPacket(burstID: burstID2, seq: 1, kind: .frames([Data(repeating: 7, count: 50)]))), to: coordinator, from: peer)
send(try #require(VoiceBurstPacket(burstID: burstID2, seq: 2, kind: .end(totalDataPackets: 1, durationMs: 64))), to: coordinator, from: peer)
context.isAppActive = true
context.sendReadReceiptsEnabled = false
let note2 = BitchatMessage(
id: "stable-disabled-voice",
sender: "alice",
content: "[voice] voice_\(burstID2.hexEncodedString()).m4a",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "me",
senderPeerID: peer
)
#expect(coordinator.absorbFinalizedVoiceNote(note2))
#expect(context.sentReadReceipts.isEmpty)
#expect(!context.hasSentReadReceipt("stable-disabled-voice"))
}
@Test func absorbIgnoresUnrelatedVoiceNotes() throws {
let context = MockChatLiveVoiceContext()
let coordinator = ChatLiveVoiceCoordinator(context: context, sweepsOnInit: false)
@@ -61,7 +61,6 @@ private final class MockChatPeerIdentityContext: ChatPeerIdentityContext {
// Private chat session lifecycle
private(set) var consolidatedPeers: [PeerID] = []
private(set) var syncedReadReceiptPeers: [PeerID] = []
private(set) var begunChatSessions: [PeerID] = []
private(set) var markedReadPeers: [PeerID] = []
@@ -71,10 +70,6 @@ private final class MockChatPeerIdentityContext: ChatPeerIdentityContext {
return false
}
func syncReadReceiptsForSentMessages(for peerID: PeerID) {
syncedReadReceiptPeers.append(peerID)
}
func beginPrivateChatSession(with peerID: PeerID) {
begunChatSessions.append(peerID)
}
@@ -277,7 +272,6 @@ struct ChatPeerIdentityCoordinatorContextTests {
#expect(context.consolidatedPeers == [peerID])
// No Noise session yet -> handshake triggered.
#expect(context.triggeredHandshakes == [peerID])
#expect(context.syncedReadReceiptPeers == [peerID])
#expect(context.storedFingerprints.map(\.fingerprint) == ["fp-alice"])
#expect(context.selectedPrivateChatFingerprint == "fp-alice")
#expect(context.begunChatSessions == [peerID])
@@ -25,6 +25,7 @@ private final class MockChatPrivateConversationContext: ChatPrivateConversationC
var unreadPrivateMessages: Set<PeerID> = []
var selectedPrivateChatPeer: PeerID?
var isAppActive = true
var sendReadReceiptsEnabled = true
var nickname = "me"
var activeChannel: ChannelID = .mesh
var nostrKeyMapping: [PeerID: String] = [:]
@@ -168,6 +169,7 @@ private final class MockChatPrivateConversationContext: ChatPrivateConversationC
// Routing & acknowledgements
private(set) var routedPrivateMessages: [(content: String, peerID: PeerID, messageID: String)] = []
private(set) var meshReadReceipts: [(messageID: String, peerID: PeerID)] = []
var routeReadReceiptResult = true
private(set) var geoPrivateMessages: [(content: String, recipientHex: String, messageID: String)] = []
private(set) var geoDeliveryAcks: [(messageID: String, recipientHex: String)] = []
private(set) var geoReadReceipts: [(messageID: String, recipientHex: String)] = []
@@ -195,6 +197,12 @@ private final class MockChatPrivateConversationContext: ChatPrivateConversationC
return cleared
}
@discardableResult
func routeReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) -> Bool {
meshReadReceipts.append((receipt.originalMessageID, peerID))
return routeReadReceiptResult
}
func sendMeshReadReceipt(_ receipt: ReadReceipt, to peerID: PeerID) {
meshReadReceipts.append((receipt.originalMessageID, peerID))
}
@@ -366,8 +374,8 @@ struct ChatPrivateConversationCoordinatorContextTests {
let senderPubkey = "feedface00112233"
context.displayNamesByPubkey[senderPubkey] = "alice#1234"
context.privateChats[convKey] = [
makeIncomingMessage(id: "mine-1", sender: "me"),
makeIncomingMessage(id: "mine-2", sender: "me")
makeIncomingMessage(id: "mine-1", sender: "me", senderPeerID: context.myPeerID),
makeIncomingMessage(id: "mine-2", sender: "me", senderPeerID: context.myPeerID)
]
coordinator.handleDelivered(
@@ -405,8 +413,8 @@ struct ChatPrivateConversationCoordinatorContextTests {
context.displayNamesByPubkey[senderPubkey] = "alice"
context.selectedPrivateChatPeer = shortPeerID
context.privateChats[shortPeerID] = [
makeIncomingMessage(id: "mine-short-1", sender: "me"),
makeIncomingMessage(id: "mine-short-2", sender: "me")
makeIncomingMessage(id: "mine-short-1", sender: "me", senderPeerID: context.myPeerID),
makeIncomingMessage(id: "mine-short-2", sender: "me", senderPeerID: context.myPeerID)
]
context.queuedMessageIDsByPeerID[shortPeerID] = ["mine-short-1", "mine-short-2"]
@@ -435,7 +443,7 @@ struct ChatPrivateConversationCoordinatorContextTests {
let stablePeerID = PeerID(hexData: Data(repeating: 0xC1, count: 32))
let unrelatedPeerID = PeerID(str: "1111222233334444")
context.privateChats[unrelatedPeerID] = [
makeIncomingMessage(id: "collision", sender: "me")
makeIncomingMessage(id: "collision", sender: "me", senderPeerID: context.myPeerID)
]
context.queuedMessageIDsByPeerID[unrelatedPeerID] = ["collision"]
@@ -1131,6 +1139,88 @@ struct ChatPrivateConversationCoordinatorContextTests {
#expect(context.privateMessageNotifications.count == 2)
}
@Test @MainActor
func nostrReceipts_rejectBlockedSenderAndNonOutgoingMessagesAndPreferFavoriteNickname() async {
let context = MockChatPrivateConversationContext()
let coordinator = ChatPrivateConversationCoordinator(context: context)
let noiseKey = Data(repeating: 0xE1, count: 32)
let stablePeerID = PeerID(hexData: noiseKey)
let senderPubkey = "feedface00112233"
context.displayNamesByPubkey[senderPubkey] = "anon#2233"
context.favoriteRelationshipsByNoiseKey[noiseKey] = makeFavoriteRelationship(
noiseKey: noiseKey,
nickname: "Alice"
)
let outgoing = BitchatMessage(
id: "out-1",
sender: "me",
content: "hello",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "Alice",
senderPeerID: context.myPeerID,
deliveryStatus: .sent
)
let incoming = makeIncomingMessage(
id: "in-1",
sender: "Alice",
content: "reply",
senderPeerID: stablePeerID
)
context.privateChats[stablePeerID] = [outgoing, incoming]
// Blocked sender cannot mutate delivery/read status.
context.blockedNostrPubkeys = [senderPubkey]
coordinator.handleReadReceipt(
NoisePayload(type: .readReceipt, data: Data("out-1".utf8)),
senderPubkey: senderPubkey,
convKey: stablePeerID
)
#expect(context.privateChats[stablePeerID]?.first?.deliveryStatus == .sent)
// Unblocked sender cannot forge a read receipt against their own incoming message.
context.blockedNostrPubkeys = []
coordinator.handleReadReceipt(
NoisePayload(type: .readReceipt, data: Data("in-1".utf8)),
senderPubkey: senderPubkey,
convKey: stablePeerID
)
#expect(!isRead(context.privateChats[stablePeerID]?.last?.deliveryStatus, by: "Alice"))
#expect(!isRead(context.privateChats[stablePeerID]?.last?.deliveryStatus, by: "anon#2233"))
// Valid outgoing message uses favorite nickname ("Alice"), not "anon#2233".
coordinator.handleReadReceipt(
NoisePayload(type: .readReceipt, data: Data("out-1".utf8)),
senderPubkey: senderPubkey,
convKey: stablePeerID
)
#expect(isRead(context.privateChats[stablePeerID]?.first?.deliveryStatus, by: "Alice"))
}
@Test @MainActor
func handlePrivateMessage_sendReadReceiptsDisabledAndUnroutableMeshRetry() async {
let context = MockChatPrivateConversationContext()
let coordinator = ChatPrivateConversationCoordinator(context: context)
let peerID = PeerID(str: "0102030405060708")
context.selectedPrivateChatPeer = peerID
// Disabled read receipts: viewing suppresses unread/notification, sends no receipt.
context.sendReadReceiptsEnabled = false
coordinator.handlePrivateMessage(makeIncomingMessage(id: "pm-muted-rr", senderPeerID: peerID))
#expect(context.meshReadReceipts.isEmpty)
#expect(!context.sentReadReceipts.contains("pm-muted-rr"))
#expect(!context.unreadPrivateMessages.contains(peerID))
// Enabled read receipts but router reports unroutable (e.g. courier mail with peer offline):
// must not mark sent so a later read scan retries once a route returns.
context.sendReadReceiptsEnabled = true
context.routeReadReceiptResult = false
coordinator.handlePrivateMessage(makeIncomingMessage(id: "pm-unroutable-live", senderPeerID: peerID))
#expect(context.meshReadReceipts.map(\.messageID) == ["pm-unroutable-live"])
#expect(!context.sentReadReceipts.contains("pm-unroutable-live"))
}
@Test @MainActor
func handleFavoriteNotification_persistsAndAnnouncesTransitionsOnly() async throws {
let context = MockChatPrivateConversationContext()
@@ -186,6 +186,7 @@ private func makeMessage(
id: String,
sender: String = "alice",
content: String = "hello",
timestamp: Date = Date(),
isPrivate: Bool = false,
senderPeerID: PeerID? = nil
) -> BitchatMessage {
@@ -193,7 +194,7 @@ private func makeMessage(
id: id,
sender: sender,
content: content,
timestamp: Date(),
timestamp: timestamp,
isRelay: false,
isPrivate: isPrivate,
recipientNickname: isPrivate ? "me" : nil,
@@ -378,6 +379,8 @@ struct ChatTransportEventCoordinatorContextTests {
#expect(context.privateChats[peerID] == nil)
#expect(context.privateChats[stablePeerID]?.map(\.id) == ["m1", "mine"])
// Recent incoming receipt IDs must be captured BEFORE migration deletes the short-ID chat.
#expect(context.unmarkedReadReceiptBatches == [["m1"]])
// Sender IDs migrate to the stable peer ID, except our own.
#expect(context.privateChats[stablePeerID]?.first?.senderPeerID == stablePeerID)
#expect(context.privateChats[stablePeerID]?.last?.senderPeerID == context.myPeerID)
@@ -386,6 +389,23 @@ struct ChatTransportEventCoordinatorContextTests {
#expect(context.stablePeerIDCache[peerID] == stablePeerID)
}
@Test @MainActor
func didDisconnect_skipsHistoricalMessagesOutsideRetryWindow() {
let context = MockChatTransportEventContext()
let coordinator = ChatTransportEventCoordinator(context: context)
let peerID = PeerID(str: "1122334455667788")
let oldTimestamp = Date().addingTimeInterval(-(TransportConfig.bleReadReceiptDisconnectRetryWindowSeconds + 60))
context.privateChats[peerID] = [
makeMessage(id: "old-msg", timestamp: oldTimestamp, isPrivate: true, senderPeerID: peerID),
makeMessage(id: "recent-msg", timestamp: Date(), isPrivate: true, senderPeerID: peerID)
]
coordinator.didDisconnectFromPeerSynchronously(peerID)
#expect(context.unmarkedReadReceiptBatches == [["recent-msg"]])
}
@Test @MainActor
func noisePayloads_driveDeliveryStatusAcksAndVerification() {
let context = MockChatTransportEventContext()
@@ -424,6 +424,11 @@ struct ChatViewModelDeliveryStatusTests {
viewModel.cleanupOldReadReceipts()
#expect(viewModel.sentReadReceipts == ["keep-receipt"])
// Clearing all private chats must prune sentReadReceipts all the way to empty.
viewModel.conversations.clear(.directPeer(peerID))
viewModel.cleanupOldReadReceipts()
#expect(viewModel.sentReadReceipts.isEmpty)
}
// MARK: - Relaunch-Restored Outbox Tests
+129 -9
View File
@@ -1094,13 +1094,51 @@ struct ChatViewModelPrivateChatTests {
}
@Test @MainActor
func syncReadReceiptsForSentMessages_judgesMineBySenderIDNotNickname() async {
let (viewModel, transport) = makeTestableViewModel()
func startPrivateChat_sendsSingleReadReceiptForNamesakeAndNeverDuplicatesAcrossRestarts() async throws {
// Integration regression:
// 1. Opening a chat must emit exactly ONE read receipt (no duplicate from PrivateChatManager).
// 2. A namesake's delivered incoming message still gets a READ receipt; own messages do not.
// 3. Sent read receipts are sealed in EncryptedHistoryStore, never written in plaintext
// to UserDefaults, and reopening a restored chat sends ZERO duplicate receipts.
let suiteName = "read-receipt-integration-\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: suiteName))
defaults.removePersistentDomain(forName: suiteName)
defer { defaults.removePersistentDomain(forName: suiteName) }
// Seed legacy plaintext key to verify one-time scrub on startup.
defaults.set(try JSONEncoder().encode(["legacy-msg"]), forKey: "sentReadReceipts")
let historyURL = FileManager.default.temporaryDirectory
.appendingPathComponent("rr-history-\(UUID().uuidString).sealed")
defer { try? FileManager.default.removeItem(at: historyURL) }
let keychain = MockKeychain()
let historyStore = EncryptedHistoryStore(
keychain: keychain,
persistsToDisk: true,
fileURL: historyURL,
persistenceEnabledProvider: { true }
)
let transport = MockTransport()
let viewModel = ChatViewModel(
keychain: keychain,
idBridge: NostrIdentityBridge(keychain: MockKeychainHelper()),
identityManager: MockIdentityManager(keychain),
transport: transport,
readReceiptsDefaults: defaults,
encryptedHistoryStore: historyStore
)
// Legacy plaintext key must be scrubbed on startup.
#expect(defaults.object(forKey: "sentReadReceipts") == nil)
#expect(viewModel.hasSentReadReceipt("legacy-msg"))
viewModel.nickname = "alice"
let peerID = PeerID(str: "0011223344556677")
transport.connectedPeers.insert(peerID)
transport.reachablePeers.insert(peerID)
viewModel.seedPrivateChat([
// A namesake's file, delivered to me (BLEFileTransferHandler.incomingMessage):
// it still needs my READ receipt.
BitchatMessage(
id: "namesake-delivered",
sender: "alice",
@@ -1112,7 +1150,6 @@ struct ChatViewModelPrivateChatTests {
senderPeerID: peerID,
deliveryStatus: .delivered(to: "alice", at: Date())
),
// My own message from before a rename, already read.
BitchatMessage(
id: "mine-before-rename",
sender: "al",
@@ -1126,11 +1163,94 @@ struct ChatViewModelPrivateChatTests {
)
], for: peerID)
viewModel.syncReadReceiptsForSentMessages(for: peerID)
viewModel.startPrivateChat(with: peerID)
await Task.yield()
#expect(!viewModel.hasSentReadReceipt("namesake-delivered"))
#expect(!viewModel.privateChatManager.sentReadReceipts.contains("namesake-delivered"))
#expect(viewModel.hasSentReadReceipt("mine-before-rename"))
// Single owner: exactly one READ receipt for the namesake's incoming message,
// none for our own message, and own message ID never pollutes sentReadReceipts.
#expect(transport.sentReadReceipts.map(\.receipt.originalMessageID) == ["namesake-delivered"])
#expect(viewModel.hasSentReadReceipt("namesake-delivered"))
#expect(!viewModel.hasSentReadReceipt("mine-before-rename"))
// Flush encrypted history and confirm UserDefaults remains completely free of plaintext IDs.
viewModel.flushPersistedPrivateHistorySynchronously()
#expect(defaults.object(forKey: "sentReadReceipts") == nil)
// Simulate app relaunch with the same encrypted history file: restored chat
// must remember sentReadReceipts and send ZERO duplicate receipts when reopened.
let transport2 = MockTransport()
transport2.connectedPeers.insert(peerID)
transport2.reachablePeers.insert(peerID)
let historyStore2 = EncryptedHistoryStore(
keychain: keychain,
persistsToDisk: true,
fileURL: historyURL,
persistenceEnabledProvider: { true }
)
let viewModel2 = ChatViewModel(
keychain: keychain,
idBridge: NostrIdentityBridge(keychain: MockKeychainHelper()),
identityManager: MockIdentityManager(keychain),
transport: transport2,
readReceiptsDefaults: defaults,
encryptedHistoryStore: historyStore2
)
#expect(viewModel2.hasSentReadReceipt("namesake-delivered"))
viewModel2.startPrivateChat(with: peerID)
await Task.yield()
#expect(transport2.sentReadReceipts.isEmpty)
}
@Test @MainActor
func stealthMode_disablesReadReceiptsAndNeverPersistsToDisk() async throws {
let suiteName = "read-receipt-stealth-\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: suiteName))
defaults.removePersistentDomain(forName: suiteName)
defer { defaults.removePersistentDomain(forName: suiteName) }
PrivacyModeSettings.setMode(.stealth, in: defaults)
defaults.set(try JSONEncoder().encode(["stale-plaintext"]), forKey: "sentReadReceipts")
let transport = MockTransport()
let peerID = PeerID(str: "0011223344556688")
transport.connectedPeers.insert(peerID)
transport.reachablePeers.insert(peerID)
let keychain = MockKeychain()
let viewModel = ChatViewModel(
keychain: keychain,
idBridge: NostrIdentityBridge(keychain: MockKeychainHelper()),
identityManager: MockIdentityManager(keychain),
transport: transport,
readReceiptsDefaults: defaults
)
// Stealth mode scrubs legacy plaintext key and does NOT load it.
#expect(defaults.object(forKey: "sentReadReceipts") == nil)
#expect(!viewModel.hasSentReadReceipt("stale-plaintext"))
#expect(!viewModel.sendReadReceiptsEnabled)
viewModel.seedPrivateChat([
BitchatMessage(
id: "stealth-in-1",
sender: "Alice",
content: "secret",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "me",
senderPeerID: peerID
)
], for: peerID)
viewModel.markPrivateChatUnread(peerID)
viewModel.startPrivateChat(with: peerID)
await Task.yield()
// Unread clears locally, but no wire read receipt is emitted and nothing hits UserDefaults.
#expect(!viewModel.unreadPrivateMessages.contains(peerID))
#expect(transport.sentReadReceipts.isEmpty)
#expect(defaults.object(forKey: "sentReadReceipts") == nil)
}
}
@@ -84,4 +84,30 @@ struct BLENoiseSessionQueuesTests {
BLEPendingTypedPayload(payload: Data([0x01, 0xBB]), transferId: nil)
])
}
@Test
func controlPayloadsDeduplicateAndRespectPerPeerCapWhilePreservingMedia() {
let peerID = PeerID(str: "aaaaaaaaaaaaaaaa")
var queues = BLENoiseSessionQueues()
let readPayload = BLENoisePayloadFactory.readReceipt(originalMessageID: "dup-id")
// Identical control payloads deduplicate.
queues.appendTypedPayload(readPayload, for: peerID)
queues.appendTypedPayload(readPayload, for: peerID)
#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)
for index in 0..<(BLENoiseSessionQueues.maxTypedPayloadsPerPeer + 5) {
queues.appendTypedPayload(
BLENoisePayloadFactory.readReceipt(originalMessageID: "msg-\(index)"),
for: peerID
)
}
let drained = queues.takeTypedPayloads(for: peerID)
#expect(drained.count == BLENoiseSessionQueues.maxTypedPayloadsPerPeer)
#expect(drained.contains(where: { $0.transferId == "keep-media" }))
}
}
@@ -428,6 +428,26 @@ struct MessageRouterTests {
#expect(transport.sentReadReceipts.count == 1)
}
@Test @MainActor
func sendReadReceipt_prefersSecurelyDeliverableTransportOverStaleReachable() async {
let peerID = PeerID(str: "0000000000000003")
let staleBLE = MockTransport()
staleBLE.reachablePeers.insert(peerID)
staleBLE.securePeers = [] // e.g. 60s stale BLE retention window, no active session
let liveNostr = MockTransport()
liveNostr.reachablePeers.insert(peerID)
liveNostr.securePeers = [peerID] // relay connected and ready
let router = MessageRouter(transports: [staleBLE, liveNostr])
let receipt = ReadReceipt(originalMessageID: "m-prefer-live", readerID: staleBLE.myPeerID, readerNickname: "Me")
let routed = router.sendReadReceipt(receipt, to: peerID)
#expect(routed)
#expect(staleBLE.sentReadReceipts.isEmpty)
#expect(liveNostr.sentReadReceipts.map(\.receipt.originalMessageID) == ["m-prefer-live"])
}
@Test @MainActor
func sendFavoriteNotification_usesConnectedOrReachable() async {
let peerID = PeerID(str: "0000000000000004")
@@ -237,14 +237,64 @@ final class PanicWipeCoverageTests: XCTestCase {
XCTAssertTrue(store.load().isEmpty)
}
func test_privateChatManager_resetForPanic_clearsSentReadReceipts() {
let manager = PrivateChatManager()
manager.sentReadReceipts.insert("msg-1")
manager.sentReadReceipts.insert("msg-2")
func test_privacyModeSettings_resetForPanic_clearsSendReadReceiptsPreference() {
let suite = "PanicWipeReadReceipts-\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suite)!
defaults.removePersistentDomain(forName: suite)
defer { defaults.removePersistentDomain(forName: suite) }
manager.resetForPanic()
PrivacyModeSettings.setMode(.everyday, in: defaults)
PrivacyModeSettings.setSendReadReceipts(false, in: defaults)
XCTAssertFalse(PrivacyModeSettings.shouldSendReadReceipts(in: defaults))
XCTAssertTrue(manager.sentReadReceipts.isEmpty)
PrivacyModeSettings.resetForPanic(in: defaults, wasTorEnabled: false)
XCTAssertNil(defaults.object(forKey: PrivacyModeSettings.sendReadReceiptsKey))
XCTAssertTrue(PrivacyModeSettings.shouldSendReadReceipts(in: defaults))
// Stealth mode preserves read-receipts-off posture across panic wipe.
PrivacyModeSettings.setMode(.stealth, in: defaults)
XCTAssertFalse(PrivacyModeSettings.shouldSendReadReceipts(in: defaults))
PrivacyModeSettings.resetForPanic(in: defaults, wasTorEnabled: true)
XCTAssertFalse(PrivacyModeSettings.shouldSendReadReceipts(in: defaults))
}
func test_encryptedHistoryStore_wipe_clearsSealedReadReceipts() {
let fileURL = FileManager.default.temporaryDirectory
.appendingPathComponent("panic-history-receipts-\(UUID().uuidString).sealed")
defer { try? FileManager.default.removeItem(at: fileURL) }
let keychain = MockKeychain()
let historyStore = EncryptedHistoryStore(
keychain: keychain,
persistsToDisk: true,
fileURL: fileURL,
persistenceEnabledProvider: { true }
)
let conversations = ConversationStore()
let peerID = PeerID(str: "0102030405060708")
conversations.append(
BitchatMessage(
id: "msg-1",
sender: "Alice",
content: "Secret",
timestamp: Date(),
isRelay: false,
isPrivate: true,
senderPeerID: peerID
),
to: .directPeer(peerID)
)
historyStore.save(
from: conversations,
nostrKeyMapping: [:],
sentReadReceipts: ["msg-1"],
synchronous: true
)
XCTAssertEqual(historyStore.load()?.sentReadReceipts, ["msg-1"])
historyStore.wipe()
XCTAssertFalse(FileManager.default.fileExists(atPath: fileURL.path))
XCTAssertNil(historyStore.load())
}
func test_nearbyNotesCounter_resetForPanic_clearsRevealedAndReleasesManager() {
@@ -50,11 +50,12 @@ struct PrivateChatManagerTests {
}
@Test @MainActor
func markAsRead_sendsReadReceiptViaRouter() async {
func markAsRead_clearsUnreadWithoutSendingDuplicateReceipts() async {
// Read-receipt routing is owned solely by ChatLifecycleCoordinator;
// PrivateChatManager only clears the unread badge so opening a chat
// never emits duplicate receipts from two independent tracking sets.
let transport = MockTransport()
let router = MessageRouter(transports: [transport])
let (manager, store) = Self.makeManager(transport: transport)
manager.messageRouter = router
let peerID = PeerID(str: "00000000000000BB")
transport.reachablePeers.insert(peerID)
@@ -75,145 +76,11 @@ struct PrivateChatManagerTests {
store.markUnread(.directPeer(peerID))
manager.markAsRead(from: peerID)
try? await Task.sleep(nanoseconds: 100_000_000)
#expect(transport.sentReadReceipts.count == 1)
#expect(manager.sentReadReceipts.contains("pm-2"))
#expect(transport.sentReadReceipts.isEmpty)
#expect(!manager.unreadMessages.contains(peerID))
}
@Test @MainActor
func markAsRead_withoutRouterFallsBackToTransport() async {
let transport = MockTransport()
let (manager, store) = Self.makeManager(transport: transport)
let peerID = PeerID(str: "00000000000000CC")
store.append(
BitchatMessage(
id: "pm-fallback",
sender: "Peer",
content: "Hi",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "Me",
senderPeerID: peerID
),
to: .directPeer(peerID)
)
manager.markAsRead(from: peerID)
#expect(transport.sentReadReceipts.count == 1)
#expect(transport.sentReadReceipts.first?.receipt.originalMessageID == "pm-fallback")
}
@Test @MainActor
func markAsRead_calledTwiceSynchronously_routesOneReceiptPerMessage() async {
// Regression: opening a chat runs two read scans in the same
// synchronous MainActor stretch (beginPrivateChatSession and
// markPrivateMessagesAsRead). The receipt must be claimed before the
// routing task gets a chance to run, or both scans route a copy.
let transport = MockTransport()
let router = MessageRouter(transports: [transport])
let (manager, store) = Self.makeManager(transport: transport)
manager.messageRouter = router
let peerID = PeerID(str: "00000000000000DE")
transport.reachablePeers.insert(peerID)
store.append(
BitchatMessage(
id: "pm-double",
sender: "Peer",
content: "Hi",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "Me",
senderPeerID: peerID
),
to: .directPeer(peerID)
)
store.markUnread(.directPeer(peerID))
manager.markAsRead(from: peerID)
manager.markAsRead(from: peerID)
try? await Task.sleep(nanoseconds: 100_000_000)
#expect(transport.sentReadReceipts.count == 1)
#expect(manager.sentReadReceipts.contains("pm-double"))
}
@Test @MainActor
func markAsRead_failedRouteReleasesClaimForRetry() async {
// No reachable transport: the receipt is not sent, and the eager
// claim must be released so a later read scan retries.
let transport = MockTransport()
let router = MessageRouter(transports: [transport])
let (manager, store) = Self.makeManager(transport: transport)
manager.messageRouter = router
let peerID = PeerID(str: "00000000000000DF")
store.append(
BitchatMessage(
id: "pm-unroutable",
sender: "Peer",
content: "Hi",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "Me",
senderPeerID: peerID
),
to: .directPeer(peerID)
)
store.markUnread(.directPeer(peerID))
manager.markAsRead(from: peerID)
try? await Task.sleep(nanoseconds: 100_000_000)
#expect(transport.sentReadReceipts.isEmpty)
#expect(!manager.sentReadReceipts.contains("pm-unroutable"))
}
@Test @MainActor
func markAsRead_fullKeyChatIncludesShortSenderAndRetriesFailedRoute() async {
let transport = MockTransport()
let router = MessageRouter(transports: [transport])
let (manager, store) = Self.makeManager(transport: transport)
manager.messageRouter = router
let fullID = PeerID(hexData: Data(repeating: 0xCC, count: 32))
let shortID = fullID.toShort()
let otherID = PeerID(hexData: Data(repeating: 0xDD, count: 32)).toShort()
for (id, sender, relay) in [
("mesh", Optional(shortID), false), ("courier", Optional(fullID), false),
("other", Optional(otherID), false), ("self", Optional(transport.myPeerID), false),
("relay", Optional(shortID), true), ("missing", nil, false)
] {
store.append(BitchatMessage(id: id, sender: "bob", content: id,
timestamp: Date(), isRelay: relay, isPrivate: true, senderPeerID: sender),
to: .directPeer(fullID))
}
manager.startChat(with: fullID)
// The router runs in a queued main-actor task; wait for its failed claims to clear.
for _ in 0..<100 where !manager.sentReadReceipts.isEmpty { await Task.yield() }
#expect(manager.sentReadReceipts.isEmpty)
#expect(transport.sentReadReceipts.isEmpty)
transport.reachablePeers = [shortID, fullID]
manager.markAsRead(from: fullID)
manager.markAsRead(from: fullID)
for _ in 0..<100 where transport.sentReadReceipts.count < 2 { await Task.yield() }
#expect(Set(transport.sentReadReceipts.map { $0.receipt.originalMessageID }) == ["mesh", "courier"])
#expect(transport.sentReadReceipts.count == 2)
#expect(manager.sentReadReceipts == ["mesh", "courier"])
#expect(transport.sentReadReceipts.first { $0.receipt.originalMessageID == "mesh" }?.peerID == shortID)
#expect(manager.privateChats[fullID]?.first { $0.id == "mesh" }?.senderPeerID == shortID)
}
@Test @MainActor
func consolidateMessages_mergesStableNoiseKeyHistoryAndMarksUnread() async {
let transport = MockTransport()
@@ -369,12 +236,7 @@ struct PrivateChatManagerTests {
// ...and no thread with the namesake appears.
#expect(manager.privateChats[namesakePeerID] == nil)
// Opening the namesake's chat finds no sent rows of mine to sync
// receipts for, and sends none.
var externalReceipts = Set<String>()
manager.syncReadReceiptsForSentMessages(peerID: namesakePeerID, externalReceipts: &externalReceipts)
#expect(externalReceipts.isEmpty)
#expect(manager.sentReadReceipts.isEmpty)
// Opening the namesake's chat sends no read receipts.
manager.markAsRead(from: namesakePeerID)
#expect(transport.sentReadReceipts.isEmpty)
}
@@ -475,58 +337,6 @@ struct PrivateChatManagerTests {
#expect(manager.privateChats[namesakePeerID] == nil)
}
@Test @MainActor
func syncReadReceiptsForSentMessages_onlyCopiesDeliveredAndRead() async {
let transport = MockTransport()
let (manager, store) = Self.makeManager(transport: transport)
let peerID = PeerID(str: "00000000000000DD")
let seeded = [
BitchatMessage(
id: "sent-read",
sender: "Me",
content: "One",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "Peer",
senderPeerID: transport.myPeerID,
deliveryStatus: .read(by: "Peer", at: Date())
),
BitchatMessage(
id: "sent-delivered",
sender: "Me",
content: "Two",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "Peer",
senderPeerID: transport.myPeerID,
deliveryStatus: .delivered(to: "Peer", at: Date())
),
BitchatMessage(
id: "sent-failed",
sender: "Me",
content: "Three",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "Peer",
senderPeerID: transport.myPeerID,
deliveryStatus: .failed(reason: "nope")
)
]
for message in seeded {
store.append(message, to: .directPeer(peerID))
}
var externalReceipts = Set<String>()
manager.syncReadReceiptsForSentMessages(peerID: peerID, externalReceipts: &externalReceipts)
#expect(externalReceipts == Set(["sent-read", "sent-delivered"]))
#expect(manager.sentReadReceipts == Set(["sent-read", "sent-delivered"]))
}
/// The store replaces `sanitizeChat`: inserts keep chronological order,
/// duplicate IDs are rejected on append, and `upsertByID` replaces the
/// stored message with the latest copy in place.