mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-26 15:25:20 +00:00
* Empty-mesh liveliness: nearby conversations, echoes, wave action, dead drops, radar The empty mesh timeline was a dead end: a grey zero and "nobody in range yet". This turns it into a live surface and gives the app pull when the mesh wakes up: - Nearest conversation: background geohash sampling now tracks actual chat messages (not just presence) per regional channel; the empty state surfaces the busiest nearby conversation with a preview, one tap to join (GeohashChatActivityTracker, fed from GeoPresenceTracker). - Echoes: the carried 6h store-and-forward window renders as dimmed "heard here earlier" rows at launch (new Transport collectArchivedPublicMessages -> GossipSyncManager snapshot, decoded with signature-derived nicknames; content-identity dedup guards against re-synced duplicates). - Wave: the "bitchatters nearby" notification gains a "wave" quick action that broadcasts a mesh 👋 straight from the notification, even backgrounded (first UNNotificationCategory in the app). - Dead drops: /drop pins a note to the current building geohash as a kind-1 location note with a 24h NIP-40 expiry; expired notes are now dropped client-side at ingest; the notices sheet shows "fades in Xh"; a "location notes" toggle plus location-permission controls live in app info (also fixes the duplicated Voice section). - Radar: an ambient sonar animation shows the radio scanning, with a privacy-safe daily tally ("N devices passed within range today" via salted per-day hashes) and a "notes left here" hint that opens the notices geo tab. All new user-facing strings ship in all 29 locales. 1403 tests green, including new suites for the activity tracker, sightings tally, and note expiry/drop publishing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Review round: app-info polish, urgent/expiry parity, centered radar, pin fill, Codex P2s - App info: LOCATION header uppercased like sibling sections; location notes and live voice descriptions shortened (29 locales); redundant "location access granted" line removed. - Notices parity: urgent + expiry controls now show on the geo tab too; the bridged Nostr note carries ["t","urgent"] and NIP-40 so relay-side readers see both; urgent parsed back from incoming notes. - Radar moved from the top of the empty state to the center of the chat area, below the help text (empty state fills the visible height). - Header pin fills whenever the scope has notices (was: only unseen), and Nostr-only nearby notes now light it too. - Codex P2 fixes: notification completion deferred until the wave action is handled (background suspension dropped the send); NIP-40 notes now prune on a timer when they expire while displayed; the location-notes kill switch retargets the nearby-notes counter immediately. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Hide macOS segmented picker's built-in label in notices composer (duplicate 'expires in') Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Geo notes: permanent (∞) expiry default, urgent stays mesh-only - Geo expiry picker gains ∞ as the default: a permanent note posts as a pure relay note (no NIP-40 tag, no mesh-board copy — a board copy must fade within days, contradicting the ∞ the user picked). 1/3/7d keep the board + bridged-note path with NIP-40. - The notes manager is now owned by the notices sheet (not the list) so the composer local-echoes ∞ notes into the list; it revives via refresh() after a tab-switch cancel, and its expiry-prune timer survives cancel (weak self, dies with the instance). - Urgent toggle returns to mesh-only per review — notes are ambient; the read-side urgent-tag parse stays so tagged notes still render. - macOS: hide the segmented picker's built-in label (duplicate "expires in"). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Clearing the mesh timeline dismisses echoes for good; tighter divider copy Triple-tap /clear emptied the timeline but the next launch re-seeded "heard here earlier" from the persisted archive. A MeshEchoSettings watermark now records the clear; only messages heard after it come back (the archive itself still carries everything for peers' sync). The echo dedup keys reset with it, and panic wipe drops the watermark. Divider copy tightened to "heard here earlier · last 6h" (29 locales). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Echoes visual polish: tinted history block, radar-captioned tally, ambient footer Device-test feedback on the echoes screen: - Archived echoes now sit on a subtle tinted background (secondary at 8%) in addition to the dim, so "heard here earlier" reads as one distinct block; the divider carries the echo ID prefix to join it. - "N devices passed within range today" moves out of the narration lines to sit centered under the radar as its caption. - When the timeline holds only echoes/system lines, a compact ambient footer (small radar + tally + live hints) renders below the history instead of the whole ambient layer vanishing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Notes strip persists above the mesh chat; leaner empty-state narration - The 📍 "notes left here" line was empty-state-only, so starting a conversation hid it. It is now a tappable strip pinned above the mesh timeline whenever unexpired notes exist at this place (opens the notices geo tab); the nearby-notes counter runs for the whole mesh timeline, not just the empty state. - Empty state narration drops "nobody in range yet..." (the radar and the sightings caption already say it) and the nearby-conversation hint moves below the help line instead of splitting the narration. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Radar means searching: hide the sweep once mesh peers are connected or reachable 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>
268 lines
9.3 KiB
Swift
268 lines
9.3 KiB
Swift
import BitFoundation
|
|
import BitLogger
|
|
import Foundation
|
|
|
|
/// The narrow surface `ChatPeerListCoordinator` needs from its owner.
|
|
///
|
|
/// Follows the `ChatDeliveryContext` exemplar: the coordinator depends on the
|
|
/// minimal context it actually uses instead of holding an `unowned` back-ref
|
|
/// to the whole `ChatViewModel`. This keeps the coordinator independently
|
|
/// testable (see `ChatPeerListCoordinatorContextTests`) and makes its true
|
|
/// dependencies explicit.
|
|
@MainActor
|
|
protocol ChatPeerListContext: AnyObject {
|
|
// MARK: Connection & chat state
|
|
var isConnected: Bool { get set }
|
|
/// A single private chat's timeline (store-direct lookup on
|
|
/// `ChatViewModel`; no `privateChats` dictionary build).
|
|
func privateMessages(for peerID: PeerID) -> [BitchatMessage]
|
|
var unreadPrivateMessages: Set<PeerID> { get }
|
|
/// Clears the peer's unread flag (single-writer store intent).
|
|
func markPrivateChatRead(_ peerID: PeerID)
|
|
var hasTrackedPrivateChatSelection: Bool { get }
|
|
func updatePrivateChatPeerIfNeeded()
|
|
func cleanupOldReadReceipts()
|
|
|
|
// MARK: Peers & sessions
|
|
var unifiedPeers: [BitchatPeer] { get }
|
|
func isPeerConnected(_ peerID: PeerID) -> Bool
|
|
func isPeerReachable(_ peerID: PeerID) -> Bool
|
|
/// Number of mesh peers currently connected or reachable, from the
|
|
/// transport's live peer snapshots.
|
|
func activeMeshPeerCount() -> Int
|
|
func registerEphemeralSession(peerID: PeerID)
|
|
func updateEncryptionStatusForPeers()
|
|
|
|
// MARK: Notifications
|
|
/// Posts the "bitchatters nearby" local notification.
|
|
func notifyNetworkAvailable(peerCount: Int)
|
|
|
|
/// Records peers seen within range for the daily ambient sightings tally.
|
|
func recordMeshSightings(peerIDs: [PeerID])
|
|
}
|
|
|
|
extension ChatViewModel: ChatPeerListContext {
|
|
// `isConnected`, `privateMessages(for:)`, `unreadPrivateMessages`,
|
|
// `hasTrackedPrivateChatSelection`, `updatePrivateChatPeerIfNeeded()`,
|
|
// `cleanupOldReadReceipts()`, `unifiedPeers`, `isPeerConnected(_:)`,
|
|
// `isPeerReachable(_:)`, `registerEphemeralSession(peerID:)`, and
|
|
// `updateEncryptionStatusForPeers()` are shared requirements with the
|
|
// other contexts or satisfied by existing `ChatViewModel` members. The
|
|
// member below flattens the nested transport access into an intent-named
|
|
// call.
|
|
|
|
func activeMeshPeerCount() -> Int {
|
|
meshService
|
|
.currentPeerSnapshots()
|
|
.filter { snapshot in
|
|
snapshot.isConnected || meshService.isPeerReachable(snapshot.peerID)
|
|
}
|
|
.count
|
|
}
|
|
|
|
func notifyNetworkAvailable(peerCount: Int) {
|
|
NotificationService.shared.sendNetworkAvailableNotification(peerCount: peerCount)
|
|
}
|
|
|
|
func recordMeshSightings(peerIDs: [PeerID]) {
|
|
for peerID in peerIDs {
|
|
MeshSightingsTracker.shared.recordSighting(peerID: peerID)
|
|
}
|
|
}
|
|
}
|
|
|
|
final class ChatPeerListCoordinator: @unchecked Sendable {
|
|
private unowned let context: any ChatPeerListContext
|
|
private var recentlySeenPeers: Set<PeerID> = []
|
|
// The "bitchatters nearby" notification only fires on the transition from
|
|
// an empty mesh to a populated one — joining peers while already meshed
|
|
// are visible in the app and must not notify. Set back to true only after
|
|
// a confirmed-empty reset, so brief link flaps stay silent.
|
|
private var meshWasEmpty = true
|
|
private var lastNetworkNotificationTime = Date.distantPast
|
|
private var networkResetTimer: Timer?
|
|
private var networkEmptyTimer: Timer?
|
|
private let networkResetGraceSeconds = TransportConfig.networkResetGraceSeconds
|
|
private let notificationCooldownSeconds: TimeInterval
|
|
|
|
init(
|
|
context: any ChatPeerListContext,
|
|
notificationCooldownSeconds: TimeInterval = TransportConfig.networkNotificationCooldownSeconds
|
|
) {
|
|
self.context = context
|
|
self.notificationCooldownSeconds = notificationCooldownSeconds
|
|
}
|
|
|
|
deinit {
|
|
networkResetTimer?.invalidate()
|
|
networkEmptyTimer?.invalidate()
|
|
}
|
|
|
|
func didUpdatePeerList(_ peers: [PeerID]) {
|
|
Task { @MainActor [weak self] in
|
|
self?.handlePeerListUpdate(peers)
|
|
}
|
|
}
|
|
}
|
|
|
|
private extension ChatPeerListCoordinator {
|
|
@MainActor
|
|
func handlePeerListUpdate(_ peers: [PeerID]) {
|
|
context.isConnected = !peers.isEmpty
|
|
cleanupStaleUnreadPeerIDs()
|
|
|
|
let meshPeers = peers.filter { peerID in
|
|
context.isPeerConnected(peerID) || context.isPeerReachable(peerID)
|
|
}
|
|
|
|
handleNetworkAvailability(meshPeers)
|
|
|
|
for peerID in peers {
|
|
context.registerEphemeralSession(peerID: peerID)
|
|
}
|
|
|
|
context.updateEncryptionStatusForPeers()
|
|
|
|
if context.hasTrackedPrivateChatSelection {
|
|
context.updatePrivateChatPeerIfNeeded()
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
func handleNetworkAvailability(_ meshPeers: [PeerID]) {
|
|
let meshPeerSet = Set(meshPeers)
|
|
|
|
if meshPeerSet.isEmpty {
|
|
scheduleNetworkEmptyTimer()
|
|
return
|
|
}
|
|
|
|
invalidateNetworkEmptyTimer()
|
|
context.recordMeshSightings(peerIDs: meshPeers)
|
|
|
|
let newPeers = meshPeerSet.subtracting(recentlySeenPeers)
|
|
// Record every sighted peer even when no notification fires. A peer
|
|
// first seen during the cooldown (or while already meshed) must not
|
|
// still count as "new" at some later peer-list event — that re-fired
|
|
// the notification while devices sat idle and connected.
|
|
recentlySeenPeers.formUnion(meshPeerSet)
|
|
|
|
let cameFromEmpty = meshWasEmpty
|
|
meshWasEmpty = false
|
|
|
|
guard cameFromEmpty, !newPeers.isEmpty else { return }
|
|
|
|
if Date().timeIntervalSince(lastNetworkNotificationTime) >= notificationCooldownSeconds {
|
|
lastNetworkNotificationTime = Date()
|
|
context.notifyNetworkAvailable(peerCount: meshPeers.count)
|
|
SecureLogger.info(
|
|
"👥 Sent bitchatters nearby notification for \(meshPeers.count) mesh peers (new: \(newPeers.count))",
|
|
category: .session
|
|
)
|
|
}
|
|
|
|
scheduleNetworkResetTimer()
|
|
}
|
|
|
|
@MainActor
|
|
func cleanupStaleUnreadPeerIDs() {
|
|
let currentPeerIDs = Set(context.unifiedPeers.map(\.peerID))
|
|
let staleIDs = context.unreadPrivateMessages.subtracting(currentPeerIDs)
|
|
|
|
guard !staleIDs.isEmpty else {
|
|
context.cleanupOldReadReceipts()
|
|
return
|
|
}
|
|
|
|
var idsToRemove: [PeerID] = []
|
|
|
|
for staleID in staleIDs {
|
|
if staleID.isGeoDM, !context.privateMessages(for: staleID).isEmpty {
|
|
continue
|
|
}
|
|
|
|
if staleID.isNoiseKeyHex, !context.privateMessages(for: staleID).isEmpty {
|
|
continue
|
|
}
|
|
|
|
idsToRemove.append(staleID)
|
|
context.markPrivateChatRead(staleID)
|
|
}
|
|
|
|
if !idsToRemove.isEmpty {
|
|
SecureLogger.debug("🧹 Cleaned up \(idsToRemove.count) stale unread peer IDs", category: .session)
|
|
}
|
|
|
|
context.cleanupOldReadReceipts()
|
|
}
|
|
|
|
@MainActor
|
|
func scheduleNetworkResetTimer() {
|
|
networkResetTimer?.invalidate()
|
|
networkResetTimer = Timer.scheduledTimer(withTimeInterval: networkResetGraceSeconds, repeats: false) { [weak self] _ in
|
|
MainActor.assumeIsolated { [weak self] in
|
|
self?.handleNetworkResetTimerFired()
|
|
}
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
func handleNetworkResetTimerFired() {
|
|
let activeMeshPeerCount = context.activeMeshPeerCount()
|
|
|
|
if activeMeshPeerCount == 0 {
|
|
recentlySeenPeers.removeAll()
|
|
meshWasEmpty = true
|
|
SecureLogger.debug("⏱️ Network notification window reset after quiet period", category: .session)
|
|
} else {
|
|
SecureLogger.debug(
|
|
"⏱️ Skipped network notification reset; still seeing \(activeMeshPeerCount) mesh peers",
|
|
category: .session
|
|
)
|
|
}
|
|
|
|
networkResetTimer = nil
|
|
}
|
|
|
|
@MainActor
|
|
func scheduleNetworkEmptyTimer() {
|
|
guard networkEmptyTimer == nil else { return }
|
|
|
|
networkEmptyTimer = Timer.scheduledTimer(
|
|
withTimeInterval: TransportConfig.uiMeshEmptyConfirmationSeconds,
|
|
repeats: false
|
|
) { [weak self] _ in
|
|
MainActor.assumeIsolated { [weak self] in
|
|
self?.handleNetworkEmptyTimerFired()
|
|
}
|
|
}
|
|
|
|
SecureLogger.debug("⏳ Mesh empty — waiting before resetting notification state", category: .session)
|
|
}
|
|
|
|
@MainActor
|
|
func invalidateNetworkEmptyTimer() {
|
|
guard networkEmptyTimer != nil else { return }
|
|
networkEmptyTimer?.invalidate()
|
|
networkEmptyTimer = nil
|
|
}
|
|
|
|
@MainActor
|
|
func handleNetworkEmptyTimerFired() {
|
|
let activeMeshPeerCount = context.activeMeshPeerCount()
|
|
|
|
if activeMeshPeerCount == 0 {
|
|
recentlySeenPeers.removeAll()
|
|
meshWasEmpty = true
|
|
SecureLogger.debug("⏳ Mesh empty — notification state reset after confirmation", category: .session)
|
|
} else {
|
|
SecureLogger.debug(
|
|
"⏳ Mesh empty timer cancelled; \(activeMeshPeerCount) mesh peers detected again",
|
|
category: .session
|
|
)
|
|
}
|
|
|
|
networkEmptyTimer = nil
|
|
}
|
|
}
|