Fix group chat background unread, dead-end status glyph, and retry timers (#1949)

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
This commit is contained in:
jackandjack authored and GitHub committed 2026-11-28 12:54:38 -10:00
1 parent cfbb7e0205
commit 2322f928b7
13 files changed
+190 -32

No files matched your search

+21
View File
@@ -157,6 +157,27 @@ final class ConversationUIModel: ObservableObject {
isSentByCurrentUser(message)
}
/// Whether an outgoing message row should render its delivery-status glyph.
/// Group chats are fire-and-flood with no per-member delivery/read ACKs in
/// v1, so a bare `.sent` checkmark would stay permanently stuck and mislead
/// readers; only actionable states (sending, progress, failure) surface there.
func showsDeliveryStatus(for message: BitchatMessage, status: DeliveryStatus) -> Bool {
guard message.isPrivate,
isSentByCurrentUser(message),
status != .notSentYet else {
return false
}
if chatViewModel.selectedPrivateChatPeer?.isGroup == true {
switch status {
case .sending, .partiallyDelivered, .failed:
return true
case .notSentYet, .sent, .carried, .delivered, .read:
return false
}
}
return true
}
/// My geochat sender ID in the location channel on screen (nil on #mesh),
/// memoized in `ownGeoChatSender`.
private func ownGeoChatPeerID() -> PeerID? {
@@ -15,6 +15,7 @@ protocol ChatGroupContext: AnyObject {
var nickname: String { get }
var myPeerID: PeerID { get }
var selectedPrivateChatPeer: PeerID? { get }
var isAppActive: Bool { get }
var groupStore: GroupStore { get }
/// Fingerprint of our own Noise static identity key.
@@ -663,7 +664,7 @@ final class ChatGroupCoordinator {
guard context.appendPrivateMessage(message, to: groupPeerID) else { return }
let isViewing = context.selectedPrivateChatPeer == groupPeerID
let isViewing = context.isAppActive && context.selectedPrivateChatPeer == groupPeerID
if !isViewing {
context.markPrivateChatUnread(groupPeerID)
let isRecent = Date().timeIntervalSince(messageDate) < 30
@@ -145,6 +145,9 @@ final class ChatLifecycleCoordinator {
markPrivateMessagesAsRead(from: peerID)
// Group chats have no wire read receipts; local unread was cleared above.
guard !peerID.isGroup else { return }
let context = self.context
context.scheduleOnMainAfter(TransportConfig.uiAnimationMediumSeconds) { [weak context] in
guard let context,
@@ -117,7 +117,8 @@ extension ChatViewModel: ChatLiveVoiceContext {
func appendGroupLiveVoiceMessage(_ message: BitchatMessage, to groupPeerID: PeerID) {
_ = appendPrivateMessage(message, to: groupPeerID)
if selectedPrivateChatPeer != groupPeerID {
let isViewing = isAppActive && selectedPrivateChatPeer == groupPeerID
if !isViewing {
markPrivateChatUnread(groupPeerID)
notifyPrivateMessage(from: message.sender, message: message.content, peerID: groupPeerID)
}
@@ -131,14 +131,8 @@ extension ChatViewModel: ChatVerificationContext {
messageRouter.retrySecurePrivateMessagesAfterAuthentication(for: peerIDAliases)
}
func retryPendingReadReceiptsIfViewing(peerIDAliases: [PeerID]) {
guard isAppActive, let selectedPeer = selectedPrivateChatPeer else { return }
let selectedShort = selectedPeer.toShort()
guard peerIDAliases.contains(where: { $0 == selectedPeer || $0.toShort() == selectedShort }) else {
return
}
markPrivateMessagesAsRead(from: selectedPeer)
}
// `retryPendingReadReceiptsIfViewing(peerIDAliases:)` is shared with
// `ChatTransportEventContext` and implemented in `ChatTransportEventCoordinator.swift`.
/// QR verification rides the mesh's Noise sessions only.
private var verifyTransport: MeshVerifying? { meshService as? MeshVerifying }
@@ -60,9 +60,7 @@ struct TextMessageView: View, Equatable {
// Heavy token scans run once per message, not once per render
let scan = message.contentScan
let parsedReply = MessageInteractionCodec.parseReply(from: message.content)
let showsDeliveryStatus = message.isPrivate
&& conversationUIModel.isSentByCurrentUser(message)
&& deliveryStatus != .notSentYet
let showsDeliveryStatus = conversationUIModel.showsDeliveryStatus(for: message, status: deliveryStatus)
if let parsedReply {
let quoteTint = conversationUIModel.colorForSenderName(
+1 -3
View File
@@ -35,9 +35,7 @@ struct MediaMessageView: View {
let isFromMe = conversationUIModel.isMediaMessageFromCurrentUser(message)
let state = mediaSendState(for: deliveryStatus, isFromMe: isFromMe)
let cancelAction: (() -> Void)? = state.canCancel ? { conversationUIModel.cancelMediaSend(messageID: message.id) } : nil
let showsDeliveryStatus = message.isPrivate
&& conversationUIModel.isSentByCurrentUser(message)
&& deliveryStatus != .notSentYet
let showsDeliveryStatus = conversationUIModel.showsDeliveryStatus(for: message, status: deliveryStatus)
// Baseline alignment (via the header text inside the VStack) keeps the
// lock on the header line; a fixed top padding left its solid body
+18 -14
View File
@@ -481,21 +481,25 @@ private struct MessageListContentView: View {
let privateConversationModel = appEnvironmentModels?.privateConversationModel {
privateConversationModel.markMessagesAsRead(from: peerID)
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)
// Group chats have no wire read receipts; local unread was
// already cleared synchronously above.
if !peerID.isGroup {
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)
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)
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)
}
}
}
}
@@ -24,6 +24,7 @@ private final class MockChatGroupContext: ChatGroupContext {
let nickname = "me"
let myPeerID: PeerID
var selectedPrivateChatPeer: PeerID?
var isAppActive = true
let groupStore = GroupStore(keychain: MockKeychain(), persistsToDisk: false)
private let identity: TestIdentity
@@ -55,21 +56,27 @@ private final class MockChatGroupContext: ChatGroupContext {
func broadcastGroupMessagePayload(_ payload: Data) {}
// Conversation intents
private(set) var unreadMarkedPeers: [PeerID] = []
private(set) var notifiedMessages: [(from: String, message: String, peerID: PeerID)] = []
private(set) var removedPrivateChats: [PeerID] = []
private(set) var endPrivateChatCount = 0
private(set) var systemMessages: [String] = []
@discardableResult
func appendPrivateMessage(_ message: BitchatMessage, to peerID: PeerID) -> Bool { true }
func markPrivateChatUnread(_ peerID: PeerID) {}
func markPrivateChatUnread(_ peerID: PeerID) { unreadMarkedPeers.append(peerID) }
func removePrivateChat(_ peerID: PeerID) { removedPrivateChats.append(peerID) }
func startPrivateChat(with peerID: PeerID) {}
func endPrivateChat() { endPrivateChatCount += 1 }
func addSystemMessage(_ content: String) { systemMessages.append(content) }
func addLocalPrivateSystemMessage(_ content: String, to peerID: PeerID) {}
func notifyPrivateMessage(from senderName: String, message: String, peerID: PeerID) {}
func notifyPrivateMessage(from senderName: String, message: String, peerID: PeerID) {
notifiedMessages.append((senderName, message, peerID))
}
func clearRecordedEffects() {
unreadMarkedPeers.removeAll()
notifiedMessages.removeAll()
removedPrivateChats.removeAll()
endPrivateChatCount = 0
systemMessages.removeAll()
@@ -336,4 +343,47 @@ struct ChatGroupCoordinatorContextTests {
#expect(context.groupStore.groups.isEmpty)
#expect(context.systemMessages.isEmpty)
}
@Test
func backgroundedOpenGroup_marksUnreadAndNotifies() throws {
let (context, coordinator, joined) = try makeJoinedGroup()
context.selectedPrivateChatPeer = joined.peerID
context.isAppActive = false
let payload = try GroupCrypto.sealMessage(
content: "ping while locked",
messageID: "grp-bg-1",
senderNickname: member.nickname,
senderSigningKey: member.member.signingKey,
timestampMs: UInt64(Date().timeIntervalSince1970 * 1000),
groupID: joined.groupID,
epoch: joined.epoch,
key: groupKey,
sign: member.sign
)
coordinator.handleGroupMessagePayload(payload, timestamp: Date())
#expect(context.unreadMarkedPeers == [joined.peerID])
#expect(context.notifiedMessages.count == 1)
#expect(context.notifiedMessages.first?.peerID == joined.peerID)
// When active and viewing the group, no unread badge or notification fires.
context.clearRecordedEffects()
context.isAppActive = true
let foregroundPayload = try GroupCrypto.sealMessage(
content: "ping while active",
messageID: "grp-fg-1",
senderNickname: member.nickname,
senderSigningKey: member.member.signingKey,
timestampMs: UInt64(Date().timeIntervalSince1970 * 1000),
groupID: joined.groupID,
epoch: joined.epoch,
key: groupKey,
sign: member.sign
)
coordinator.handleGroupMessagePayload(foregroundPayload, timestamp: Date())
#expect(context.unreadMarkedPeers.isEmpty)
#expect(context.notifiedMessages.isEmpty)
}
}
@@ -480,6 +480,21 @@ struct ChatLifecycleCoordinatorContextTests {
#expect(context.ownerLevelReadPasses.isEmpty)
}
@Test @MainActor
func handleDidBecomeActive_groupChatClearsUnreadWithoutSchedulingRetry() {
let context = MockChatLifecycleContext()
let coordinator = ChatLifecycleCoordinator(context: context)
let groupPeerID = PeerID(groupID: Data((0..<16).map(UInt8.init)))
context.selectedPrivateChatPeer = groupPeerID
coordinator.handleDidBecomeActive()
#expect(context.managerReadMarks == [groupPeerID])
#expect(context.scheduledDelays.isEmpty)
#expect(context.routedReadReceipts.isEmpty)
#expect(context.geoReadReceipts.isEmpty)
}
}
// MARK: - Screenshot Routing
+40
View File
@@ -1321,6 +1321,46 @@ struct ChatViewModelPrivateChatTests {
#expect(!blockedViewModel.networkActivationAllowed)
#expect(!blockedViewModel.canSendGeohashReadReceipt)
}
@Test @MainActor
func groupLiveVoiceMessage_marksUnreadWhenGroupOpenInBackground() {
let (viewModel, _) = makeTestableViewModel()
let groupPeerID = PeerID(groupID: Data((0..<16).map(UInt8.init)))
let senderPeerID = PeerID(str: "1122334455667788")
viewModel.startPrivateChat(with: groupPeerID)
viewModel.setAppActive(false)
let bgVoice = BitchatMessage(
id: "grp-voice-bg",
sender: "Alice",
content: "[voice] burst.aac",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: viewModel.nickname,
senderPeerID: senderPeerID
)
viewModel.appendGroupLiveVoiceMessage(bgVoice, to: groupPeerID)
#expect(viewModel.unreadPrivateMessages.contains(groupPeerID))
// Becoming active clears local unread; foreground voice burst stays read.
viewModel.handleDidBecomeActive()
#expect(!viewModel.unreadPrivateMessages.contains(groupPeerID))
let fgVoice = BitchatMessage(
id: "grp-voice-fg",
sender: "Alice",
content: "[voice] burst2.aac",
timestamp: Date(),
isRelay: false,
isPrivate: true,
recipientNickname: viewModel.nickname,
senderPeerID: senderPeerID
)
viewModel.appendGroupLiveVoiceMessage(fgVoice, to: groupPeerID)
#expect(!viewModel.unreadPrivateMessages.contains(groupPeerID))
}
}
// MARK: - Private Chat Selection Tests
@@ -467,4 +467,36 @@ struct ConversationUIModelTests {
let sent = try #require(Self.privateRow("[voice] \(note.lastPathComponent)", with: Self.peerID, of: viewModel))
#expect(uiModel.isSentByCurrentUser(sent))
}
@Test @MainActor
func showsDeliveryStatus_hidesDeadEndSentGlyphInGroupChatsOnly() {
let (viewModel, _) = makeChatViewModel(nickname: "alice")
let uiModel = makeUIModel(for: viewModel)
let ownMessage = row("alice", Self.myPeerID, content: "hello", isPrivate: true, deliveryStatus: .sent)
let incomingMessage = row("bob", Self.peerID, content: "hi", isPrivate: true, deliveryStatus: .sent)
// 1:1 DM shows receipt states (sent, delivered, read) as well as progress/failure.
viewModel.startPrivateChat(with: Self.peerID)
#expect(uiModel.showsDeliveryStatus(for: ownMessage, status: .sent))
#expect(uiModel.showsDeliveryStatus(for: ownMessage, status: .delivered(to: "bob", at: Date())))
#expect(uiModel.showsDeliveryStatus(for: ownMessage, status: .read(by: "bob", at: Date())))
#expect(uiModel.showsDeliveryStatus(for: ownMessage, status: .sending))
#expect(uiModel.showsDeliveryStatus(for: ownMessage, status: .failed(reason: "offline")))
#expect(!uiModel.showsDeliveryStatus(for: ownMessage, status: .notSentYet))
#expect(!uiModel.showsDeliveryStatus(for: incomingMessage, status: .sent))
// Group chat hides dead-end receipt glyphs (.sent/.delivered/.read) while
// still surfacing actionable sending/progress/failure states.
let groupPeerID = PeerID(groupID: Data((0..<16).map(UInt8.init)))
viewModel.startPrivateChat(with: groupPeerID)
#expect(!uiModel.showsDeliveryStatus(for: ownMessage, status: .sent))
#expect(!uiModel.showsDeliveryStatus(for: ownMessage, status: .delivered(to: "bob", at: Date())))
#expect(!uiModel.showsDeliveryStatus(for: ownMessage, status: .read(by: "bob", at: Date())))
#expect(!uiModel.showsDeliveryStatus(for: ownMessage, status: .carried))
#expect(!uiModel.showsDeliveryStatus(for: ownMessage, status: .notSentYet))
#expect(uiModel.showsDeliveryStatus(for: ownMessage, status: .sending))
#expect(uiModel.showsDeliveryStatus(for: ownMessage, status: .partiallyDelivered(reached: 1, total: 3)))
#expect(uiModel.showsDeliveryStatus(for: ownMessage, status: .failed(reason: "failed")))
#expect(!uiModel.showsDeliveryStatus(for: incomingMessage, status: .failed(reason: "failed")))
}
}
@@ -426,6 +426,7 @@ final class HybridGroupDeliveryTests: XCTestCase {
var nickname = "creator"
var myPeerID = PeerID(str: "1111111111111111")
var selectedPrivateChatPeer: PeerID?
var isAppActive = true
let groupStore: GroupStore
let mySigningPrivateKey = Curve25519.Signing.PrivateKey()