Use asynchronous waits for panic metadata cleanup

Processed-event deletion and gossip retirement now use asynchronous
waits. The controller still waits for their results before reporting
completion, without blocking the main actor on those two queues.

Closed admission and established recovery intent before yielding.
Cleared buffered public messages, discarded pending geohash sends and
bound relay callbacks to the panic generation at registration. Completed
deferred service wiring after a successful startup-recovery retry.
This commit is contained in:
heyaim 2026-11-03 20:21:03 -06:00
parent 749f90653f
commit 59e607cf78
22 changed files with 735 additions and 160 deletions

View File

@ -27,6 +27,8 @@ final class AppChromeModel: ObservableObject {
/// that did not commit must be visible, not just logged — the person who
/// triggered it needs to know data may remain on the device.
@Published private(set) var panicWipeBlocked = false
@Published private(set) var panicInProgress = false
private(set) var panicTask: Task<Void, Never>?
private let chatViewModel: ChatViewModel
private let onPanicWipe: () -> Void
@ -128,6 +130,8 @@ final class AppChromeModel: ObservableObject {
}
func panicClearAllData() {
guard !panicInProgress else { return }
panicInProgress = true
// A wipe invalidates everything on screen, and its outcome must be
// visible: the success message and the failed-wipe banner both live
// on the root timeline, so a sheet left up (the App Info danger-zone
@ -140,7 +144,11 @@ final class AppChromeModel: ObservableObject {
prepareForPanic?()
onPanicWipe()
chatViewModel.panicClearAllData()
let cleanup = chatViewModel.beginPanicClearAllData()
panicTask = Task { @MainActor [self] in
_ = await cleanup?.value
panicInProgress = chatViewModel.isPanicResetting
}
}
private func bind(privateInboxModel: PrivateInboxModel) {
@ -175,6 +183,9 @@ final class AppChromeModel: ObservableObject {
.receive(on: DispatchQueue.main)
.assign(to: &$torBlocked)
chatViewModel.$isPanicResetting
.assign(to: &$panicInProgress)
chatViewModel.$panicRecoveryBlocked
.receive(on: DispatchQueue.main)
.assign(to: &$panicWipeBlocked)

View File

@ -32,6 +32,7 @@ final class AppRuntime: ObservableObject {
private let idBridge: NostrIdentityBridge
private var cancellables = Set<AnyCancellable>()
private var started = false
private var startRequested = false
private var lastNostrRelayConnectedState = false
private var didHandleInitialNostrConnection = false
@ -127,6 +128,7 @@ final class AppRuntime: ObservableObject {
}
func start() {
startRequested = true
guard chatViewModel.networkActivationAllowed else { return }
guard !started else {
checkForSharedContent()
@ -297,6 +299,16 @@ final class AppRuntime: ObservableObject {
private extension AppRuntime {
func bindRuntimeObservers() {
chatViewModel.$panicRecoveryBlocked
.removeDuplicates()
.dropFirst()
.receive(on: DispatchQueue.main)
.sink { [weak self] blocked in
guard !blocked, let self, self.startRequested else { return }
self.start()
}
.store(in: &cancellables)
NostrRelayManager.shared.$isConnected
.receive(on: DispatchQueue.main)
.sink { [weak self] isConnected in

View File

@ -742,6 +742,28 @@ final class BLEService: NSObject {
clearEmergencySessionState()
}
#if DEBUG
func _test_replaceGossipManager(_ manager: GossipSyncManager) {
gossipSyncManager?.stop()
gossipSyncManager = manager
}
#endif
/// Close admission and stop radio activity before yielding for gossip retirement.
@MainActor
func beginPanicReset() -> Task<Void, Never> {
setPanicSuspended(true)
let retiringGossip = gossipSyncManager
gossipSyncManager = nil
noisePacketHandler.resetForPanic()
stopServicesImmediatelyForPanic()
return Task { @MainActor [self] in
await retiringGossip?.stopForPanicAsync()
onEngine { noisePacketHandler.resetForPanic() }
clearEmergencySessionState()
}
}
/// Reopen the radio only after media deletion and recovery-marker commit.
func completePanicReset(restartServices: Bool) {
// The media wipe ran on the recovery operations' own file store; this
@ -1040,7 +1062,7 @@ final class BLEService: NSObject {
/// Panic cannot spend its security boundary sending a signed LEAVE or
/// pumping the main run loop. Close the radio and timers immediately;
/// the identity/session cleanup follows synchronously.
/// the caller completes the remaining identity/session cleanup.
private func stopServicesImmediatelyForPanic() {
bleQueue.sync {
pendingNotifications.removeAll()

View File

@ -21,12 +21,22 @@ protocol BluetoothStateReporting: AnyObject {
protocol PanicResettingTransport: AnyObject {
/// Quiesces the radio and drains in-flight work ahead of a panic wipe.
func suspendForPanicReset()
@MainActor
func beginPanicReset() -> Task<Void, Never>
/// Finishes a panic wipe, optionally restarting services.
func completePanicReset(restartServices: Bool)
/// Rotates the transport identity as part of a panic reset.
func resetIdentityForPanic(currentNickname: String, restartServices: Bool)
}
extension PanicResettingTransport {
@MainActor
func beginPanicReset() -> Task<Void, Never> {
suspendForPanicReset()
return Task {}
}
}
/// File and private-media transfer over a mesh transport, including the
/// capability-proof policy that gates encrypted private media.
protocol MeshFileTransferring: AnyObject {

View File

@ -322,6 +322,15 @@ final class MessageDeduplicationService {
return nostrEventStore?.wipe() ?? true
}
@MainActor
func clearAllAsync() async -> Bool {
contentCache.clear()
nostrEventCache.clear()
nostrAckCache.clear()
pendingPersistIDs.removeAll()
return await nostrEventStore?.wipeAsync() ?? true
}
/// Clears only the in-memory Nostr caches (events and ACKs). Runs on
/// every geohash channel switch, so the disk record deliberately
/// survives — wiping it here would forfeit cross-launch private-envelope dedup

View File

@ -69,6 +69,19 @@ final class NostrProcessedEventStore {
ioQueue.sync { PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL) }
}
/// Completes in FIFO order without occupying the caller's executor.
func wipeAsync() async -> Bool {
await withCheckedContinuation { continuation in
enqueueWipe { continuation.resume(returning: $0) }
}
}
private func enqueueWipe(_ completion: @escaping (Bool) -> Void) {
ioQueue.async { [self] in
completion(PanicFileDeletion.remove(&fileURL, resolvingWith: resolveDefaultFileURL))
}
}
private func loadLocked() -> [String] {
guard let fileURL,
let data = try? Data(contentsOf: fileURL),

View File

@ -13,5 +13,5 @@ struct PanicMetadataWipeOperations {
var wipeGossip: () -> Bool
var wipeGroups: () -> Bool
var wipeBoard: () -> Bool
var wipeEvents: () -> Bool
var wipeEvents: @MainActor () async -> Bool
}

View File

@ -139,12 +139,14 @@ final class GossipSyncManager {
// Timer
private var periodicTimer: DispatchSourceTimer?
private let queue = DispatchQueue(label: "mesh.sync", qos: .utility)
private let queue: DispatchQueue
private var lastStalePeerCleanup: Date = .distantPast
private var syncSchedules: [SyncSchedule] = []
private var responseRateLimiter: SyncResponseRateLimiter
init(myPeerID: PeerID, config: Config = Config(), requestSyncManager: RequestSyncManager, archive: GossipMessageArchive? = nil) {
init(myPeerID: PeerID, config: Config = Config(), requestSyncManager: RequestSyncManager, archive: GossipMessageArchive? = nil,
queue: DispatchQueue = DispatchQueue(label: "mesh.sync", qos: .utility)) {
self.queue = queue
self.myPeerID = myPeerID
self.config = config
self.requestSyncManager = requestSyncManager
@ -200,8 +202,8 @@ final class GossipSyncManager {
periodicTimer?.cancel(); periodicTimer = nil
}
/// Retire this owner after its earlier persistence finishes. The caller
/// removes the archive after this returns, while transport admission is closed.
/// Retire this owner after its earlier persistence finishes.
/// The panic controller deletes the archive after this method returns.
func stopForPanic() {
stop()
queue.sync {
@ -209,6 +211,22 @@ final class GossipSyncManager {
}
}
/// Retires persistence in queue order without blocking the caller.
@MainActor
func stopForPanicAsync() async {
stop()
await withCheckedContinuation { continuation in
enqueuePanicRetirement { continuation.resume() }
}
}
private func enqueuePanicRetirement(_ completion: @escaping () -> Void) {
queue.async { [self] in
stoppedForPanic = true
completion()
}
}
func scheduleInitialSyncToPeer(_ peerID: PeerID, delaySeconds: TimeInterval = 5.0) {
queue.asyncAfter(deadline: .now() + delaySeconds) { [weak self] in
guard let self = self else { return }

View File

@ -83,9 +83,24 @@ final class ChatOutgoingCoordinator {
/// the message still goes out at the difficulty already reached.
/// (Read access is internal so tests can await the send's completion.)
private(set) var geohashMiningTask: Task<Void, Never>?
private var wipeGeneration: UInt64 = 0
init(context: any ChatOutgoingContext) {
/// Panic abandons pending sends; ordinary cancellation still expedites mining.
func resetForPanic() {
wipeGeneration &+= 1
geohashMiningTask?.cancel()
geohashMiningTask = nil
}
typealias GeohashEventBuilder = (String, String, NostrIdentity, String, Bool) async throws -> NostrEvent
private let buildGeohashEvent: GeohashEventBuilder
init(context: any ChatOutgoingContext, buildGeohashEvent: @escaping GeohashEventBuilder = {
try await NostrProtocol.createMinedEphemeralGeohashEvent(
content: $0, geohash: $1, senderIdentity: $2, nickname: $3, teleported: $4)
}) {
self.context = context
self.buildGeohashEvent = buildGeohashEvent
}
/// Finish any in-flight geohash PoW mining early (the pending message
@ -98,7 +113,9 @@ final class ChatOutgoingCoordinator {
guard let trimmed = content.trimmedOrNilIfEmpty else { return }
if content.hasPrefix("/") {
Task { @MainActor [weak context = self.context] in
let generation = wipeGeneration
Task { @MainActor [weak self, weak context = self.context] in
guard let self, self.wipeGeneration == generation else { return }
context?.handleCommand(content)
}
return
@ -184,26 +201,23 @@ private extension ChatOutgoingCoordinator {
// delays or blocks a send beyond `NostrPoW.miningTimeCap`.
let previousSend = geohashMiningTask
previousSend?.cancel()
geohashMiningTask = Task { @MainActor [weak context = self.context] in
let generation = wipeGeneration
geohashMiningTask = Task { @MainActor [weak self, weak context = self.context] in
await previousSend?.value
guard let self, self.wipeGeneration == generation else { return }
let event: NostrEvent
do {
event = try await NostrProtocol.createMinedEphemeralGeohashEvent(
content: trimmed,
geohash: channel.geohash,
senderIdentity: identity,
nickname: nickname,
teleported: teleported
)
event = try await self.buildGeohashEvent(trimmed, channel.geohash, identity, nickname, teleported)
} catch {
guard self.wipeGeneration == generation else { return }
SecureLogger.error("❌ Failed to prepare geohash message: \(error)", category: .session)
context?.addSystemMessage(
String(localized: "system.location.send_failed", comment: "System message when a location channel send fails")
)
return
}
guard let context else { return }
guard self.wipeGeneration == generation, let context else { return }
let message = BitchatMessage(
id: event.id,

View File

@ -11,6 +11,7 @@ import Foundation
/// true dependencies explicit.
@MainActor
protocol ChatTransportEventContext: AnyObject {
var networkActivationAllowed: Bool { get }
// MARK: Connection & chat state
var isConnected: Bool { get set }
var nickname: String { get }
@ -86,6 +87,10 @@ protocol ChatTransportEventContext: AnyObject {
func handleVouchPayload(from peerID: PeerID, payload: Data)
}
extension ChatTransportEventContext {
var networkActivationAllowed: Bool { true }
}
extension ChatViewModel: ChatTransportEventContext {
// `isConnected`, `nickname`, `myPeerID`, `privateMessages(for:)`,
// `unreadPrivateMessages`, `selectedPrivateChatPeer`, `notifyUIChanged()`,
@ -268,6 +273,7 @@ final class ChatTransportEventCoordinator {
@MainActor
func didConnectToPeerSynchronously(_ peerID: PeerID) {
guard context.networkActivationAllowed else { return }
SecureLogger.debug("🤝 Peer connected: \(peerID)", category: .session)
context.isConnected = true
@ -291,6 +297,7 @@ final class ChatTransportEventCoordinator {
@MainActor
func didDisconnectFromPeerSynchronously(_ peerID: PeerID) {
guard context.networkActivationAllowed else { return }
SecureLogger.debug("👋 Peer disconnected: \(peerID)", category: .session)
context.removeEphemeralSession(peerID: peerID)
@ -332,6 +339,7 @@ private extension ChatTransportEventCoordinator {
messageID: String?,
in context: any ChatTransportEventContext
) {
guard context.networkActivationAllowed else { return }
let normalized = content.trimmed
let mentions = context.parseMentions(from: normalized)
let message = BitchatMessage(
@ -358,6 +366,7 @@ private extension ChatTransportEventCoordinator {
_ message: BitchatMessage,
in context: any ChatTransportEventContext
) -> Bool {
guard context.networkActivationAllowed else { return false }
guard !context.isMessageBlocked(message) else { return false }
guard !message.content.trimmed.isEmpty || message.isPrivate else { return false }
@ -374,7 +383,7 @@ private extension ChatTransportEventCoordinator {
func runOnMain(_ action: @escaping @MainActor (any ChatTransportEventContext) -> Void) {
Task { @MainActor [weak context = self.context] in
guard let context else { return }
guard let context, context.networkActivationAllowed else { return }
action(context)
}
}
@ -429,6 +438,7 @@ private extension ChatTransportEventCoordinator {
timestamp: Date,
in context: any ChatTransportEventContext
) {
guard context.networkActivationAllowed else { return }
switch type {
case .privateMessage:
guard let packet = PrivateMessagePacket.decode(from: payload) else { return }

View File

@ -199,7 +199,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
let unifiedPeerService: UnifiedPeerService
let autocompleteService: AutocompleteService
let deduplicationService: MessageDeduplicationService // internal for test access
private lazy var outgoingCoordinator = ChatOutgoingCoordinator(context: self)
private(set) lazy var outgoingCoordinator = ChatOutgoingCoordinator(context: self)
private lazy var lifecycleCoordinator = ChatLifecycleCoordinator(context: self)
private lazy var transportEventCoordinator = ChatTransportEventCoordinator(context: self)
private lazy var peerListCoordinator = ChatPeerListCoordinator(context: self)
@ -332,7 +332,9 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
private let panicMetadataWipeOperations: PanicMetadataWipeOperations?
private let panicRecoveryOperations: PanicRecoveryOperations
private let panicNetworkLifecycle: PanicNetworkLifecycle
private var isPanicResetting = false
@Published private(set) var isPanicResetting = false
private(set) var startupPanicRecovery: Task<Bool, Never>?
private var bootstrapConfigured = false
/// Private group membership: keys in the keychain, metadata on disk.
let groupStore: GroupStore
private let nicknameKey = "bitchat.nickname"
@ -1238,14 +1240,20 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
"Pending panic recovery detected; wiping before runtime services start",
category: .security
)
_ = panicClearAllData(restartServices: false)
startupPanicRecovery = beginPanicClearAllData(restartServices: false)
}
if networkActivationAllowed {
ChatViewModelBootstrapper(viewModel: self).configure()
configureAfterRecoveryIfNeeded()
}
}
private func configureAfterRecoveryIfNeeded() {
guard !bootstrapConfigured else { return }
bootstrapConfigured = true
ChatViewModelBootstrapper(viewModel: self).configure()
}
// MARK: - Deinitialization
deinit {
@ -1315,12 +1323,14 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
/// Routes to private chat if one is selected, otherwise broadcasts
@MainActor
func sendMessage(_ content: String) {
guard networkActivationAllowed else { return }
outgoingCoordinator.sendMessage(content)
}
/// Sends a 👋 to the mesh channel regardless of the active channel.
@MainActor
func sendMeshWave() {
guard networkActivationAllowed else { return }
outgoingCoordinator.sendMeshWave()
}
@ -1561,28 +1571,42 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
// PANIC: Emergency data clearing for activist safety
@MainActor
@discardableResult
func panicClearAllData(restartServices: Bool = true) -> Bool {
func panicClearAllData(restartServices: Bool = true) async -> Bool {
guard let task = beginPanicClearAllData(restartServices: restartServices) else { return false }
return await task.value
}
/// Establish the recovery boundary synchronously at the confirmed UI action.
/// The returned task owns cleanup even if its caller stops awaiting it.
@MainActor
func beginPanicClearAllData(restartServices: Bool = true) -> Task<Bool, Never>? {
guard !isPanicResetting else { return nil }
panicRecoveryBlocked = true
isPanicResetting = true
defer { isPanicResetting = false }
// Stop internet and location-presence work before clearing identity or
// state. These services cancel their subscriptions and delayed tasks,
// so old callbacks cannot reconnect during the transaction.
panicNetworkLifecycle.stop()
// IMPORTANT: Clear Nostr-related state
// Drop relay subscriptions, handlers, pending sends, and replay state.
// Geohash DM handlers can capture pre-wipe Nostr identities, so a plain
// disconnect is not enough here.
NostrRelayManager.shared.resetForPanicWipe()
// Clearing relay handlers stops NEW events, but a detached gift-wrap
// decrypt spawned just before the wipe still holds a pre-wipe key and
// ciphertext; bump the pipeline's wipe generation so its result is
// dropped at the main-actor delivery hop instead of landing here.
nostrCoordinator.inbound.invalidateInFlightDecrypts()
outgoingCoordinator.resetForPanic()
nostrRelayManager = nil
// Establish both independent durable intents before erasing anything.
// `wipeMedia` will still attempt deletion if neither write succeeds.
let recoveryIntent = panicRecoveryOperations.begin()
// Quiesce the mesh before clearing stores. Identity replacement below
// deliberately stays stopped until media deletion and marker commit.
if let panicTransport = meshService as? PanicResettingTransport {
panicTransport.suspendForPanicReset()
} else {
meshService.emergencyDisconnectAll()
}
// Invalidate detached media preparation and close live capture file
// handles before clearing state or removing the media directory.
mediaTransferCoordinator.resetForPanic()
@ -1598,9 +1622,31 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
// Clear all messages (public timelines and private chats live in the
// single-writer ConversationStore; the derived `messages` view and
// the legacy mirror empty with it)
publicMessagePipeline.resetForPanic()
conversations.clearAll()
pendingGeohashSystemMessages.removeAll()
// Quiesce the mesh before clearing stores. Identity replacement below
// deliberately stays stopped until media deletion and marker commit.
let retirement: Task<Void, Never>?
if let panicTransport = meshService as? PanicResettingTransport {
retirement = panicTransport.beginPanicReset()
} else {
meshService.emergencyDisconnectAll()
retirement = nil
}
return Task { @MainActor [self] in
defer { isPanicResetting = false }
await retirement?.value
return await finishPanicClearAllData(recoveryIntent, restartServices: restartServices)
}
}
@MainActor
private func finishPanicClearAllData(
_ recoveryIntent: PanicRecoveryIntent,
restartServices: Bool
) async -> Bool {
// Delete all keychain data (including Noise and Nostr keys)
let keychainWipeCompleted = keychain.deleteAllKeychainData()
if !keychainWipeCompleted {
@ -1700,19 +1746,13 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
// Clear read receipt tracking
sentReadReceipts.removeAll()
metadataWipeCompleted = (panicMetadataWipeOperations?.wipeEvents() ?? deduplicationService.clearAll()) && metadataWipeCompleted
// IMPORTANT: Clear Nostr-related state
// Drop relay subscriptions, handlers, pending sends, and replay state.
// Geohash DM handlers can capture pre-wipe Nostr identities, so a plain
// disconnect is not enough here.
NostrRelayManager.shared.resetForPanicWipe()
// Clearing relay handlers stops NEW events, but a detached gift-wrap
// decrypt spawned just before the wipe still holds a pre-wipe key and
// ciphertext; bump the pipeline's wipe generation so its result is
// dropped at the main-actor delivery hop instead of landing here.
nostrCoordinator.inbound.invalidateInFlightDecrypts()
nostrRelayManager = nil
let eventCleanupCompleted: Bool
if let operations = panicMetadataWipeOperations {
eventCleanupCompleted = await operations.wipeEvents()
} else {
eventCleanupCompleted = await deduplicationService.clearAllAsync()
}
metadataWipeCompleted = eventCleanupCompleted && metadataWipeCompleted
// Clear Nostr identity associations
idBridge.clearAllAssociations()
@ -1728,9 +1768,8 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
meshService.setNickname(nickname)
}
// The wipe must finish before this security action returns. A detached
// task could otherwise lose a race with a new capture or app exit and
// leave pre-panic media behind.
// Keep admission closed and recovery pending until file cleanup and
// the recovery-marker commit have both finished.
let panicCompleted: Bool
do {
try panicRecoveryOperations.wipeMedia(recoveryIntent)
@ -1766,18 +1805,23 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
guard panicCompleted else { return false }
if let panicTransport = meshService as? PanicResettingTransport {
// Startup recovery reopens admission but leaves actual service
// start to the bootstrapper immediately after this method.
// Startup recovery reopens admission here; the bootstrapper below
// starts services if initialization has not finished yet.
panicTransport.completePanicReset(
restartServices: restartServices
restartServices: restartServices && bootstrapConfigured
)
}
// A failed startup attempt leaves the service graph unwired. The first
// successful retry must configure it before ordinary runtime work resumes.
let wasConfigured = bootstrapConfigured
configureAfterRecoveryIfNeeded()
if restartServices {
// All persistent state and media are gone. Bring each service back
// only now, under the new identity — a panic-resetting transport
// owns its own restart sequencing above.
if !(meshService is PanicResettingTransport) {
if wasConfigured && !(meshService is PanicResettingTransport) {
meshService.startServices()
}
@ -2054,6 +2098,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
@MainActor
func didReceiveTransportEvent(_ event: TransportEvent) {
guard networkActivationAllowed else { return }
switch event {
case .messageReceived(let message):
_ = didReceiveTransportMessageSynchronously(message)
@ -2159,13 +2204,15 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
func didReceiveGroupMessage(payload: Data, timestamp: Date) {
Task { @MainActor [weak self] in
self?.groupCoordinator.handleGroupMessagePayload(payload, timestamp: timestamp)
guard let self, self.networkActivationAllowed else { return }
self.groupCoordinator.handleGroupMessagePayload(payload, timestamp: timestamp)
}
}
func didReceivePublicVoiceFrame(from peerID: PeerID, nickname: String, payload: Data, timestamp: Date) {
Task { @MainActor [weak self] in
self?.liveVoiceCoordinator.handlePublicVoiceFramePayload(
guard let self, self.networkActivationAllowed else { return }
self.liveVoiceCoordinator.handlePublicVoiceFramePayload(
from: peerID,
nickname: nickname,
payload: payload,
@ -2332,6 +2379,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
/// Handle incoming public message
@MainActor
func handlePublicMessage(_ message: BitchatMessage) {
guard networkActivationAllowed else { return }
// Bridge hints are unauthenticated and may never suppress a genuine
// BLE sender. Once the radio packet has passed BLE signature checks,
// replace any earlier bridge alias before this row is enqueued.
@ -2350,6 +2398,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage
/// difficulty; sufficient PoW relaxes the per-sender rate limit.
@MainActor
func handlePublicMessage(_ message: BitchatMessage, powBits: Int) {
guard networkActivationAllowed else { return }
publicConversationCoordinator.handlePublicMessage(message, powBits: powBits)
}

View File

@ -36,6 +36,7 @@ extension ChatViewModel {
id: NostrIdentity,
messageTimestamp: Date
) {
guard networkActivationAllowed else { return }
privateConversationCoordinator.handlePrivateMessage(
payload,
senderPubkey: senderPubkey,
@ -176,6 +177,7 @@ extension ChatViewModel {
@MainActor
func handlePrivateMessage(_ message: BitchatMessage) {
guard networkActivationAllowed else { return }
// A finalized voice note whose burst already streamed in live swaps
// into the existing bubble instead of appearing (and notifying) twice.
if liveVoiceCoordinator.absorbFinalizedVoiceNote(message) { return }

View File

@ -11,6 +11,7 @@ import Tor
protocol GeohashSubscriptionContext: AnyObject {
// MARK: Channel & subscription state
var activeChannel: ChannelID { get set }
var networkActivationAllowed: Bool { get }
var currentGeohash: String? { get set }
var geoSubscriptionID: String? { get }
var geoDmSubscriptionID: String? { get }
@ -132,6 +133,43 @@ final class GeohashSubscriptionManager {
self.presence = presence
}
#if DEBUG
/// Lets tests hold the outer callback before it enters the inbound pipeline.
@MainActor var relayCallbackScheduler: ((@escaping @MainActor () async -> Void) -> Void)?
#endif
@MainActor
func giftWrapHandler(identity: NostrIdentity, resubscribing: Bool) -> (NostrEvent) -> Void {
relayEventHandler { manager, event in
if resubscribing {
await manager.inbound.subscribeGiftWrap(event, id: identity)?.value
} else {
await manager.inbound.handleGiftWrap(event, id: identity)?.value
}
}
}
@MainActor
private func relayEventHandler(
_ receive: @escaping @MainActor (GeohashSubscriptionManager, NostrEvent) async -> Void
) -> (NostrEvent) -> Void {
let generation = inbound.wipeGeneration
#if DEBUG
let scheduler = relayCallbackScheduler
#endif
return { [weak self] event in
let delivery: @MainActor () async -> Void = { [weak self] in
guard let self, self.inbound.wipeGeneration == generation,
self.context?.networkActivationAllowed == true else { return }
await receive(self, event)
}
#if DEBUG
if let scheduler { scheduler(delivery); return }
#endif
Task { @MainActor in await delivery() }
}
}
@MainActor
func resubscribeCurrentGeohash() {
guard let context else { return }
@ -153,17 +191,15 @@ final class GeohashSubscriptionManager {
count: TransportConfig.nostrGeoRelayCount
)
replayingGeoSubscriptionID = subID
NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays, handler: { [weak self] event in
Task { @MainActor [weak self] in
guard let self else { return }
self.inbound.subscribeNostrEvent(event, isHistoryReplay: self.replayingGeoSubscriptionID == subID)
// Gateway downlink: rebroadcast relay events for the viewed
// channel onto the mesh (no-op unless gateway mode is on).
GatewayService.shared.rebroadcastRelayEvent(event, geohash: channel.geohash)
}
let generation = inbound.wipeGeneration
NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays, handler: relayEventHandler { manager, event in
manager.inbound.subscribeNostrEvent(event, isHistoryReplay: manager.replayingGeoSubscriptionID == subID)
// Gateway downlink shares the callback's panic-generation check.
GatewayService.shared.rebroadcastRelayEvent(event, geohash: channel.geohash)
}, onEOSE: { [weak self] in
Task { @MainActor [weak self] in
self?.endHistoryReplay(for: subID)
guard let self, self.inbound.wipeGeneration == generation else { return }
self.endHistoryReplay(for: subID)
}
})
@ -179,11 +215,8 @@ final class GeohashSubscriptionManager {
pubkey: identity.publicKeyHex,
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
)
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in
Task { @MainActor [weak self] in
self?.inbound.subscribeGiftWrap(giftWrap, id: identity)
}
}
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub,
handler: giftWrapHandler(identity: identity, resubscribing: true))
}
}
@ -252,17 +285,15 @@ final class GeohashSubscriptionManager {
let filter = NostrFilter.geohashEphemeral(channel.geohash, since: ts, limit: TransportConfig.nostrGeohashInitialLimit)
let subRelays = GeoRelayDirectory.shared.closestRelays(toGeohash: channel.geohash, count: 5)
replayingGeoSubscriptionID = subID
NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays, handler: { [weak self] event in
Task { @MainActor [weak self] in
guard let self else { return }
self.inbound.handleNostrEvent(event, isHistoryReplay: self.replayingGeoSubscriptionID == subID)
// Gateway downlink: rebroadcast relay events for the viewed
// channel onto the mesh (no-op unless gateway mode is on).
GatewayService.shared.rebroadcastRelayEvent(event, geohash: channel.geohash)
}
let generation = inbound.wipeGeneration
NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays, handler: relayEventHandler { manager, event in
manager.inbound.handleNostrEvent(event, isHistoryReplay: manager.replayingGeoSubscriptionID == subID)
// Gateway downlink shares the callback's panic-generation check.
GatewayService.shared.rebroadcastRelayEvent(event, geohash: channel.geohash)
}, onEOSE: { [weak self] in
Task { @MainActor [weak self] in
self?.endHistoryReplay(for: subID)
guard let self, self.inbound.wipeGeneration == generation else { return }
self.endHistoryReplay(for: subID)
}
})
@ -283,11 +314,8 @@ final class GeohashSubscriptionManager {
pubkey: identity.publicKeyHex,
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
)
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub) { [weak self] giftWrap in
Task { @MainActor [weak self] in
self?.inbound.handleGiftWrap(giftWrap, id: identity)
}
}
NostrRelayManager.shared.subscribe(filter: dmFilter, id: dmSub,
handler: giftWrapHandler(identity: identity, resubscribing: false))
}
@MainActor
@ -384,11 +412,10 @@ final class GeohashSubscriptionManager {
limit: TransportConfig.nostrGeohashSampleLimit
)
let subRelays = GeoRelayDirectory.shared.closestRelays(toGeohash: gh, count: 5)
NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays) { [weak self] event in
Task { @MainActor [weak self] in
self?.presence.subscribeNostrEvent(event, gh: gh)
}
}
NostrRelayManager.shared.subscribe(filter: filter, id: subID, relayUrls: subRelays,
handler: relayEventHandler { manager, event in
manager.presence.subscribeNostrEvent(event, gh: gh)
})
}
@MainActor
@ -418,10 +445,9 @@ final class GeohashSubscriptionManager {
since: Date().addingTimeInterval(-TransportConfig.nostrDMSubscribeLookbackSeconds)
)
context.nostrRelayManager?.subscribe(filter: filter, id: "chat-messages") { [weak self] event in
Task { @MainActor [weak self] in
self?.inbound.handleNostrMessage(event)
}
}
context.nostrRelayManager?.subscribe(filter: filter, id: "chat-messages",
handler: relayEventHandler { manager, event in
await manager.inbound.handleNostrMessage(event)?.value
})
}
}

View File

@ -9,6 +9,7 @@ import Foundation
@MainActor
protocol NostrInboundPipelineContext: AnyObject {
var currentGeohash: String? { get }
var networkActivationAllowed: Bool { get }
// MARK: Event dedup
func hasProcessedNostrEvent(_ eventID: String) -> Bool
@ -127,7 +128,7 @@ final class NostrInboundPipeline {
/// count when they arrive, which keeps senders with skewed clocks visible.
@MainActor
func subscribeNostrEvent(_ event: NostrEvent, isHistoryReplay: Bool = false) {
guard let context else { return }
guard let context, context.networkActivationAllowed else { return }
// Cheap rejects (kind, dedup lookup) — duplicates dominate real
// traffic. The signature was already verified (exactly once, off the
// main actor) by NostrRelayManager before delivery.
@ -200,8 +201,10 @@ final class NostrInboundPipeline {
mentions: mentions.isEmpty ? nil : mentions
)
Task { @MainActor [weak context] in
guard let context else { return }
let generation = wipeGeneration
Task { @MainActor [weak self, weak context] in
guard let self, let context, context.networkActivationAllowed,
self.wipeGeneration == generation else { return }
let isBlocked = context.isNostrBlocked(pubkeyHexLowercased: event.pubkey.lowercased())
context.handlePublicMessage(message, powBits: powBits)
if !isBlocked {
@ -214,7 +217,7 @@ final class NostrInboundPipeline {
/// See `subscribeNostrEvent(_:isHistoryReplay:)` for `isHistoryReplay`.
@MainActor
func handleNostrEvent(_ event: NostrEvent, isHistoryReplay: Bool = false) {
guard let context else { return }
guard let context, context.networkActivationAllowed else { return }
// Cheap rejects (kind, dedup lookup) — the signature was already
// verified (exactly once, off the main actor) by NostrRelayManager.
guard (event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue
@ -298,45 +301,51 @@ final class NostrInboundPipeline {
mentions: mentions.isEmpty ? nil : mentions
)
Task { @MainActor [weak context] in
guard let context else { return }
let generation = wipeGeneration
Task { @MainActor [weak self, weak context] in
guard let self, let context, context.networkActivationAllowed,
self.wipeGeneration == generation else { return }
context.handlePublicMessage(message, powBits: powBits)
context.checkForMentions(message)
context.sendHapticFeedback(for: message)
}
}
@discardableResult
@MainActor
func subscribeGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
guard let context else { return }
func subscribeGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) -> Task<Void, Never>? {
guard let context, context.networkActivationAllowed else { return nil }
// Cheap dedup pre-check only; processGeohashGiftWrap does the
// authoritative main-actor check-and-record before the off-main
// NIP-17 unwrap. The outer signature was already verified (exactly
// once, off the main actor) by NostrRelayManager.
guard !context.hasProcessedNostrEvent(giftWrap.id) else { return }
guard !context.hasProcessedNostrEvent(giftWrap.id) else { return nil }
// Capture the wipe generation at spawn, alongside the per-geohash
// identity (private key) the detached task strongly captures. A panic
// wipe between spawn and delivery bumps the generation, and the task
// drops its result instead of delivering plaintext post-wipe.
let wipeGeneration = self.wipeGeneration
Task.detached(priority: .userInitiated) { [weak self] in
await self?.processGeohashGiftWrap(giftWrap, id: id, verbose: false, wipeGeneration: wipeGeneration)
return Task.detached(priority: .userInitiated) { [weak self] in
guard let self else { return }
await self.processGeohashGiftWrap(giftWrap, id: id, verbose: false, wipeGeneration: wipeGeneration)
}
}
@discardableResult
@MainActor
func handleGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) {
guard let context else { return }
func handleGiftWrap(_ giftWrap: NostrEvent, id: NostrIdentity) -> Task<Void, Never>? {
guard let context, context.networkActivationAllowed else { return nil }
// Cheap dedup pre-check only; see subscribeGiftWrap.
if context.hasProcessedNostrEvent(giftWrap.id) {
return
return nil
}
// Spawn-time wipe-generation capture; see subscribeGiftWrap.
let wipeGeneration = self.wipeGeneration
Task.detached(priority: .userInitiated) { [weak self] in
await self?.processGeohashGiftWrap(giftWrap, id: id, verbose: true, wipeGeneration: wipeGeneration)
return Task.detached(priority: .userInitiated) { [weak self] in
guard let self else { return }
await self.processGeohashGiftWrap(giftWrap, id: id, verbose: true, wipeGeneration: wipeGeneration)
}
}
@ -361,7 +370,7 @@ final class NostrInboundPipeline {
// Authoritative check-and-record, atomic on the main actor so two
// concurrent detached tasks can't both process the same event.
let alreadyProcessed: Bool = await MainActor.run {
guard self.wipeGeneration == wipeGeneration else { return true }
guard context.networkActivationAllowed, self.wipeGeneration == wipeGeneration else { return true }
if context.hasProcessedNostrEvent(giftWrap.id) { return true }
context.recordProcessedNostrEvent(giftWrap.id)
return false
@ -396,7 +405,7 @@ final class NostrInboundPipeline {
// A panic wipe during the off-main decrypt must not let the
// pre-wipe plaintext reach post-wipe state; drop it here, atomic
// with the wipe on the main actor.
guard self.wipeGeneration == wipeGeneration else { return }
guard context.networkActivationAllowed, self.wipeGeneration == wipeGeneration else { return }
guard let packet = Self.decodeEmbeddedBitChatPacket(from: content),
packet.type == MessageType.noiseEncrypted.rawValue,
let payload = NoisePayload.decode(packet.payload)
@ -432,38 +441,35 @@ final class NostrInboundPipeline {
}
@MainActor
func handleNostrMessage(_ giftWrap: NostrEvent) {
guard let context else { return }
@discardableResult
func handleNostrMessage(_ giftWrap: NostrEvent) -> Task<Void, Never>? {
guard let context, context.networkActivationAllowed else { return nil }
// Cheap dedup pre-check only; processNostrMessage does the
// authoritative check-and-record before the off-main NIP-17 unwrap.
// The outer signature was already verified (exactly once, off the
// main actor) by NostrRelayManager, and only verified events are
// recorded, so a forged-signature copy can never poison the dedup
// set and suppress the genuine event.
if context.hasProcessedNostrEvent(giftWrap.id) { return }
if context.hasProcessedNostrEvent(giftWrap.id) { return nil }
Task.detached(priority: .userInitiated) { [weak self] in
await self?.processNostrMessage(giftWrap)
let generation = wipeGeneration
return Task.detached(priority: .userInitiated) { [weak self] in
guard let self else { return }
await self.processNostrMessage(giftWrap, wipeGeneration: generation)
}
}
func processNostrMessage(_ giftWrap: NostrEvent) async {
func processNostrMessage(_ giftWrap: NostrEvent, wipeGeneration: UInt64) async {
guard let context else { return }
// Authoritative check-and-record, atomic on the main actor so two
// concurrent detached tasks can't both process the same event.
let alreadyProcessed: Bool = await MainActor.run {
if context.hasProcessedNostrEvent(giftWrap.id) { return true }
// Admission, dedup and identity acquisition share one main-actor hop.
// A task admitted before panic must not acquire the old identity under
// the new generation while asynchronous cleanup is still pending.
let currentIdentity: NostrIdentity? = await MainActor.run {
guard context.networkActivationAllowed,
self.wipeGeneration == wipeGeneration,
!context.hasProcessedNostrEvent(giftWrap.id) else { return nil }
context.recordProcessedNostrEvent(giftWrap.id)
return false
}
if alreadyProcessed { return }
// Fetch the identity and the wipe generation in ONE main-actor hop:
// the generation then vouches for exactly this identity. A wipe after
// this point bumps the generation and the delivery hop below drops
// the decrypted result (same guard as processGeohashGiftWrap; this
// account-mailbox path had the identical hazard).
let (currentIdentity, wipeGeneration): (NostrIdentity?, UInt64) = await MainActor.run {
(context.currentNostrIdentity(), self.wipeGeneration)
return context.currentNostrIdentity()
}
guard let currentIdentity else { return }
@ -502,7 +508,7 @@ final class NostrInboundPipeline {
await MainActor.run {
// Drop pre-wipe plaintext if a panic wipe landed
// during the off-main decrypt (see above).
guard self.wipeGeneration == wipeGeneration else { return }
guard context.networkActivationAllowed, self.wipeGeneration == wipeGeneration else { return }
context.registerNostrKeyMapping(senderPubkey, for: targetPeerID)
switch payload.type {

View File

@ -74,6 +74,14 @@ final class PublicMessagePipeline {
buffer.contains { $0.message.id == messageID }
}
func resetForPanic() {
timer?.invalidate()
timer = nil
buffer.removeAll(keepingCapacity: false)
recentBatchSizes.removeAll(keepingCapacity: false)
dynamicFlushInterval = baseFlushInterval
}
func flushIfNeeded() {
flushBuffer()
}

View File

@ -228,6 +228,7 @@ struct ContentView: View {
var body: some View {
mainContent
.disabled(appChromeModel.panicInProgress)
.onAppear { [conversationUIModel, voiceRecordingVM] in
conversationUIModel.setCurrentColorScheme(colorScheme)
conversationUIModel.setCurrentTheme(appTheme)

View File

@ -485,7 +485,7 @@ struct AppArchitectureTests {
@Test("Panic wipe dismisses chrome sheets so its outcome is visible")
@MainActor
func panicWipeDismissesChromePresentation() {
func panicWipeDismissesChromePresentation() async {
let viewModel = makeArchitectureViewModel()
let privateInboxModel = PrivateInboxModel(conversations: ConversationStore())
let chromeModel = AppChromeModel(chatViewModel: viewModel, privateInboxModel: privateInboxModel)
@ -500,6 +500,9 @@ struct AppArchitectureTests {
chromeModel.showFingerprint(for: PeerID(str: "peer-3"))
chromeModel.panicClearAllData()
#expect(viewModel.isPanicResetting)
#expect(!viewModel.networkActivationAllowed)
await chromeModel.panicTask?.value
#expect(!chromeModel.isAppInfoPresented)
#expect(!chromeModel.isLocationChannelsSheetPresented)

View File

@ -106,6 +106,7 @@ private final class MockChatNostrContext: ChatNostrContext {
// Nostr identity & blocking
var geohashIdentities: [String: NostrIdentity] = [:]
var networkActivationAllowed = true
var nostrIdentity: NostrIdentity?
var blockedNostrPubkeys: Set<String> = []
var displayNamesByPubkey: [String: String] = [:]
@ -117,7 +118,13 @@ private final class MockChatNostrContext: ChatNostrContext {
return identity
}
func currentNostrIdentity() -> NostrIdentity? { nostrIdentity }
var identityReads = 0
var onIdentityRead: (() -> Void)?
func currentNostrIdentity() -> NostrIdentity? {
identityReads += 1
onIdentityRead?()
return nostrIdentity
}
func isNostrBlocked(pubkeyHexLowercased: String) -> Bool {
blockedNostrPubkeys.contains(pubkeyHexLowercased.lowercased())
@ -275,6 +282,23 @@ private func teleportedGeohashEvent(from sender: NostrIdentity, sentAt: Date) th
/// the full view-model tests.
struct ChatNostrCoordinatorContextTests {
@Test(arguments: [false, true]) @MainActor
func queuedPublicNostrDeliveryRespectsPanicBoundary(_ sampled: Bool) async throws {
let context = MockChatNostrContext()
let coordinator = ChatNostrCoordinator(context: context)
let sender = try NostrIdentity.generate()
let event = try NostrProtocol.createEphemeralGeohashEvent(
content: "pre-panic public message", geohash: "u4pruyd",
senderIdentity: sender, nickname: "synthetic")
if sampled { coordinator.inbound.subscribeNostrEvent(event) }
else { coordinator.inbound.handleNostrEvent(event) }
coordinator.inbound.invalidateInFlightDecrypts()
await drainMainQueue()
#expect(context.handledPublicMessages.isEmpty)
#expect(context.mentionCheckedMessageIDs.isEmpty)
#expect(context.hapticMessageIDs.isEmpty)
}
@Test @MainActor
func handleNostrEvent_ingestsPublicMessageOnceAndDeduplicates() async throws {
let context = MockChatNostrContext()
@ -543,6 +567,51 @@ struct ChatNostrCoordinatorContextTests {
// `test_receiveGiftWrap_tamperedSignatureIsDroppedAndDoesNotPoisonDedup`.
// The inbound pipeline only ever sees verified events.
@Test(arguments: [false, true]) @MainActor
func mailboxRejectsIdentityAcquisitionAcrossPanic(_ blocked: Bool) async throws {
let context = MockChatNostrContext()
let coordinator = ChatNostrCoordinator(context: context)
let recipient = try NostrIdentity.generate()
let sender = try NostrIdentity.generate()
context.nostrIdentity = recipient
let embedded = try #require(NostrEmbeddedBitChat.encodePMForNostrNoRecipient(
content: "old mailbox plaintext", messageID: "mailbox-boundary"))
let giftWrap = try NostrProtocol.createPrivateMessage(content: embedded,
recipientPubkey: recipient.publicKeyHex, senderIdentity: sender)
let generation = coordinator.inbound.wipeGeneration
if blocked { context.networkActivationAllowed = false }
else { coordinator.inbound.invalidateInFlightDecrypts() }
await coordinator.inbound.processNostrMessage(giftWrap, wipeGeneration: generation)
#expect(context.identityReads == 0)
#expect(context.recordedNostrEventIDs.isEmpty)
#expect(context.handledPrivateMessages.isEmpty)
context.networkActivationAllowed = true
await coordinator.inbound.processNostrMessage(giftWrap,
wipeGeneration: coordinator.inbound.wipeGeneration)
#expect(context.identityReads == 1)
#expect(context.handledPrivateMessages.count == 1)
}
@Test @MainActor
func mailboxDropsDeliveryIfPanicFollowsIdentityAcquisition() async throws {
let context = MockChatNostrContext()
let coordinator = ChatNostrCoordinator(context: context)
let recipient = try NostrIdentity.generate()
let sender = try NostrIdentity.generate()
context.nostrIdentity = recipient
let embedded = try #require(NostrEmbeddedBitChat.encodePMForNostrNoRecipient(
content: "old mailbox plaintext", messageID: "mailbox-delivery"))
let giftWrap = try NostrProtocol.createPrivateMessage(content: embedded,
recipientPubkey: recipient.publicKeyHex, senderIdentity: sender)
context.onIdentityRead = { coordinator.inbound.invalidateInFlightDecrypts() }
await coordinator.inbound.processNostrMessage(giftWrap,
wipeGeneration: coordinator.inbound.wipeGeneration)
#expect(context.identityReads == 1)
#expect(context.handledPrivateMessages.isEmpty)
#expect(context.nostrKeyMapping.isEmpty)
}
@Test @MainActor
func processNostrMessage_duplicateDeliveryProcessesOnce() async throws {
let context = MockChatNostrContext()
@ -559,10 +628,10 @@ struct ChatNostrCoordinatorContextTests {
// Fan-in of the same (already verified) gift wrap from several relays
// records and processes exactly once.
await coordinator.inbound.processNostrMessage(giftWrap)
await coordinator.inbound.processNostrMessage(giftWrap, wipeGeneration: coordinator.inbound.wipeGeneration)
#expect(context.recordedNostrEventIDs == [giftWrap.id])
await coordinator.inbound.processNostrMessage(giftWrap)
await coordinator.inbound.processNostrMessage(giftWrap, wipeGeneration: coordinator.inbound.wipeGeneration)
#expect(context.recordedNostrEventIDs == [giftWrap.id])
}

View File

@ -257,3 +257,43 @@ struct ChatOutgoingCoordinatorContextTests {
== context.appendedPublicMessages.map(\.message.id))
}
}
struct OutgoingPanicBoundaryTests {
@Test(arguments: [false, true]) @MainActor
func completionFromOldMiningCannotEchoSendOrReportError(_ failMining: Bool) async throws {
let context = MockChatOutgoingContext()
context.activeChannel = .location(GeohashChannel(level: .city, geohash: "u4pruydq"))
var release: CheckedContinuation<Void, Never>?
let coordinator = ChatOutgoingCoordinator(context: context, buildGeohashEvent: { content, geohash, identity, nickname, teleported in
let event = try await NostrProtocol.createMinedEphemeralGeohashEvent(
content: content, geohash: geohash, senderIdentity: identity,
nickname: nickname, teleported: teleported)
await withCheckedContinuation { release = $0 }
if failMining { throw MockChatOutgoingContext.IdentityUnavailable() }
return event
})
coordinator.sendMessage("old mining")
let task = try #require(coordinator.geohashMiningTask)
for _ in 0..<100 where release == nil { try await Task.sleep(nanoseconds: 10_000_000) }
let resume = try #require(release)
coordinator.resetForPanic()
resume.resume()
await task.value
#expect(context.appendedPublicMessages.isEmpty)
#expect(context.sentGeohashContexts.isEmpty)
#expect(context.recordedActivityKeys.isEmpty)
#expect(context.systemMessages.isEmpty)
}
@Test @MainActor
func panicInvalidatesDeferredCommandsButAllowsFreshCommands() async {
let context = MockChatOutgoingContext()
let coordinator = ChatOutgoingCoordinator(context: context)
coordinator.sendMessage("/who old")
coordinator.resetForPanic()
coordinator.sendMessage("/who fresh")
await drainMainActorTasks()
#expect(context.handledCommands == ["/who fresh"])
}
}

View File

@ -2067,7 +2067,7 @@ struct ChatViewModelPrivateMediaDeletionTests {
}
@Test @MainActor
func panicInvalidatesActiveAndQueuedPrivateChatClears() {
func panicInvalidatesActiveAndQueuedPrivateChatClears() async {
let (viewModel, transport) = makeTestableViewModel()
transport.deferDeletedPrivateMediaPersistence = true
let firstPeerID = PeerID(str: String(repeating: "4", count: 64))
@ -2099,7 +2099,7 @@ struct ChatViewModelPrivateMediaDeletionTests {
transport.deletedPrivateMediaMessageIDBatches == [[firstID]]
)
_ = viewModel.panicClearAllData(restartServices: false)
_ = await viewModel.panicClearAllData(restartServices: false)
viewModel.seedPrivateChat([
privateMediaMessage(
id: firstID,
@ -2153,7 +2153,7 @@ struct ChatViewModelPrivateMediaDeletionTests {
struct ChatViewModelPanicTests {
@Test(arguments: 0...6) @MainActor
func metadataFailureAttemptsRemainingCleanupAndRetryCommits(_ failedStore: Int) {
func metadataFailureAttemptsRemainingCleanupAndRetryCommits(_ failedStore: Int) async {
let names = ["courier", "bridge", "gossip", "groups", "board", "events"]
var attempts: [String] = []
var denyDeletion = true
@ -2191,7 +2191,7 @@ struct ChatViewModelPanicTests {
)
let starts = transport.startServicesCallCount
#expect(!viewModel.panicClearAllData(), "A denied metadata store must keep panic incomplete")
#expect(!(await viewModel.panicClearAllData()), "A denied metadata store must keep panic incomplete")
#expect(attempts == names, "A denied store must not skip the later metadata stores")
#expect(keychain.deleteAllCallCount == 1)
#expect(mediaAttempts == 1, "Metadata failure must not skip media cleanup")
@ -2203,7 +2203,7 @@ struct ChatViewModelPanicTests {
denyDeletion = false
attempts.removeAll()
#expect(viewModel.panicClearAllData())
#expect(await viewModel.panicClearAllData())
#expect(attempts == names, "Retry must attempt the full metadata cleanup again")
#expect(keychain.deleteAllCallCount == 2)
#expect(mediaAttempts == 2)
@ -2215,7 +2215,7 @@ struct ChatViewModelPanicTests {
}
@Test(arguments: 0..<6) @MainActor
func unresolvedMetadataLocationKeepsPanicPendingUntilRetry(_ failedStore: Int) throws {
func unresolvedMetadataLocationKeepsPanicPendingUntilRetry(_ failedStore: Int) async throws {
let names = ["courier", "bridge", "gossip", "groups", "board", "events"]
let fm = FileManager.default
let root = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
@ -2282,7 +2282,7 @@ struct ChatViewModelPanicTests {
let starts = transport.startServicesCallCount
#expect(keychain.saveIdentityKey(Data("SYNTHETIC_KEY".utf8), forKey: "panic-url-resolution-test"))
#expect(!viewModel.panicClearAllData(), "An unresolved persistent location must keep panic incomplete")
#expect(!(await viewModel.panicClearAllData()), "An unresolved persistent location must keep panic incomplete")
#expect(attempts == names, "A failed lookup must not skip other metadata stores")
#expect(keychain.deleteAllCallCount == 1)
#expect(keychain.getIdentityKey(forKey: "panic-url-resolution-test") == nil)
@ -2300,7 +2300,7 @@ struct ChatViewModelPanicTests {
let failedLookups = lookups[failedStore]
denyLookup = false
attempts.removeAll()
#expect(viewModel.panicClearAllData(), "Retry must resolve the location and finish cleanup")
#expect(await viewModel.panicClearAllData(), "Retry must resolve the location and finish cleanup")
#expect(lookups[failedStore] > failedLookups, "Retry must attempt the failed lookup again")
#expect(attempts == names)
#expect(keychain.deleteAllCallCount == 2)
@ -2314,7 +2314,7 @@ struct ChatViewModelPanicTests {
}
@Test @MainActor
func metadataFailureDuringBootstrapKeepsIntentForRetry() {
func metadataFailureDuringBootstrapKeepsIntentForRetry() async {
let names = ["courier", "bridge", "gossip", "groups", "board", "events"]
var attempts: [String] = []
var denyBoardDeletion = true
@ -2348,6 +2348,8 @@ struct ChatViewModelPanicTests {
panicMetadataWipeOperations: metadata
)
_ = await viewModel.startupPanicRecovery?.value
#expect(attempts == names, "Bootstrap recovery must attempt each metadata operation")
#expect(keychain.deleteAllCallCount == 1)
#expect(mediaAttempts == 1)
@ -2357,9 +2359,11 @@ struct ChatViewModelPanicTests {
#expect(transport.startServicesCallCount == 0)
#expect(!viewModel.networkActivationAllowed)
#expect(transport.delegate == nil)
#expect(viewModel.publicMessagePipeline.delegate == nil)
denyBoardDeletion = false
attempts.removeAll()
#expect(viewModel.panicClearAllData())
#expect(await viewModel.panicClearAllData())
#expect(attempts == names)
#expect(keychain.deleteAllCallCount == 2)
#expect(mediaAttempts == 2)
@ -2368,22 +2372,32 @@ struct ChatViewModelPanicTests {
#expect(restarts == 1)
#expect(transport.startServicesCallCount == 1)
#expect(viewModel.networkActivationAllowed)
#expect(transport.delegate === viewModel)
#expect(transport.eventDelegate === viewModel)
#expect(viewModel.publicMessagePipeline.delegate != nil)
let fresh = BitchatMessage(sender: "synthetic", content: "after startup retry", timestamp: Date(), isRelay: false)
viewModel.handlePublicMessage(fresh)
viewModel.publicMessagePipeline.flushIfNeeded()
#expect(viewModel.messages.contains(where: { $0.id == fresh.id }))
let bindings = viewModel.cancellables.count
#expect(await viewModel.panicClearAllData())
#expect(viewModel.cancellables.count == bindings, "A later wipe must not bootstrap twice")
}
@Test @MainActor
func panicClearAllData_finishesMediaWipeBeforeReturning() {
func panicClearAllData_finishesMediaWipeBeforeReturning() async {
var wipeFinished = false
let (viewModel, _) = makeTestableViewModel(panicMediaWipe: {
wipeFinished = true
})
viewModel.panicClearAllData()
await viewModel.panicClearAllData()
#expect(wipeFinished)
}
@Test @MainActor
func panicClearAllData_stopsNetworkBeforeWipeAndRestartsAfterCommit() {
func panicClearAllData_stopsNetworkBeforeWipeAndRestartsAfterCommit() async {
var events: [String] = []
let lifecycle = PanicNetworkLifecycle(
stop: { events.append("stop") },
@ -2394,7 +2408,7 @@ struct ChatViewModelPanicTests {
panicNetworkLifecycle: lifecycle
)
let completed = viewModel.panicClearAllData()
let completed = await viewModel.panicClearAllData()
#expect(completed)
#expect(events == ["stop", "wipe", "restart"])
@ -2402,7 +2416,7 @@ struct ChatViewModelPanicTests {
}
@Test @MainActor
func panicKeychainFailureKeepsRecoveryPendingAndServicesStopped() {
func panicKeychainFailureKeepsRecoveryPendingAndServicesStopped() async {
let keychain = MockKeychain()
keychain.simulatedDeleteAllResult = false
var events: [String] = []
@ -2429,7 +2443,7 @@ struct ChatViewModelPanicTests {
)
let startsBeforePanic = transport.startServicesCallCount
let completed = viewModel.panicClearAllData()
let completed = await viewModel.panicClearAllData()
#expect(!completed)
#expect(events == ["stop", "begin", "wipe"])
@ -2439,7 +2453,7 @@ struct ChatViewModelPanicTests {
}
@Test @MainActor
func pendingPanicRecoveryCompletesBeforeTransportBootstrap() {
func pendingPanicRecoveryCompletesBeforeTransportBootstrap() async {
var events: [String] = []
let operations = PanicRecoveryOperations(
isPending: {
@ -2461,6 +2475,8 @@ struct ChatViewModelPanicTests {
panicRecoveryOperations: operations
)
_ = await viewModel.startupPanicRecovery?.value
#expect(events == ["read", "begin", "wipe", "complete"])
#expect(transport.emergencyDisconnectCallCount == 1)
#expect(transport.startServicesCallCount == 1)
@ -2468,7 +2484,7 @@ struct ChatViewModelPanicTests {
}
@Test @MainActor
func failedStartupRecoveryLeavesTransportAndNetworkBlocked() {
func failedStartupRecoveryLeavesTransportAndNetworkBlocked() async {
enum WipeFailure: Error { case failed }
var completedMarker = false
let operations = PanicRecoveryOperations(
@ -2487,6 +2503,8 @@ struct ChatViewModelPanicTests {
panicRecoveryOperations: operations
)
_ = await viewModel.startupPanicRecovery?.value
#expect(!completedMarker)
#expect(transport.emergencyDisconnectCallCount == 1)
#expect(transport.startServicesCallCount == 0)
@ -2494,7 +2512,7 @@ struct ChatViewModelPanicTests {
}
@Test @MainActor
func failedStartupKeychainRecoveryLeavesIntentAndTransportBlocked() {
func failedStartupKeychainRecoveryLeavesIntentAndTransportBlocked() async {
let keychain = MockKeychain()
keychain.simulatedDeleteAllResult = false
var events: [String] = []
@ -2516,6 +2534,8 @@ struct ChatViewModelPanicTests {
panicRecoveryOperations: operations
)
_ = await viewModel.startupPanicRecovery?.value
#expect(events == ["begin", "wipe"])
#expect(keychain.deleteAllCallCount == 1)
#expect(transport.emergencyDisconnectCallCount == 1)
@ -2552,7 +2572,7 @@ struct ChatViewModelPanicTests {
], for: PeerID(str: "PEER1"))
viewModel.markPrivateChatUnread(PeerID(str: "PEER1"))
viewModel.panicClearAllData()
await viewModel.panicClearAllData()
// After panic, emergency disconnect should be called
#expect(transport.emergencyDisconnectCallCount == 1)
@ -2583,7 +2603,7 @@ struct ChatViewModelPanicTests {
viewModel.geoNicknames = [pubkey: "alice"]
viewModel.teleportedGeo = [pubkey]
viewModel.panicClearAllData()
await viewModel.panicClearAllData()
#expect(viewModel.activeChannel == .mesh)
#expect(viewModel.geoSubscriptionID == nil)
@ -2597,7 +2617,7 @@ struct ChatViewModelPanicTests {
}
@Test @MainActor
func panicClearAllData_wipesTheLocationStateOfItsOwnManager() throws {
func panicClearAllData_wipesTheLocationStateOfItsOwnManager() async throws {
// Where the device has been, persisted the way the location manager
// writes it: a teleport and a bookmark.
let suiteName = "ChatViewModelPanicTests.\(UUID().uuidString)"
@ -2609,7 +2629,7 @@ struct ChatViewModelPanicTests {
#expect(locationManager.bookmarks == ["u4pruy"])
let (viewModel, _) = makeTestableViewModel(locationManager: locationManager)
viewModel.panicClearAllData()
await viewModel.panicClearAllData()
// The wipe lands on the manager the view model runs on: `.shared` in
// the app, this test's own here, which leaves the process-wide one to
@ -2631,3 +2651,234 @@ struct ChatViewModelLifecycleTests {
#expect(transport.startServicesCallCount == 1)
}
}
// Private responsiveness regression: synthetic files and mocked lifecycle/recovery.
struct PanicResponsivenessTests {
@Test(arguments: [false, true]) @MainActor
func eventQueueWaitAllowsMainActorProgressBeforeCompletion(_ cancelCaller: Bool) async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
let file = root.appendingPathComponent("events.json")
try Data("[]".utf8).write(to: file)
let queue = DispatchQueue(label: "panic.test.events")
let store = NostrProcessedEventStore(fileURL: file, ioQueue: queue)
let dedup = MessageDeduplicationService(nostrEventStore: store)
let release = DispatchSemaphore(value: 0)
queue.async { release.wait() }
// Bounded watchdog releases the synthetic slow operation even if main blocks.
var pending = false
var committed = false
var restarted = false
var heartbeatWhilePending = false
var duringWipe: () -> Void = {}
var heartbeat: Task<Void, Never>?
var wipeTask: Task<Bool, Never>?
let recovery = PanicRecoveryOperations(isPending: { false }, begin: {
pending = true
duringWipe()
return PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true)
}, wipeMedia: { _ in }, complete: { committed = true; pending = false })
let metadata = PanicMetadataWipeOperations(wipeCourier: { true }, wipeBridge: { true },
wipeGossip: { true }, wipeGroups: { true }, wipeBoard: { true }, wipeEvents: {
DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) { release.signal() }
return await dedup.clearAllAsync()
})
let (viewModel, _) = makeTestableViewModel(panicRecoveryOperations: recovery,
panicNetworkLifecycle: PanicNetworkLifecycle(stop: {}, restart: { restarted = true }),
panicMetadataWipeOperations: metadata)
duringWipe = {
heartbeat = Task { @MainActor in
try? await Task.sleep(nanoseconds: 50_000_000)
heartbeatWhilePending = pending && !committed && !restarted && !viewModel.networkActivationAllowed
if cancelCaller { wipeTask?.cancel() }
release.signal()
}
}
wipeTask = Task { @MainActor in await viewModel.panicClearAllData() }
let result = await wipeTask!.value
await heartbeat?.value
#expect(heartbeatWhilePending, "Main actor must run while queued deletion is pending")
#expect(result)
#expect(committed && restarted)
#expect(!FileManager.default.fileExists(atPath: file.path))
}
}
struct GossipPanicResponsivenessTests {
@Test(arguments: [false, true]) @MainActor
func pendingRetirementYieldsAndRejectsOverlappingPanic(_ denyEvents: Bool) async throws {
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
let file = root.appendingPathComponent("gossip.json")
let queue = DispatchQueue(label: "panic.test.gossip")
let archive = GossipMessageArchive(fileURL: file)
let manager = GossipSyncManager(myPeerID: PeerID(str: "1122334455667788"),
requestSyncManager: RequestSyncManager(), archive: archive, queue: queue)
let release = DispatchSemaphore(value: 0)
queue.async { release.wait(); archive.save([Data("synthetic queued save".utf8)]) }
let keychain = MockKeychain()
let idBridge = NostrIdentityBridge(keychain: MockKeychainHelper())
let identityManager = MockIdentityManager(keychain)
let transport = BLEService(keychain: keychain, idBridge: idBridge,
identityManager: identityManager, initializeBluetoothManagers: false)
var pending = false
var begins = 0
var commits = 0
var mediaAttempts = 0
var deny = denyEvents
let recovery = PanicRecoveryOperations(isPending: { false }, begin: {
begins += 1; pending = true
DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) { release.signal() }
return PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true)
}, wipeMedia: { _ in mediaAttempts += 1 }, complete: { commits += 1; pending = false })
let metadata = PanicMetadataWipeOperations(wipeCourier: { true }, wipeBridge: { true },
wipeGossip: { archive.wipe() }, wipeGroups: { true }, wipeBoard: { true }, wipeEvents: { !deny })
let viewModel = ChatViewModel(keychain: keychain, idBridge: idBridge,
identityManager: identityManager, transport: transport,
panicRecoveryOperations: recovery, panicMetadataWipeOperations: metadata)
transport._test_replaceGossipManager(manager)
defer { transport.suspendForPanicReset() }
let buffered = BitchatMessage(sender: "synthetic", content: "buffered before wipe", timestamp: Date(), isRelay: false)
viewModel.handlePublicMessage(buffered)
#expect(viewModel.publicMessagePipeline.containsMessage(withID: buffered.id))
let chrome = AppChromeModel(chatViewModel: viewModel,
privateInboxModel: PrivateInboxModel(conversations: viewModel.conversations))
let recipient = try NostrIdentity.generate()
let sender = try NostrIdentity.generate()
let embedded = try #require(NostrEmbeddedBitChat.encodePMForNostrNoRecipient(
content: "old mailbox plaintext", messageID: "old-mailbox"))
let giftWrap = try NostrProtocol.createPrivateMessage(content: embedded,
recipientPubkey: recipient.publicKeyHex, senderIdentity: sender)
let mailboxTask = viewModel.nostrCoordinator.inbound.handleNostrMessage(giftWrap)
let heartbeat = Task { @MainActor in
try? await Task.sleep(nanoseconds: 50_000_000)
#expect(pending && transport.radioIsPanicSuspended())
#expect(!viewModel.networkActivationAllowed)
#expect(!(await viewModel.panicClearAllData()), "Overlapping panic must not begin another transaction")
#expect(begins == 1)
// The pre-panic task reaches identity acquisition while retirement
// remains pending. It must not add an event ID to the new generation.
await mailboxTask?.value
#expect(!viewModel.hasProcessedNostrEvent(giftWrap.id))
release.signal()
#expect(!viewModel.publicMessagePipeline.containsMessage(withID: buffered.id))
viewModel.publicMessagePipeline.flushIfNeeded()
#expect(!viewModel.messages.contains(where: { $0.id == buffered.id }))
let late = BitchatMessage(sender: "synthetic", content: "during wipe", timestamp: Date(), isRelay: false)
viewModel.handlePublicMessage(late)
#expect(!viewModel.publicMessagePipeline.containsMessage(withID: late.id))
#expect(!viewModel.messages.contains(where: { $0.id == late.id }), "Pending wipe must reject inbound state")
viewModel.sendMessage("during wipe")
#expect(!viewModel.messages.contains(where: { $0.content == "during wipe" }), "Pending wipe must reject user sends")
}
chrome.panicClearAllData()
// No actor yield between confirmation and these boundary assertions.
#expect(pending && begins == 1)
#expect(transport.radioIsPanicSuspended())
#expect(!viewModel.networkActivationAllowed && chrome.panicInProgress)
await chrome.panicTask?.value
await heartbeat.value
#expect(!chrome.panicInProgress)
#expect(mediaAttempts == 1)
#expect(!FileManager.default.fileExists(atPath: file.path), "Delete must follow queued save")
#expect(pending == denyEvents)
#expect(commits == (denyEvents ? 0 : 1))
#expect(transport.radioIsPanicSuspended() == denyEvents)
manager.persistNow()
_ = manager._messageCount(for: PeerID(str: "1122334455667788"))
#expect(!FileManager.default.fileExists(atPath: file.path), "Retired owner must not recreate the archive")
if denyEvents {
deny = false
#expect(await viewModel.panicClearAllData())
#expect(!pending && commits == 1 && !transport.radioIsPanicSuspended())
}
let fresh = BitchatMessage(sender: "synthetic", content: "new after recovery", timestamp: Date(), isRelay: false)
viewModel.handlePublicMessage(fresh)
viewModel.publicMessagePipeline.flushIfNeeded()
#expect(viewModel.messages.contains(where: { $0.id == fresh.id }))
}
}
@Suite(.serialized)
struct PanicTaskBoundaryTests {
@Test(arguments: [false, true]) @MainActor
func queuedRelayCallbackCannotAdoptPostPanicGeneration(_ resubscribing: Bool) async throws {
let recovery = PanicRecoveryOperations(isPending: { false }, begin: {
PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true)
}, wipeMedia: { _ in }, complete: {})
let metadata = PanicMetadataWipeOperations(wipeCourier: { true }, wipeBridge: { true },
wipeGossip: { true }, wipeGroups: { true }, wipeBoard: { true }, wipeEvents: { true })
let suiteName = "PanicTaskBoundaryTests.\(UUID().uuidString)"
let storage = try #require(UserDefaults(suiteName: suiteName))
defer { storage.removePersistentDomain(forName: suiteName) }
let (viewModel, _) = makeTestableViewModel(panicRecoveryOperations: recovery,
panicMetadataWipeOperations: metadata, locationManager: LocationChannelManager(storage: storage))
let recipient = try NostrIdentity.generate()
let sender = try NostrIdentity.generate()
let embedded = try #require(NostrEmbeddedBitChat.encodePMForNostrNoRecipient(
content: "synthetic old relay callback", messageID: "old-callback"))
let event = try NostrProtocol.createPrivateMessage(content: embedded,
recipientPubkey: recipient.publicKeyHex, senderIdentity: sender)
var callbacks: [@MainActor () async -> Void] = []
let subscriptions = viewModel.nostrCoordinator.subscriptions
subscriptions.relayCallbackScheduler = { callbacks.append($0) }
let handler = subscriptions.giftWrapHandler(identity: recipient, resubscribing: resubscribing)
handler(event)
#expect(callbacks.count == 1)
#expect(await viewModel.panicClearAllData())
// Model an already-enqueued outer callback not scheduled until after
// recovery. It must not acquire the pipeline's new wipe generation.
let oldCallback = callbacks.removeFirst()
await oldCallback()
#expect(!viewModel.hasProcessedNostrEvent(event.id))
let oldMessages = viewModel.conversations.conversationsByID.values.flatMap(\.messages)
#expect(!oldMessages.contains { $0.content == "synthetic old relay callback" })
// A new registration after recovery can deliver the same test event.
let freshHandler = subscriptions.giftWrapHandler(identity: recipient, resubscribing: resubscribing)
freshHandler(event)
await callbacks.removeFirst()()
let freshMessages = viewModel.conversations.conversationsByID.values.flatMap(\.messages)
#expect(freshMessages.contains { $0.content == "synthetic old relay callback" })
}
@Test @MainActor
func pendingGeohashSendCannotRestoreClearedConversation() async throws {
var releaseCleanup: CheckedContinuation<Bool, Never>?
let recovery = PanicRecoveryOperations(isPending: { false }, begin: {
PanicRecoveryIntent(fileMarkerEstablished: true, externalMarkerEstablished: true)
}, wipeMedia: { _ in }, complete: {})
let metadata = PanicMetadataWipeOperations(wipeCourier: { true }, wipeBridge: { true },
wipeGossip: { true }, wipeGroups: { true }, wipeBoard: { true }, wipeEvents: {
await withCheckedContinuation { releaseCleanup = $0 }
})
let suiteName = "PanicTaskBoundaryTests.\(UUID().uuidString)"
let storage = try #require(UserDefaults(suiteName: suiteName))
defer { storage.removePersistentDomain(forName: suiteName) }
let (viewModel, _) = makeTestableViewModel(panicRecoveryOperations: recovery,
panicMetadataWipeOperations: metadata, locationManager: LocationChannelManager(storage: storage))
let channel = GeohashChannel(level: .city, geohash: "u4pruydq")
viewModel.activeChannel = .location(channel)
viewModel.sendMessage("synthetic pre-panic send")
let send = try #require(viewModel.outgoingCoordinator.geohashMiningTask)
// Begin panic without yielding to the outgoing task. Mining and its
// continuation then run while the controller waits for cleanup.
let wipe = try #require(viewModel.beginPanicClearAllData())
await send.value
for _ in 0..<100 where releaseCleanup == nil { await Task.yield() }
let release = try #require(releaseCleanup)
let retained = viewModel.conversations.conversationsByID[.geohash(channel.geohash)]?.messages ?? []
#expect(!retained.contains { $0.content == "synthetic pre-panic send" })
#expect(!viewModel.networkActivationAllowed)
release.resume(returning: true)
#expect(await wipe.value)
// A fresh outgoing task after successful recovery must still work.
viewModel.activeChannel = .location(channel)
viewModel.sendMessage("synthetic fresh send")
await viewModel.outgoingCoordinator.geohashMiningTask?.value
let fresh = viewModel.conversations.conversationsByID[.geohash(channel.geohash)]?.messages ?? []
#expect(fresh.contains { $0.content == "synthetic fresh send" })
}
}

View File

@ -334,7 +334,7 @@ struct ConversationUIModelTests {
// The wipe reseeds every geohash identity and returns to the mesh,
// which takes the retired key out of the memo too.
viewModel.panicClearAllData()
await viewModel.panicClearAllData()
#expect(await TestHelpers.waitUntil({ uiModel.ownGeoChatSender == nil }, timeout: TestConstants.settleTimeout))
Self.show(geohash: Self.geohash, in: viewModel)
let newHex = try Self.myGeoHex(viewModel)

View File

@ -649,6 +649,7 @@ private struct SeededGenerator: RandomNumberGenerator {
/// the coordinator's own pipeline.
@MainActor
private final class PerfNostrContext: ChatNostrContext {
var networkActivationAllowed: Bool { true }
var activeChannel: ChannelID = .location(GeohashChannel(level: .neighborhood, geohash: "u4pruyd"))
var currentGeohash: String? = "u4pruyd"
var geoSubscriptionID: String?