mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-25 11:25:20 +00:00
* Consolidate duplicate BLE links after restore; suppress duplicate fragment streams; onChange coalescing
Field evidence (two-phone test after BLE state-restoration relaunches):
both phones held 2-3 simultaneous same-role connections to each other —
one side received every packet from three distinct centrals all bound to
the same peer — so every PTT voice frame arrived 3x, and a 41KB voice
file went out as TWO complete independent 89-fragment streams (different
assembly ids), both fully reassembled and the duplicate only dropped at
the very end by messageID dedup. 2-3x airtime/battery on all traffic
plus doubled reassembly memory.
Root causes and fixes:
- Duplicate links stayed unbound forever: announces (the only packet
that binds a link to a peer) went through the per-peer duplicate-link
collapse, so a peer's second/third link never received the announce it
needed to become bound — and unbound links pass the collapse untouched,
so every broadcast sprayed down all of them. Direct announces now
bypass the collapse and reach every live link (relayed announces keep
it); once bound, the existing collapse dedups all traffic.
- Same-role link retirement: a verified direct announce now consolidates
our central-role connections to that peer — keep the link the announce
arrived on (or the most recently bound one), cancel other connected
links bound to the same peer. One connection per role per peer is the
normal dual-role topology; only same-role duplicates are touched, only
links already announce-bound are retired (never pre-announce links),
at most one retirement per peer per rebind-cooldown window, and the
peer keeps a live link either way. Directness stays forgeable (TTL is
unsigned), so a replay could nominate the survivor — bounded by the
cooldown and by DM routing's existing canDeliverSecurely gate. A
rotation rebind now also cancels other stale links still bound to the
rotated-away ID, so the ghost identity retires promptly.
- Deterministic preferred-link collapse: when several bound links to one
peer are candidates, collapse now keeps the peer's most recently bound
link (the reverse-mapped one) instead of dictionary order; links
without a discovered characteristic are excluded from fanout (they
cannot be written to, and could silently eat a peer's collapsed copy).
links(to:) now reports all bound peripheral links, and removing one
duplicate no longer clobbers the reverse map of the survivor.
- Duplicate fragment streams: a transferId-less resend (gossip-sync
replay, spool) of file content already being fragmented out to a
covering audience is dropped at the outbound scheduler (broadcast
covers everyone; directed covers its recipient). App-initiated sends
carry an explicit transferId the progress UI tracks and always run.
A peer that asks after the stream completes still gets a resend.
- didUnsubscribeFrom no longer flaps a peer that is still live on other
links (the far side retiring its duplicate arrives as an unsubscribe);
didDisconnectPeripheral bookkeeping is skipped for self-retired links
by removing the store entry before cancelling.
Also: guard the DeliveryStatus onChange state write in TextMessageView/
MediaMessageView (unconditional per-row writes under a message storm
tripped SwiftUI's "tried to update multiple times per frame" warning).
The restore-path bgRemaining=∞ log was already fixed on main (#1425
review follow-up 07b5ac31: init-time seed + sampler-routed restore
captures); verified, no change needed.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Review fixes: multi-link disconnect guard, characteristic-aware retirement
Adversarial review of the duplicate-link PR (merge-with-nits):
- didDisconnectPeripheral gets the same multi-link guard as the
unsubscribe path: when a duplicate link drops naturally while the peer
stays live on another (dual-role central link, or a second bound link
during the post-restore consolidation window), peer-disconnect
bookkeeping (markDisconnected + disconnect notify) no longer runs — a
UI blip until the next announce re-marked the peer connected. The
reverse map was just repaired onto a connected survivor, so
directLinkState is the accurate probe. Scan restart and connect-slot
refill stay unguarded: they respond to the physical drop regardless of
remaining logical links. (No unit test: driving the CBCentralManager
delegate requires CBPeripheral instances, which cannot be constructed
in tests; the policy pieces backing the guard are covered.)
- Retirement is now characteristic-aware: the policy snapshot carries
characteristic presence, and keptPeripheralUUID selects anchors only
among writable links while any exist — consolidation must not keep a
link mid-service-rediscovery (didModifyServices cleared its
characteristic) and cancel the writable duplicate, stranding outbound
traffic on the central link until rediscovery finishes. When neither
anchor is writable but a writable duplicate exists, consolidation
defers to a later announce instead of guessing. The reverse-map
survivor repair in removePeripheral prefers writable links for the
same reason. Three new policy tests cover charless-vs-writable.
Deferred with code comments per review: central-side collapse keeps the
oldest subscription (no recency signal; remote consolidates within its
cooldown), and the extra preferred-bindings bleQueue hop in
sendOnAllLinks (fold into a combined snapshot if profiling flags it).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
161 lines
7.3 KiB
Swift
161 lines
7.3 KiB
Swift
//
|
|
// MediaMessageView.swift
|
|
// bitchat
|
|
//
|
|
// Created by Islam on 30/03/2026.
|
|
//
|
|
|
|
import SwiftUI
|
|
import BitFoundation
|
|
|
|
struct MediaMessageView: View {
|
|
@Environment(\.colorScheme) private var colorScheme
|
|
@Environment(\.appTheme) private var theme
|
|
@ThemedPalette private var palette
|
|
@EnvironmentObject private var conversationUIModel: ConversationUIModel
|
|
let message: BitchatMessage
|
|
let media: BitchatMessage.Media
|
|
/// Value snapshot of the message's mutable delivery status, captured at
|
|
/// construction (see `TextMessageView.deliveryStatus`): `BitchatMessage`
|
|
/// is a reference type mutated in place, and SwiftUI compares reference
|
|
/// fields by identity, so without the snapshot a status-only change
|
|
/// (send progress, delivered → read) would not re-render this row.
|
|
private let deliveryStatus: DeliveryStatus?
|
|
@State private var showDeliveryDetail = false
|
|
|
|
@Binding var imagePreviewURL: URL?
|
|
|
|
init(message: BitchatMessage, media: BitchatMessage.Media, imagePreviewURL: Binding<URL?>) {
|
|
self.message = message
|
|
self.media = media
|
|
self.deliveryStatus = message.deliveryStatus
|
|
self._imagePreviewURL = imagePreviewURL
|
|
}
|
|
|
|
var body: some View {
|
|
let isFromMe = conversationUIModel.isMediaMessageFromCurrentUser(message)
|
|
let state = mediaSendState(for: deliveryStatus, isFromMe: isFromMe)
|
|
let cancelAction: (() -> Void)? = state.canCancel ? { conversationUIModel.cancelMediaSend(messageID: message.id) } : nil
|
|
|
|
// Baseline alignment (via the header text inside the VStack) keeps the
|
|
// lock on the header line; a fixed top padding left its solid body
|
|
// hanging below the line's visual center.
|
|
HStack(alignment: .firstTextBaseline, spacing: 0) {
|
|
if message.isPrivate {
|
|
Image(systemName: "lock.fill")
|
|
.font(.bitchatSystem(size: 8))
|
|
.foregroundColor(Color.orange.opacity(0.75))
|
|
.padding(.trailing, 4)
|
|
.accessibilityHidden(true)
|
|
}
|
|
VStack(alignment: .leading, spacing: 2) {
|
|
HStack(alignment: .center, spacing: 4) {
|
|
Text(conversationUIModel.formatMessageHeader(message, colorScheme: colorScheme, theme: theme))
|
|
.fixedSize(horizontal: false, vertical: true)
|
|
.frame(maxWidth: .infinity, alignment: .leading)
|
|
// Delivery status indicator for private messages. Tappable:
|
|
// .help() tooltips only exist on macOS, so iOS users get the
|
|
// explanation as a caption under the row instead.
|
|
if message.isPrivate && conversationUIModel.isSentByCurrentUser(message),
|
|
let status = deliveryStatus {
|
|
Button {
|
|
showDeliveryDetail.toggle()
|
|
} label: {
|
|
DeliveryStatusView(status: status)
|
|
.padding(.leading, 4)
|
|
.contentShape(Rectangle())
|
|
}
|
|
.buttonStyle(.plain)
|
|
.accessibilityHint(
|
|
String(localized: "content.accessibility.delivery_detail_hint", comment: "Accessibility hint for the delivery status glyph explaining a tap reveals details")
|
|
)
|
|
}
|
|
}
|
|
|
|
// Failure reasons stay visible without a tap; other statuses
|
|
// reveal on demand.
|
|
if message.isPrivate && conversationUIModel.isSentByCurrentUser(message),
|
|
let status = deliveryStatus {
|
|
if case .failed = status {
|
|
Text(verbatim: status.bitchatDescription)
|
|
.bitchatFont(size: 11)
|
|
.foregroundColor(Color.red.opacity(0.9))
|
|
.fixedSize(horizontal: false, vertical: true)
|
|
} else if showDeliveryDetail {
|
|
Text(verbatim: status.bitchatDescription)
|
|
.bitchatFont(size: 11)
|
|
.foregroundColor(palette.secondary)
|
|
.fixedSize(horizontal: false, vertical: true)
|
|
}
|
|
}
|
|
|
|
Group {
|
|
switch media {
|
|
case .voice(let url):
|
|
VoiceNoteView(
|
|
url: url,
|
|
isSending: state.isSending,
|
|
sendProgress: state.progress,
|
|
isLive: conversationUIModel.isLiveVoiceMessage(message),
|
|
onCancel: cancelAction
|
|
)
|
|
case .image(let url):
|
|
BlockRevealImageView(
|
|
url: url,
|
|
revealProgress: state.progress,
|
|
isSending: state.isSending,
|
|
onCancel: cancelAction,
|
|
initiallyBlurred: !isFromMe,
|
|
onOpen: {
|
|
if !state.isSending {
|
|
imagePreviewURL = url
|
|
}
|
|
},
|
|
onDelete: !isFromMe ? { conversationUIModel.deleteMediaMessage(messageID: message.id) } : nil
|
|
)
|
|
.frame(maxWidth: 280)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
.padding(.vertical, 4)
|
|
// Collapse the revealed caption when the status advances (e.g.
|
|
// sending → sent → delivered) so a detail opened for one state
|
|
// doesn't linger and silently morph into another. Guarded write:
|
|
// under a message storm many rows change status within one frame,
|
|
// and an unconditional state write per change trips SwiftUI's
|
|
// "tried to update multiple times per frame" re-entrancy warning.
|
|
.onChange(of: deliveryStatus) { _ in
|
|
if showDeliveryDetail {
|
|
showDeliveryDetail = false
|
|
}
|
|
}
|
|
}
|
|
|
|
private func mediaSendState(for deliveryStatus: DeliveryStatus?, isFromMe: Bool) -> (isSending: Bool, progress: Double?, canCancel: Bool) {
|
|
// A received message is never in a send state: BitchatMessage defaults
|
|
// private messages to .sending, so an incoming message's status must
|
|
// not drive the reveal mask or disable the reveal tap.
|
|
guard isFromMe else { return (false, nil, false) }
|
|
var isSending = false
|
|
var progress: Double?
|
|
if let status = deliveryStatus {
|
|
switch status {
|
|
case .sending:
|
|
isSending = true
|
|
progress = 0
|
|
case .partiallyDelivered(let reached, let total):
|
|
if total > 0 {
|
|
isSending = true
|
|
progress = Double(reached) / Double(total)
|
|
}
|
|
case .sent, .carried, .read, .delivered, .failed:
|
|
break
|
|
}
|
|
}
|
|
let canCancel = isSending && conversationUIModel.isSentByCurrentUser(message)
|
|
let clamped = progress.map { max(0, min(1, $0)) }
|
|
return (isSending, isSending ? clamped : nil, canCancel)
|
|
}
|
|
}
|