diff --git a/bitchat/App/ConversationUIModel.swift b/bitchat/App/ConversationUIModel.swift index 59fcc9e2..b929f222 100644 --- a/bitchat/App/ConversationUIModel.swift +++ b/bitchat/App/ConversationUIModel.swift @@ -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? { diff --git a/bitchat/ViewModels/ChatGroupCoordinator.swift b/bitchat/ViewModels/ChatGroupCoordinator.swift index ef35a303..d4c10b48 100644 --- a/bitchat/ViewModels/ChatGroupCoordinator.swift +++ b/bitchat/ViewModels/ChatGroupCoordinator.swift @@ -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 diff --git a/bitchat/ViewModels/ChatLifecycleCoordinator.swift b/bitchat/ViewModels/ChatLifecycleCoordinator.swift index d101b260..c37db5f8 100644 --- a/bitchat/ViewModels/ChatLifecycleCoordinator.swift +++ b/bitchat/ViewModels/ChatLifecycleCoordinator.swift @@ -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, diff --git a/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift b/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift index 80dc86c1..31e6fdd8 100644 --- a/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift +++ b/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift @@ -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) } diff --git a/bitchat/ViewModels/ChatVerificationCoordinator.swift b/bitchat/ViewModels/ChatVerificationCoordinator.swift index 2dd6a5a6..702bb669 100644 --- a/bitchat/ViewModels/ChatVerificationCoordinator.swift +++ b/bitchat/ViewModels/ChatVerificationCoordinator.swift @@ -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 } diff --git a/bitchat/Views/Components/TextMessageView.swift b/bitchat/Views/Components/TextMessageView.swift index 292e7a20..e289808a 100644 --- a/bitchat/Views/Components/TextMessageView.swift +++ b/bitchat/Views/Components/TextMessageView.swift @@ -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( diff --git a/bitchat/Views/Media/MediaMessageView.swift b/bitchat/Views/Media/MediaMessageView.swift index 05dc0ce0..063b935a 100644 --- a/bitchat/Views/Media/MediaMessageView.swift +++ b/bitchat/Views/Media/MediaMessageView.swift @@ -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 diff --git a/bitchat/Views/MessageListView.swift b/bitchat/Views/MessageListView.swift index 6c85b994..3ece723d 100644 --- a/bitchat/Views/MessageListView.swift +++ b/bitchat/Views/MessageListView.swift @@ -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) + } } } } diff --git a/bitchatTests/ChatGroupCoordinatorContextTests.swift b/bitchatTests/ChatGroupCoordinatorContextTests.swift index 84f6fe6e..309bb47a 100644 --- a/bitchatTests/ChatGroupCoordinatorContextTests.swift +++ b/bitchatTests/ChatGroupCoordinatorContextTests.swift @@ -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) + } } diff --git a/bitchatTests/ChatLifecycleCoordinatorContextTests.swift b/bitchatTests/ChatLifecycleCoordinatorContextTests.swift index fcaa73ce..aacfa0a2 100644 --- a/bitchatTests/ChatLifecycleCoordinatorContextTests.swift +++ b/bitchatTests/ChatLifecycleCoordinatorContextTests.swift @@ -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 diff --git a/bitchatTests/ChatViewModelTests.swift b/bitchatTests/ChatViewModelTests.swift index 35df5285..f8b2d088 100644 --- a/bitchatTests/ChatViewModelTests.swift +++ b/bitchatTests/ChatViewModelTests.swift @@ -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 diff --git a/bitchatTests/ConversationUIModelTests.swift b/bitchatTests/ConversationUIModelTests.swift index a4f90e6c..36e58c01 100644 --- a/bitchatTests/ConversationUIModelTests.swift +++ b/bitchatTests/ConversationUIModelTests.swift @@ -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"))) + } } diff --git a/bitchatTests/Services/Phase1FeaturesTests.swift b/bitchatTests/Services/Phase1FeaturesTests.swift index c033da4f..af82f160 100644 --- a/bitchatTests/Services/Phase1FeaturesTests.swift +++ b/bitchatTests/Services/Phase1FeaturesTests.swift @@ -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()