Files
bitchat/bitchatTests/Services/PrivateChatManagerTests.swift
T
dd6b624cae Quality pass on the 1.7.0 batch: fix confirmed bugs, bump to 1.7.1 (#1418)
* Quality pass on the 1.7.0 batch: fix confirmed bugs, bump to 1.7.1

Post-merge review of PRs #1400–#1417 (push-to-talk, mesh bridging, DM
store-and-forward, empty-mesh liveliness, geo-notes). Fixes the confirmed,
well-scoped findings; deeper architectural/security items are tracked
separately.

- PTT hot-mic leak: releasing the mic during VoiceCaptureSession.start()'s
  150ms retry pause left the mic live and streaming for up to 120s, because
  cancel() no-op'd once `completed` was set. Bail after the sleep if the hold
  was released, and make cancel() always tear down a late-started capture.
- Bridge courier depositDrop reported success and burned the dedup slot before
  the drop was actually published (evicted/compose-fail = lying 📦 "carried"
  with no retry). Only consume publishedDropKeys on durable accept; add
  BoundedIDSet.remove() to release evicted/failed slots (uses the dead dedupKey).
- Blocked senders resurfaced via archived "heard here earlier" echoes, the one
  path that bypassed the live block filter — filter at seed time.
- A late optimistic .sent clobbered the router's .carried state; extend
  ConversationStore.shouldSkipStatusUpdate to a full precedence guard
  (sending < sent < carried < delivered < read).
- Read receipts were permanently burned when the router dropped them (marked
  sent then dropped). sendReadReceipt/routeReadReceipt now return Bool; only
  record as sent on a successful route, else retry on the next read scan.
- MessageRouter.cleanupExpiredMessages() had no production caller, so DMs to a
  peer that never reconnects sat on .sending until relaunch — run it in the
  120s bridge sweep.
- Sightings tally now rolls over at midnight while idle; wave notification
  action localized across all 29 locales; bridged anon#tag uses suffix(4) like
  everything else; makeThrowawayIdentity delegates to NostrIdentity.generate();
  .swiftlint.yml excludes .claude worktrees.
- Add regression tests: carried→sent no-downgrade, carried→delivered upgrade,
  evicted pending drop stays retryable.
- Bump MARKETING_VERSION to 1.7.1.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Fix CI: adjust delivery-status benchmark and drop now-dead addSystemMessage

The stricter no-downgrade guard (delivered/carried never regress to sent) broke
two things the earlier commit didn't catch locally (perf tests are skipped in
the default run, and Periphery runs only in CI):

- PerformanceBaselineTests delivery benchmarks alternated sent <-> delivered
  assuming both directions apply; the delivered -> sent half is now correctly
  skipped, so the pass measured 0 updates. Alternate two delivered timestamps
  instead — every update is real, no downgrade.
- Routing the geoDM "not in a location channel" error into the thread removed
  the only caller of ChatPrivateConversationContext.addSystemMessage, leaving
  it (and its mock) dead per Periphery. Drop the protocol requirement, the mock
  impl, and the now-vacuous systemMessages.isEmpty assertions (the invariant is
  compile-time enforced: the context can no longer emit a public system line).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Address review findings: read-receipt dedup, carried-vs-sending, block-time echo purge

- Read receipts: claim the receipt in sentReadReceipts synchronously
  before spawning the routing task (chat open runs two read scans in one
  MainActor stretch, so the async insert let every unread message route
  twice), and release the claim when the route fails so the
  retry-on-failed-route behavior is preserved.

- Delivery status: extend the no-downgrade guard so the `.sending`
  stamp a pre-handshake resend emits can no longer clobber
  carried/delivered/read (the 📦 indicator survived `.sent` but not
  `.sending`).

- Archived echoes: blocking a peer now purges their carried public
  messages from the gossip archive at block time (UnifiedPeerService
  and /block), while the fingerprint-to-peerID mapping is still known —
  the seed-time filter can't resolve offline non-favorite strangers and
  stays only as defense-in-depth. New Transport hook (default no-op) +
  GossipSyncManager.removePublicMessages with immediate persist.

- Bridge courier: an envelope that can't encode within the drop size
  caps fails identically on every attempt; consume the dedup slot so
  the 120s retry sweep stops re-running Noise sealing on it.

- MeshSightingsTracker: cache the day-key DateFormatter instead of
  building one per call.

Tests: double-markAsRead dedup + failed-route retry, carried→sending
no-downgrade matrix, block-time purge (manager + service wiring),
oversize-drop slot consumption.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Also skip the sent→sending downgrade in the delivery-status guard

Codex review follow-up: sendPrivateMessage without an established Noise
session emits `.sending` asynchronously, so it can land after the
message already reached `.sent` and visibly walk "Sent" back to
"Sending...". Treat `.sending` as weaker than `.sent` too — the status
was already truthful. `.failed` → `.sending` stays allowed so a retry
after a real failure remains visible.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Retain Codable properties in Periphery scan (same fix as #1421)

The noiseKey assign-only false positive fired persistently on this branch
(twice, including a rerun) despite the baselined USR. Byte-identical to the
fix on fix/announce-replay-link-steal so the branches merge cleanly in
either order.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 16:44:02 +02:00

348 lines
12 KiB
Swift

//
// PrivateChatManagerTests.swift
// bitchatTests
//
// Tests for PrivateChatManager read receipt and selection behavior.
// Message storage lives in the single-writer ConversationStore; the
// manager's privateChats/unreadMessages are derived views over it.
//
import Testing
import Foundation
import BitFoundation
@testable import bitchat
struct PrivateChatManagerTests {
@MainActor
private static func makeManager(transport: MockTransport) -> (PrivateChatManager, ConversationStore) {
let store = ConversationStore()
let manager = PrivateChatManager(meshService: transport, conversationStore: store)
return (manager, store)
}
@Test @MainActor
func startChat_setsSelectedAndClearsUnread() async {
let transport = MockTransport()
let (manager, store) = Self.makeManager(transport: transport)
let peerID = PeerID(str: "00000000000000AA")
store.append(
BitchatMessage(
id: "pm-1",
sender: "Peer",
content: "Hi",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "Me",
senderPeerID: peerID
),
to: .directPeer(peerID)
)
store.markUnread(.directPeer(peerID))
manager.startChat(with: peerID)
#expect(manager.selectedPeer == peerID)
#expect(!manager.unreadMessages.contains(peerID))
#expect(manager.privateChats[peerID] != nil)
}
@Test @MainActor
func markAsRead_sendsReadReceiptViaRouter() async {
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)
store.append(
BitchatMessage(
id: "pm-2",
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.count == 1)
#expect(manager.sentReadReceipts.contains("pm-2"))
#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 consolidateMessages_mergesStableNoiseKeyHistoryAndMarksUnread() async {
let transport = MockTransport()
let (manager, store) = Self.makeManager(transport: transport)
let identityManager = MockIdentityManager(MockKeychain())
let idBridge = NostrIdentityBridge(keychain: MockKeychainHelper())
let unifiedPeerService = UnifiedPeerService(meshService: transport, idBridge: idBridge, identityManager: identityManager)
manager.unifiedPeerService = unifiedPeerService
let peerID = PeerID(str: "0123456789abcdef")
let noiseKey = Data((0..<32).map(UInt8.init))
let stablePeerID = PeerID(hexData: noiseKey)
transport.updatePeerSnapshots([
TransportPeerSnapshot(
peerID: peerID,
nickname: "Alice",
isConnected: true,
noisePublicKey: noiseKey,
lastSeen: Date()
)
])
try? await Task.sleep(nanoseconds: 50_000_000)
store.append(
BitchatMessage(
id: "stable-msg",
sender: "Alice",
content: "Hello from stable",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "Me",
senderPeerID: stablePeerID
),
to: .directPeer(stablePeerID)
)
store.markUnread(.directPeer(stablePeerID))
let hadUnread = manager.consolidateMessages(for: peerID, peerNickname: "Alice", persistedReadReceipts: [])
#expect(hadUnread)
#expect(manager.privateChats[stablePeerID] == nil)
#expect(manager.privateChats[peerID]?.count == 1)
#expect(manager.privateChats[peerID]?.first?.senderPeerID == peerID)
#expect(manager.unreadMessages.contains(peerID))
}
@Test @MainActor
func consolidateMessages_movesTemporaryGeoDMHistoryByNickname() async {
let transport = MockTransport()
let (manager, store) = Self.makeManager(transport: transport)
let peerID = PeerID(str: "0011223344556677")
let tempPeerID = PeerID(nostr_: "0000000000000000000000000000000000000000000000000000000000000042")
store.append(
BitchatMessage(
id: "geo-msg",
sender: "Alice",
content: "Geo hello",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: "Me",
senderPeerID: tempPeerID
),
to: .directPeer(tempPeerID)
)
store.markUnread(.directPeer(tempPeerID))
let hadUnread = manager.consolidateMessages(for: peerID, peerNickname: "alice", persistedReadReceipts: [])
#expect(hadUnread)
#expect(manager.privateChats[tempPeerID] == nil)
#expect(manager.privateChats[peerID]?.count == 1)
#expect(manager.privateChats[peerID]?.first?.senderPeerID == peerID)
#expect(manager.unreadMessages.contains(peerID))
#expect(!manager.unreadMessages.contains(tempPeerID))
}
@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, nickname: "Me", 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.
@Test @MainActor
func store_keepsChronologicalOrderAndDedupsByID() async {
let transport = MockTransport()
let (manager, store) = Self.makeManager(transport: transport)
let peerID = PeerID(str: "00000000000000EE")
let base = Date(timeIntervalSince1970: 10)
func message(_ id: String, _ content: String, offset: TimeInterval) -> BitchatMessage {
BitchatMessage(
id: id,
sender: "Peer",
content: content,
timestamp: base.addingTimeInterval(offset),
isRelay: false,
isPrivate: true,
recipientNickname: "Me",
senderPeerID: peerID
)
}
#expect(store.append(message("same", "Older", offset: 10), to: .directPeer(peerID)))
// Out-of-order arrival is inserted in timestamp order.
#expect(store.append(message("first", "First", offset: 0), to: .directPeer(peerID)))
// Duplicate ID is rejected on append…
#expect(!store.append(message("same", "Newest", offset: 20), to: .directPeer(peerID)))
// …and replaced in place by upsert.
store.upsertByID(message("same", "Newest", offset: 20), in: .directPeer(peerID))
#expect(manager.privateChats[peerID]?.map(\.id) == ["first", "same"])
#expect(manager.privateChats[peerID]?.last?.content == "Newest")
}
}